def factorial(n):
if n ==0:
return 1
else:
return n * factorial(n-1)
# 재귀함수로 피보나치 수열
def fibonacci(n):
if n == 1:
return 1
if n == 2:
return 1
else:
return fibonacci(n-1) + fibonacci(n-2)
global 변수이름
전역 변수로 사용하기 위한 키워드
딕셔너리를 사용해서 한 번 계산한 값을 저장하는 것
# 메모 변수를 만듦
dictionary = {
1: 1,
2: 1
}
def fibonacci(n):
if n in dictionary:
# 메모가 되어 있으면 메모된 값을 리턴
return dictionary[n]
else:
# 메모가 되어 있지 않으면 값을 구힘
output = fibonacci(n-1) + fiboanacci(n-2)
dictionary[n] = output
return output
리스트와 비슷한 자료형으로, 리스트와 다른 점은 한번 결정된 요소는 바꿀 수 없다는 것
괄호를 생략해도 튜플로 인식할 수 있는 경우 괄호 생략 가능
tuple_test = (10, 20, 30)
tuple_test[0] # 10
tuple_test[1] # 20
tuple_test[2] # 30
# 요소를 하나만 가지는 튜플 선언
(273, )
매개변수로 함수를 전달하기 위해 함수 구문을 작성하는 것이 번거롭고, 코드 공간 낭비라는 생각이 들 때 함수를 간단하고 쉽게 선언하는 방법
lambda 매개변수 : 리턴값
# 매개변수로 받은 함수를 10번 호출하는 함수
def call_10_times(func):
for i in range(10):
func()
# 간단한 출력하는 함수
def print_hello():
print("안녕하세요")
# 조합하기
call 10_times(print_hello)
map(함수, 리스트)
filter(함수, 리스트)
def power(item):
return item * item
def under_3(item):
return item < 3
list_input_a = [1, 2, 3, 4, 5]
# map() 함수 사용
output_a = map(power, list_input_a)
print("map(power, list_input_a) :", list(output_a))
# [1, 4, ,9, 16, 25]
# filter() 함수 사용
output_b = filter(under_3, list_input_a)
print("filter(under_3, list_input_a): ", list(output_b))
# [1, 2]
📍 람다로 변경하면
# def 키워드를 lambda로 바꾸고 return 키워드 삭제
power = lambda x: x * x
under_3: lambda x: x < 3
list_input_a = [1, 2, 3, 4, 5]
# map() 함수 사용
output_a = map(power, list_input_a)
#output_a = map(lambda x: x * x, list_input_a)
print("map(power, list_input_a) :", list(output_a))
# [1, 4, ,9, 16, 25]
# filter() 함수 사용
output_b = filter(under_3, list_input_a)
#output_b = filter(lambda x: x < 3, list_input_a)
print("filter(under_3, list_input_a): ", list(output_b))
# [1, 2]
파일 열 때
파일 객체 = open(문자열: 파일 경로, 문자열:읽기 모드)
파일 닫을 때
파일 객체.close()
모드 | 설명 |
---|---|
w | write (새로 쓰기) |
a | append (뒤에 이어서 쓰기 모드) |
r | read (읽기 모드) |
with 구문이 종료될 때 자동으로 파일이 닫힘
with open(문자열 : 파일 경로, 문자열: 모드) as 파일 객체: 문장