为了账号安全,请及时绑定邮箱和手机立即绑定

在 def 之外赋予 balance 新值

在 def 之外赋予 balance 新值

BIG阳 2022-05-24 15:29:59
退出循环时如何获得 balance 的新值?现在它只取原始值并打印它。我也试过 balance += (balance + dep)balance = 500def main(balance):    if balance <= 999999:        intrest = 0.01    if balance >= 1000000:        intrest = 0.02    menu = int(input('Press 1 for balance, 2 for deposit, 3 for withdrawal or 4 for interest return: '))    if menu == 1:        print(balance)    elif menu == 2:        dep = int(input('How much do you want to deposit? '))        balance = (balance + dep)        print('Your new balance is', balance)        if balance <= 999999:            intrest = 0.01        if balance >= 1000000:            intrest = 0.02            print('Congratulations, your intrest just went up!')    elif menu == 3:        wit = int(input('How much do you want to withdraw? '))        balance = (balance - wit)        print('Your new balance is', balance)        if balance <= 999999:            intrest = 0.01        print('Your intrest is now back to standard!')    elif menu == 4:        intrest_return = balance + (balance * intrest)        print(intrest_return)    while True:        restart = str(input('Would you like to do more? Press y for yes or n for no: '))        if restart == 'y':            main(balance)        else:            breakmain(balance)print(balance)
查看完整描述

2 回答

?
三国纷争

TA贡献1804条经验 获得超7个赞

您应该return在代码中使用 a ,然后将其分配给您的变量。这将是您的代码:


balance = 500

def main(balance):

    if balance <= 999999:

        intrest = 0.01

    if balance >= 1000000:

        intrest = 0.02

    menu = int(input('Press 1 for balance, 2 for deposit, 3 for withdrawal or 4 for interest return: '))

    if menu == 1:

        print(balance)

    elif menu == 2:

        dep = int(input('How much do you want to deposit? '))

        balance = (balance + dep)

        print('Your new balance is', balance)

        if balance <= 999999:

            intrest = 0.01

        if balance >= 1000000:

            intrest = 0.02

            print('Congratulations, your intrest just went up!')

    elif menu == 3:

        wit = int(input('How much do you want to withdraw? '))

        balance = (balance - wit)

        print('Your new balance is', balance)

        if balance <= 999999:

            intrest = 0.01

        print('Your intrest is now back to standard!')

    elif menu == 4:

        intrest_return = balance + (balance * intrest)

        print(intrest_return)

    while True:

        restart = str(input('Would you like to do more? Press y for yes or n for no: '))

        if restart == 'y':

            main(balance)

        else:

            break

    return balance

balance=main(balance)

print(balance)


查看完整回答
反对 回复 2022-05-24
?
慕田峪7331174

TA贡献1828条经验 获得超13个赞

添加global balance函数的第一行。

除非您这样做,否则在函数内分配的任何变量都被视为本地变量,这就是您收到错误的原因。


查看完整回答
反对 回复 2022-05-24
  • 2 回答
  • 0 关注
  • 94 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信