Python

[Python]함수(Function)

sagesse2021 2021. 11. 18. 16:09
반응형

//int ( ) function 사용해서 string변수 정수로 변환하기

age = "18"
print(age)
print(type(age))

n_age= int(age)
print(n_age)
print(type(n_age))

18

<class 'str'>

18

<class 'int'>

 

//function정의하기

def say_hello():
  print("hello")
  print("bye")

say_hello()

hello

bye

  • 파이썬에서는 indentation(들여쓰기)로 function의 시작과 끝을 판단(중괄호를 쓰지 않음)
  • 들여쓰기로 function의 안(body)이라는 것을 표시 할 수 있다
  • function의 이름 뒤에 ( )를 추가하면 function을 실행 하는 것(say_hello를 출력)
  • function의 body는 들여쓰기로 구분되어야 한다

// function에 인자 who를 넣어주고 실행하기

def say_hello( who):
  print("hello", who)
  
say_hello("Jihye")

hello Jihye

def plus(a, b):
  print(a+b)

def minus(a, b):
  print(a-b)

plus(2,5)
minus(2,5)

7

-3

def plus(a, b):
  print(a+b)

def minus(a, b=0):
  print(a-b)

plus(2,5)
minus(2)

7

2

  • minus function을 호출하려고 하는데 인자b를 전달하지 않으면 print(a-b)는 작동하지 x, 이런 경우 default값을 추가할 수 있다(b에 0을 기본값으로 줌)

// say_hello function정의하고 외부에서 input 가져오기

def say_hello(name="anonymous"):
  print("hello", name)

say_hello()
say_hello("Coco")
  • 인자 없이 function을 호출하는 경우 function을 정의하는 부분에서 default값을 지정해야 함

hello anonymous

hello Coco

반응형

'Python' 카테고리의 다른 글

[Python]Keyworded Arguments  (0) 2021.11.19
[Python]return  (0) 2021.11.18
[Python]튜플과 딕셔너리(Tuple and Dictionary)  (0) 2021.11.18
[Python]리스트(Lists)  (0) 2021.11.17
[Python]데이터 타입(Data types)  (0) 2021.11.17