for i, person in enumerate(people):
name = person['name']
age = person['age']
print(i, name, age)
if 2 < i:
breakfor s in scores:
name = s['name']
score = str(s['score'])
print(f'{name}의 점수는 {score}점입니다.') # f를 넣으면 f-string으로 변함for person in people:
try: # 일단 실행하는데
if 20 < person['age']:
print(person['name']
except: # 에러가 나면 이걸 실행해라
print('에러입니다.')from main_func import * # main_func에 있는 함수들을 전부* 불러온다.result = ('짝수' if num % 2 == 0 else '홀수')b_list = [a * 2 for a in a_list] # List Comprehsnsiondef check_adult(person):
return ('성인' if 20 < person['age'] else '청소년')
# map : people을 돌면서 check_adult하고, 그 return값으로 list를 만든다.
result = map(check_adult, people)
# lambda식 : 한줄짜리 함수를 뭐하러 만드냐, 그냥 lambda식 쓰자.
# people을 돌면서 그 값을 x에 넣고, lambda식 동작결과로 list를 만든다.
result = map(lambda x: ('성인' if 20 < x['age'] else '청소년'), people )
# filter : map과 유사하지만, True인 것들만 뽑아오는 것.
result = filter(lambda x: 20 < x['age'], people)
print(list(result)) # list 씌워야 진짜 리스트 완성def cal(a, b = 2): # b에 값이 안들어오면 2가 기본값
return a + 2 * b
result = cal(b = 2, a = 1) # 매개변수 순서 맘대로 가능
def cal(*args): # 변수를 리스트 형태로 무제한으로 받음
for name in args:
print(f'{name}야 밥먹어라~')
# 라이브러리 등에서 많이 쓰임
def cal(**kwargs): # 변수를 딕셔너리 형태로 무제한으로 받음
print(kwargs)
cal(name = 'bob', age = 30, height = 100)
물체마다 관련된 속성을 넣어둔다.
그것을 컨트롤 할 수 있는 함수도 만들어준다.
중앙에서는 그 함수만 불러서 물체를 제어한다.
class Monster():
hp = 100 # self.hp
alive = true
def damage(self, attack):
self.hp = self.hp - attack
if self.hp < 0:
self.alive = False
def status_check(self):
if self.alive:
print('살았다!')
else:
print('죽었다!')
m1 = Monster() # 인스턴스 생성
m1.damage(150)
m1.status_check() # 죽었다!
m1 = Monster()
m1.damage(90)
m1.status_check() # 살았다!