This is an old revision of the document!
python
prepare
get python
settings
- Editors
- Visual Studio Code
- Vim
SublimetextpyCharm
$ python3 hello_world.py
variables and types
- 변수 이름은 snake_case로
- 문자열은 “This is a string”, 'This is also a string.' 모두 가능
- {string_variable}.title() → 첫 글자 대문자로
- {string_variable}.upeer()
- {string_variable}.lower()
- f-string
- full_name = f“{first_name} {last_name}”
- full_name = “{} {}”.format(fist_name, last_name)
- escape characters; \', \\, \n, \r, \t, \b, \f, \ooo, \xhh
- {string_variable}.rstrip() → 오른쪽 공백 삭제, .strip() → 양쪽 공백 제거, .lstrip() → 왼쪽 공백 제거
- numeric; integer, floating point number, underscored number → 15_000_000_000
- 상수는 대문자로; MAX_CONNECTIONS = 5000
- comments; #
message = "Hello Python" print(message)
>>> import this
list
- 대괄호 []와 콤마 ,
- 이름을 복수형으로
- 인덱스는 0부터, [-1]은 끝에서부터의 인덱스
bicycles = ['trek', 'cannondale', 'redline', 'specialized']
print(bicycles)
print(bicycles[0])
print(bicycles[0].title())
bicycles[0] = 'mini bell' # change value
bicycles.append('trek') # append value
bicycles.insert(0, 'strida') # insert value
del bicycles[0] # delete
popped_bicycle = bicycles.pop() # pop value (stack)
#popped_bicycle = bicycles.pop(0) # pop value by index
bicycles.remove('redline') # remove by value
bicycles.sort() # sort permanently by alphabet
bicycles.sort(reverse=True) # reverse sort
print(sorted(bicycles)) # sort temporarily
bicycles.reverse() #
len(bicycles)
list handling
magicians = ['alice', 'david', 'carolina']
for magician in magicians:
print(magician)
for value in range(1, 5): # 1 ~ 4
print(value)
numbers = list(range(1, 6)) # numbers = [1, 2, 3, 4, 5]
even_numbers = list(range(2, 11, 2)) # even_numbers = [2, 4, 6, 8, 10]
squares = []
for value in range(1, 11):
square = value ** 2
squares.appen(square)
# squares = [value ** 2 for value in range(1,11)]
print(squares)
digits = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0]
min(digits)
max(digits)
sum(digits)
- slice; 원래 리스트 유지
- players[0:3] # index 0에서부터 3개까지 자름 [:3]
- players[2:] # index 2부터 끝까지
- players[-3:] # 끝에서 셋
- 복사
- my_friends = your_friends[:]
- my_friends = your_friends는 포인터 같은 역할
- tuple(immutable)
- 대괄호 대신 소괄호 ()와 콤마 ,
- 한 개 항목의 튜플이더라도 콤마 필요; my_t = (3,)
- Coding style; PEP(Python Enhancement Proposal) 8
- 들여쓰기 공백 네 칸
- 행 길이 79자
if state
cars = ['audi', 'bmw', 'subaru', 'toyota']
for car in cars:
if car == 'bmw':
print(car.upper())
else:
print(car.title())
- == ; equals to
- != ; not equals
- <, ⇐, >, >=
- and, or
- in; 'mushrooms' in requested_toppings
- not in;
- boolean expression; True, False
- if, if-else, if-elif-else
if age < 4: # GOOD if age<4: #bad
dictionary
- key-value pair
- 중괄호 {}
alien_0 = {'color': 'green', 'points': 5}
print(alien_0['color'])
print(alien_0['points'])
alien_0['x_position'] = 0
alien_0['y_position'] = 25
dict_0 = {} # 빈 값으로 딕셔너리 선언
del alien_0['points'] # points key 제거
favorite_languages = {
'jen': 'python',
'sarah': 'c',
'edward': 'ruby',
'phil': 'python',
}
point_value = alien_0.get('points', 'No point value assigned.') # key가 없을 경우의 default 값을 지정하여 error 방지
user_0 = {
'username': 'efermi',
'first': 'enrico',
'last': 'fermi',
}
for key, value in user_0.items():
print(f"\nKey: {key}")
print(f"Value: {value}")
for name in favorite_languages.key():
print(name.title())
for language in favorite_languages.values():
print(language.title())
for language in set(favorite_languages.values()): # set는 중복을 제거한 고유한 데이터 형식
print(language.title())
- nesting
- 딕셔너리 안에 리스트, 리스트 안에 딕셔너리, 딕셔너리 안에 딕셔너리…