본문 바로가기

Python_Beginer/Study

Python Variable Arguments(가변 길이 함수) - args

반응형

1. 가변 길이 함수

- Parameter(파라미터) 갯수가 정해지지 않을 때 사용

- 함수를 호출 할 때 Arguments(아규먼트)의 갯수가 변할 수 있을 때 사용

- *(애스터리스크) 사용


2. 기본 구조

def 함수명(*args):
명령어
return


3. Sample Code

- 더하기 함수 정의

def do_sum(*args):
total = 0
for x in args:
total += x

return total

- 더하기 함수 호출

print(do_sum(1))
print(do_sum(1, 2))
print(do_sum(1, 2, 3))
print(do_sum(1, 2, 3, 4))
print('-' * 10)

1

3

6

10

----------


Process finished with exit code 0


- 더하기 곱셈 함수 정의(if ~ elif / for 문 사용)

def do_calc(op, *args):
if op == '+':
total = 0
for x in args:
total += x
return total

elif op == '*':
total = 1
for x in args:
total *= x
return total

else:
return '연산은 + 또는 *만 가능합니다.'

- 더하기 곱셈 함수 호출

print(do_calc('+', 1))
print(do_calc('+', 1, 2, 3, 4, 5))
print(do_calc('*', 1))
print(do_calc('*', 1, 2, 3, 4, 5))
print(do_calc('-', 2))
print('-' * 10)

1

15

1

120

연산은 + 또는 *만 가능합니다.

----------


Process finished with exit code 0

반응형