for 문:
list
(혹은 다른 자료 구조)의 요소를 한번에 하나씩 가지고 원하는 로직을 실행할 수 있게 해준다for element in list: do_something_with_element
break:for
문을 끝까지 진행할 필요 없이 중간에서 멈추고 싶을 때 사용
continue:for
문에서 완전히 빠져 나오고 싶지는 않지만 다음 요소, 즉 다음 iteration으로 넘어가고 싶을 때 사용
range: 시작조건, 종료조건, 스텝(생략 가능)을 쓸 수 있다for in range(start_value, end_value, step)
step을 사용해서 반복문의 증가 폭을 조절할 수 있고 거꾸로도 수행할 수 있다
while 문: 특정 조건문이 True 일동안 코드블록을 반복 실행한다
while <조건문>: <수행할 문장>
Break & Continue:for
문과 동일하게 사용
else:while
의 조건문이False
이면 실행된다while <조건문>: <수행할 문장> else: <while문이 종료된 후 수행할 문장>
dictionary를 사용한 for문: 각 요소의
key
만return
한다for each_key in dict_name: print(f"{each_key} : {dict_name[each_key]}) # {each_key} = key, {dict_name[each_key]}) = value
value 값으로 looping:values()
함수 사용,dictionary
의value
들을list
의 형태로return
해준다for each_value in dict_name.values(): print(f"{each_value}) # {each_values} = value
key와 value 값 모두 사용:items()
함수를 사용,key
와value
를tuple
로return
해준다for each_key, each_value in dict_name.items(): print(f"{each_key} : {each_value) # {each_key} = key, {each_value}) = value
**kwargs
: 그 수가 정해지지 않고 유동적으로 변할 수 있는keyword arguments
선언 하기 위해서는parameter
이름앞에 두개의 별표**
로 시작해야한다
일반적인 keyword arguments와의 차이점:
1.Argument
수를 0부터 N까지 유동적으로 넘겨줄 수 있다
2.Keyword
가 미리 정해져 있지 않기때문에 원하는keyword
를 유동적으로 사용할 수 있다
3.Keyworded variable length of arguments
는dictionary
형태로 지정된다
*args
:keyword
를 사용하지 않고 순서대로 값을 전달하는 방식
variable arguments
는tuple
로 변환되어 함수에 전달된다
중첩함수(nested function): 상위 부모 함수 안에서만 호출 가능
중첩함수를 사용하는 이유:
1. 가독성 : 부모함수의 코드를 효과적으로 관리하고 가독성을 높일 수 있다
2. Closure : 중첩 함수를 통해서 격리된 부모함수의 변수를 사용한 연산을 가능하게 해준다
Closure 예시
숫자의 수(數) 을 구하는 함수def calculate_power(number, power): return number ** power calculate_power(2, 7) # 128
2의 승을 구하는 함수
def calculate_power_of_two(power): return 2 ** power calculate_power_of_two(7) # 128
설정되는 수의 승을 구하는 함수 → closure를 사용
def generate_power(base_number): def nth_power(power): return base_number ** power return nth_power calculate_power_of_two = generate_power(2) calculate_power_of_two(7) # 128 calculate_power_of_seven = generate_power(7) calculate_power_of_seven(3) # 343