Python
[Python] ν¨μ - μ λ ₯κ°μ΄ λͺ κ°κ° λ μ§ λͺ¨λ₯Ό λ
μ½λ©νλ λΆμ΄
2021. 3. 20. 01:44
λ°μν
νμ΄μ¬μ μ΄λ° λ¬Έμ λ₯Ό ν΄κ²°νκΈ° μν΄ λ€μκ³Ό κ°μ λ°©λ²μ μ 곡νλ€.
def ν¨μμ΄λ¦(*λ§€κ°λ³μ):
μνν λ¬Έμ₯
...
-μ¬λ¬ κ°μ μ λ ₯κ°μ λ°λ ν¨μ λ§λ€κΈ°
>>> def add_many(*args):
... result = 0
... for i in args:
... result = result + i # *argsμ μ
λ ₯λ°μ λͺ¨λ κ°μ λνλ€
... return result
...
>>>
*μ¬κΈ°μ *argsλ μμλ‘ μ ν λ³μ μ΄λ¦μ΄λ€.
*argsμ²λΌ λ§€κ°λ³μ μ΄λ¦ μμ *μ λΆμ΄λ©΄ μ λ ₯κ°μ μ λΆ λͺ¨μμ ννλ‘ λ§λ€μ΄ μ€λ€.
<ν¨μλ₯Ό μ μ©ν κ²>
>>> result = add_many(1,2,3) # add_many ν¨μμ κ²°κ΄κ°μ result λ³μμ λμ
>>> print(result)
6
>>> result = add_many(1,2,3,4,5,6,7,8,9,10)
>>> print(result)
55
μ¬λ¬ κ°μ μ λ ₯μ μ²λ¦¬ν λ def add_many(*args)μ²λΌ ν¨μμ λ§€κ°λ³μλ‘ *argsλ§ μ¬μ©ν μ μλ κ²μ μλλ€.
>>> def add_mul(choice, *args):
... if choice == "add": # λ§€κ°λ³μ choicedp 'add'λ₯Ό μ
λ ₯λ°μμ λ
... result = 0
... for i in args:
... result = result + i # argsμ μ
λ ₯λ°μ λͺ¨λ κ°μ λνλ€
... elif choice == "mul": # λ§€κ°λ³μ choicedp 'mul'μ μ
λ ₯λ°μμ λ
... result = 1
... for i in args:
... result = result * i # *argsμ μ
λ ₯λ°μ λͺ¨λ κ°μ κ³±νλ€
... return result
...
>>>
>>> result = add_mul('add', 1,2,3,4,5)
>>> print(result)
15
>>> result = add_mul('mul', 1,2,3,4,5)
>>> print(result)
120
λ§€κ°λ³μ choiceμ 'add'κ° μ λ ₯λ κ²½μ° *argsμ μ λ ₯λλ λͺ¨λ κ°μ λν΄μ 15λ₯Ό λλ €μ£Όκ³ ,
'mul'μ΄ μ λ ₯λ κ²½μ° *argsμ μ λ ₯λλ λͺ¨λ κ°μ κ³±ν΄μ 120μ λλ €μ€λ€.
λ°μν