개발일기 [Python 파이썬]

[Python result] 파이썬 결과값 도출: 함수 호출 vs 튜플 생성

neullo 2024. 3. 8. 00:16

처음 파이썬을 공부하다 보면 result에 a, b라고 해야 하는지 (a, b)라고 해야 하는지 (a, (b))라고 해야 하는지 헷갈릴 수 있다. 사례를 통해 배워보자.

함수 호출의 예시:

pythonCopy code
def add(a, b):
    return a + b

result = add(3, 5)  # add 함수를 호출하고 결과를 변수 result에 저장
print(result)  # 출력: 8

위의 코드에서 **add(3, 5)**는 함수 **add**를 호출하고, 이 함수에 인자로 3과 5를 전달합니다. 함수가 실행되면 3과 5를 더한 결과인 8이 반환되고, 이 결과가 result 변수에 할당됩니다.

 

def remove_vowels(my_string):
    vowels = "aeiouAEIOU"  # 모음을 저장한 문자열
    result = ""  # 모음이 제거된 문자열을 저장할 변수

    # 주어진 문자열을 순회하면서
    for char in my_string:
        # 현재 문자가 모음이 아니면 결과에 추가합니다.
        if char not in vowels:
            result += char

    return result

# 예시 문자열
my_string = "Hello World"
# 모음을 제거한 문자열을 출력합니다.
print(remove_vowels(my_string))
remove_vowels(my_string)
is a common pattern in function calls. When calling a function, you use parentheses () after the function name to invoke it, and within these parentheses, you provide any arguments to the function. So, remove_vowels(my_string) calls the remove_vowels function and passes my_string as an argument.

For example, result = remove_vowels(my_string) calls the remove_vowels function and stores its result in the variable result. This is how you assign the return value of a function to a variable.

 

튜플 생성의 예시:

pythonCopy code
a = 10
b = 20

result = a, b  # 변수 a와 b를 튜플로 묶어서 변수 result에 할당
print(result)  # 출력: (10, 20)

위의 코드에서 **a, b**는 변수 **a**와 **b**를 튜플로 묶는 것을 나타냅니다. 이 두 변수가 튜플로 묶인 결과가 result 변수에 할당됩니다. 따라서 **result**에는 **(10, 20)**이라는 튜플이 저장됩니다.

이렇게 함수 호출과 튜플 생성은 각각 서로 다른 동작을 수행하며, 각각의 예시는 해당 동작을 보여줍니다.