首页 > 解决方案 > 在循环中多次更改变量的值

问题描述

我有一个银行程序,您可以在其中执行多项操作,并且 var balance 需要根据用户输入进行更新。它第一次这样做,并在下一次运行中使用新值。但是如果你第三次运行循环,它会在第一次运行时使用平衡输出,而不是第二次。如果你运行它第四次,它仍然使用第一个值,依此类推。

我对编程还是很陌生,但我的理论是第二个循环不能返回平衡的新值,所以它只是卡在第一个上。但我不知道如何解决这个问题。

这里有人有什么想法吗?谢谢你。

balance = 500
def main(balance):
    menu = int(input('Press 1 for balance, 2 for deposit, 3 for withdrawal or 4 for interest return: '))
    print()
    if menu == 1:
        print(balance)
    elif menu == 2:
        dep = int(input('How much do you want to deposit? '))
        print()
        balance = (balance + dep)
        print('Your new balance is', balance)
        print()
        if balance <= 999999:
            interest = 0.01
            print('Your interest is standard, 0.01%')
        if balance >= 1000000:
            interest = 0.02 
            print('Your intrest is premium, 0.02%!')
    elif menu == 3:
        wit = int(input('How much do you want to withdraw? '))
        print()
        balance = (balance - wit)
        print('Your new balance is', balance)
        print()
        if balance <= 999999:
            interest = 0.01
            print('Your intrest is standard, 0.01%')
        if balance >= 1000000:
            interest = 0.02
            print('Your interest is premium, 0.02%!')
    elif menu == 4:
        if balance <= 999999:
            interest = 0.01
        if balance >= 1000000:
            interest = 0.02
        interest_return = (balance * interest)
        balance = (balance + interest_return)
        print('Your interest is', interest, 'that makes your intrest return', interest_return, 'and your new balance', balance)
    return balance
balance = main(balance)
while True:
    print()
    restart = str(input('Would you like to do more? Press y for yes or n for no: '))
    if restart == 'n':
        print('Thank you for using the automatic bank service!')
        break
    elif restart == 'y':
        main(balance)
    else:
        print()
        print('Invalid input, press y for yes or n for no')
        continue

标签: pythonloopsreturnvar

解决方案


您需要balance使用用户输入更新 while 循环中的变量。将行更新main(balance)balance = main(balance)


推荐阅读