I want to use the result of a function in another function to do comparison and print out the balance. But the code is repeating itself twice and not giving me the required result
Below is part of the code
def coins():
print("Please insert coins.")
qtrs = int(input('How many quarters: '))
dmes = int(input('How many dimes: '))
ncks = int(input('How many nickles: '))
pens = int(input('How many pennies: '))
coinS = (0.25 * qtrs) + (0.1 * dmes) + (0.05 * ncks) + (0.01 * pens)
return coinS
def compare_coins(n):
if coins() > MENU[n]["cost"]:
change = coins() - MENU[n]["cost"] #I tried using coinS it is giving me an error
print( f'Here is your ${change}')
The code is repeating twice because you are calling the coins() function twice, once in the ‘if’ statement condition, and the second time inside the ‘if’ statement. So, the program asks for input twice. You can solve this by storing the value returned by coins() in a variable. Modified code:
def coins():
print("Please insert coins.")
qtrs = int(input('How many quarters: '))
dmes = int(input('How many dimes: '))
ncks = int(input('How many nickles: '))
pens = int(input('How many pennies: '))
coinS = (0.25 * qtrs) + (0.1 * dmes) + (0.05 * ncks) + (0.01 * pens)
return coinS
def compare_coins(n):
user_coins = coins() #Create a variable to store the value
if user_coins > MENU[n]["cost"]:
change = user_coins - MENU[n]["cost"]
print( f'Here is your ${change}')
Doing this will not require calling the coins() function twice.