파이썬 return과 print의 차이점

서현·2024년 8월 6일
0

파이썬

목록 보기
4/19

return값이 print와 헷갈리는 경우가 많아 작성해보겠습니다

return

여러 개의 retrurn을 하나의 변수로 받는 경우 튜플로 표현됨

print

말그대로 출력값을 확인할 수 있는 함수를 말함

1) return값이 있는 경우


def hello(hello_to):
  return "hello" + hello_to

hello("world") #출력 : 
print(hello("world")) #출력 : helloworld

2)print가 있는 경우

def hello(hello_to):
  print("hello" + hello_to)

hello("world") 
#출력 : 
#helloworld
print(hello("world"))
#출력
#helloworld
#None

3) return과 print가 같이 있는 경우

def hello(hello_to):
  print("haha")
  return "hello" + hello_to

hello("world") #haha
print(hello("world")) 
#haha
#helloworld

해설

return값이 있는 경우 눈에 보이지는 않지만 값을 출력하기 전에 return값으로 돌아가는데요
아래 1)번의 식을 참고하여 말씀드리자면

5번줄과 같이 hello함수를 호출한 경우 2번 hello함수로 돌아가서 return값을 가져오게 됩니다. 출력되지 않아 눈으로 확인하기어렵지만 6번줄처럼 출력값을 확인해보면 return으로 가져온 helloworld를 출력할 수 있습니다.

하지만 return이 없고 print만 있는 경우,

첫번째로 출력된 helloworld는 hello함수 내에서 바로 출력된 값이고,
두번째로 출력된 helloworld는 6번줄에 있는 print때문에 출력된 값입니다.

여기서 아래의 None은 왜 출력된 것일까요?
함수 내에 return값이 없다면 None을 출력합니다. hello함수 내에도 return값이 존재하지 않아서 None이 같이 출력된 것입니다.

profile
서현이의 코드 생활 ദ്ദി ( ᵔ ᗜ ᵔ )

0개의 댓글