본문 바로가기
Study/Python

[Python] 함수

by YoungD 2023. 10. 12.

함수

 

def 함수명(매개변수):실행문장return 반환변수 -> 호출했던 곳으로 감
In [1]:
def number_sum(num1, num2):
    r = num1 + num2
    return r
# 함수 정의 후 실행 시켰는지 확인하기
In [2]:
print(number_sum(2,3))
5

#

  • 실습문제
In [3]:
def cal(num1, num2, op='+') : # op='+' 매개변수 op의 기본값을 + 로 설정
    """덧셈과 뺄셈을 계산하는 함수""" # docstring 추가하기
    if op == '+' :
        result = num1 + num2
        return result
    elif op == '-' :
        result = num1 - num2
        return result
    else :
        return '연산기호 입력 에러'
In [4]:
num1 = int(input('첫 번째 정수 입력 >> '))
num2 = int(input('두 번째 정수 입력 >> '))
op = input('연산자 입력(+,-) >> ')
result = cal(num1, num2, op)
print('결과 : {}'.format(result))
첫 번째 정수 입력 >> 5
두 번째 정수 입력 >> 9
연산자 입력(+,-) >> +
결과 : 14
In [5]:
cal(1,2) # 매개변수 op 의 기본값 + 적용
Out[5]:
3
In [6]:
cal(1, 2, '-')
Out[6]:
-1
In [7]:
print(cal(7,op='-'))
print(cal(8))

print(cal('A','B'))
 

가변매개변수

In [8]:
def add(*args) :
    total = 0
    for n in args :
        total += n
    return total
In [9]:
print(add(1, 2, 3))
print(add(4, 5, 6, 7, 8, 9, 10))
6
49
In [10]:
def add(num, *args) :
    total = 0
    for n in args :
        total += n
    return total
In [11]:
print(add(1, 2, 3))
print(add(4, 5, 6, 7))
5
18
In [12]:
# return 키워드는 한 번만 사용 가능하다.

def add_sub(n1, n2) :
        return n1+n2, n1-n2, "더하기 빼기 결과"
In [13]:
ar, sr, str1 add_sub(3,9)

print(ar)
print(sr)
print(str1)
  Cell In[13], line 1
    ar, sr, str1 add_sub(3,9)
                 ^
SyntaxError: invalid syntax
In [14]:
a, b, c = [1, 2, 3]

'Study > Python' 카테고리의 다른 글

[Python] Matplotlib  (0) 2023.10.16
[Python] pandas라이브러리 CrimeData 실습  (0) 2023.10.13
[Python] 딕셔너리  (0) 2023.10.11
[Python] 반복문  (2) 2023.10.07
[Python] 리스트, 튜플  (0) 2023.10.06