함수 정의 시 parameter라고 부름
def my_func(a, b):
pass
x = 1
y = "a"
my_func(x, y)
a = 1,2,3
print(a)
print(type(a))
(1, 2, 3)
<class 'tuple'>
a,b,c = [1,2,3]
print(a,b,c)
a,b,c = 10, 20, "hello"
print(a,b,c)
a,b,c = "XYZ"
print(a,b,c)
1 2 3
10 20 hello
X Y Z
1
2
3
4
5
l = [1,2,3,4,5,6]
1)
a = l[0]
b = [1:]
2)
a, b = l[0], l[1:]
3)
a, *b = l
a, *b, c = [1,2,3,4,5]
print(a,b,c)
a = [1,2,3]
b = [4,5,6]
c = [*a, *b]
print(c)
a = {"p": 1, "y": 2, "z": 10}
b = {"t": 3, "h": 4, "z": 50}
c = {**a, **b}
print(c) # b의 z가 a의 z를 overwrote함을 주의하라.
d1 = {"a": 1, "b": 2}
print({"a": 10, **d1})
a, *b, (c, *d) = [1,2,3, "python"]
print(a,b,c,d)
1 [2, 3, 4] 5
[1, 2, 3, 4, 5, 6]
{'p': 1, 'y': 2, 'z': 50, 't': 3, 'h': 4}
{'a': 1, 'b': 2}
1 [2, 3] p ['y', 't', 'h', 'o', 'n']
a, b, c = [1,2,3,4,5] 는 에러!
*
indicates the "end" of positional argumentsdef my_func(*, b):
pass
from datetime import datetime
from time import sleep
def main(t=datetime.now()):
print(t)
main()
sleep(3)
main()
2022-02-11 17:55:09.028305
2022-02-11 17:55:09.028305
from datetime import datetime
from time import sleep
def main(t=None):
t = t or datetime.now()
print(t)
main()
sleep(3)
main()
2022-02-11 17:57:52.713788
2022-02-11 17:57:55.719404
def main(a, li=[]):
li.append(a)
return li
res1 = main(1)
print(res1)
res2 = main(3)
print(res2)
print(res1)
print(res1 is res2)
[1]
[1, 3]
[1, 3]
True
# 해결책
def main(a, li=None):
li = li or []
li.append(a)
return li
# 의도적으로 함수 param에 mutable을 줄 때도 있다.
# cache를 반복적으로 쓰려면 아래처럼 해야함.
def factorial(n, cache={}):
if n < 1:
return 1
elif n in cache:
return cache[n]
else:
print("calculate")
res = n * factorial(n-1)
cache[n] = res
return res
res = factorial(3)
print(res)
res = factorial(3)
print(res)
calculate
calculate
calculate
6
6