'I need help understanding how calling functions works
def exact_change(user_total):
num_quarters = user_total // 25
user_total %= 25
num_dimes = user_total // 10
user_total %= 10
num_nickels = user_total // 5
user_total %= 5
num_pennies = user_total
return(num_pennies, num_nickels, num_dimes, num_quarters)
if __name__ == '__main__':
input_val = int(input())
num_pennies, num_nickels, num_dimes, num_quarters = exact_change(input_val)
if input_val <= 0:
print('no change')
else:
if num_pennies > 1:
print(f'{num_pennies} pennies')
elif num_pennies ==1:
print(f'{num_pennies} penny')
if num_nickels > 1:
print(f'{num_nickels} nickels')
elif num_nickels == 1:
print(f'{num_nickels} nickel')
if num_dimes > 1:
print(f'{num_dimes} dimes')
elif num_dimes == 1:
print(f'{num_dimes} dime')
if num_quarters > 1:
print(f'{num_quarters} quarters')
elif num_quarters == 1:
print(f'{num_quarters} quarter')
I'm struggling to understand why we need this num_pennies, num_nickels, num_dimes, num_quarters = exact_change(input_val) line of code because if the function already returns those values why would we need to initialize those in our main function.. and couldnt we just make the variables global inside exact_change() function instead of calling them manually in the main functions?
Solution 1:[1]
All the variable that are created inside a function, exist only inside a function while the function it's executing the code. They they get disposed to free memory for other uses.
In order to use what the function return (if it's not a void function) you have to store it to a variable.
In this case the funtion return multiple value, so you unpack them into 4 diffrent one for better use, if you would store all of them in a single one it will be a tuple.
You could to the variables global, but the idea of a function it's to reuse part of the code multiple times. So if you do the variable global they will likly exist only once.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Sau1707 |
