Allie H Allie H - 1 month ago 5
Python Question

Python passing local variables for modification in function

and I'm trying to figure out how I would go about passing local variables to a function and then returning the modified values. I've written the code below:

def main():
change = 150
coins = 0
quarter = 25
dime = 10
nickel = 5
penny = 1

while (change >= quarter):
change = change - quarter
coins += 1
while (change >= dime):
change = change - dime
coins += 1
while (change >= nickel):
change = change - nickel
coins += 1
while (change >= penny):
change = change - pennt
coins += 1
print(coins)

if __name__ == "__main__":
main()


But I'd like to be able to extract the modifications of the change and coins variables like so:

def main():
change = 150
coins = 0
quarter = 25
dime = 10
nickel = 5
penny = 1

while (change >= quarter):
count (change, coins, quarter)
while (change >= dime):
count (change, coins, dime)
while (change >= nickel):
count (change, coins, nickel)
while (change >= penny):
count (change, coins, penny)
print(coins)

def count(ch, co, n):
ch = ch - n
co += 1
return ch, co

if __name__ == "__main__":
main()


However, I know this isn't the way to do it. From what I understand, there could be an issue with trying to return multiple variables from the function, but it also seems like there an issue when I try to even modify only the change variable within the count function.
I would really appreciate any advice.

Answer

You're returning two values from count(), so you should capture those values when you call it:

while (change >= quarter):
    change, coins = count(change, coins, quarter)

Modifying ch and co inside count() will not affect the outer values change and coins.