여러 값을 반환하는 함수
이전 연습 문제에서는 튜플을 만들고, 변수에 할당하고, 언팩하는 방법을 연습했어요. 이번에는 함수가 튜플을 사용해 여러 값을 반환하도록 해 보겠습니다. shout() 함수를 업데이트해 하나의 문자열만 반환하는 대신, 각 문자열에 !!!를 붙인 두 개의 문자열을 반환하도록 하겠습니다.
return x, y는 return (x, y)와 같은 결과를 낸다는 점에 유의하세요. 실제로 전자는 내부적으로 x와 y를 튜플로 포장해 반환합니다!
이 연습은 강의의 일부입니다
Python 함수 입문
연습 안내
- 함수 헤더를 수정해 함수 이름을
shout_all로 바꾸고, 순서대로word1,word2두 매개변수를 받도록 하세요. word1과word2각각에 문자열'!!!'를 이어 붙여서shout1,shout2에 할당하세요.shout1과shout2로 구성된 튜플shout_words를 만드세요.- 문자열
'congratulations'와'you'로shout_all()을 호출하고, 결과를yell1,yell2에 할당하세요(shout_all()은 2개의 값을 반환합니다!).
실습형 인터랙티브 연습
이 예제를 이 샘플 코드를 완성하여 풀어보세요.
# Define shout_all with parameters word1 and word2
def shout_all(____, ____):
"""Return a tuple of strings"""
# Concatenate word1 with '!!!': shout1
# Concatenate word2 with '!!!': shout2
# Construct a tuple with shout1 and shout2: shout_words
# Return shout_words
return shout_words
# Pass 'congratulations' and 'you' to shout_all(): yell1, yell2
# Print yell1 and yell2
print(yell1)
print(yell2)