【问题标题】:Python working substraction in function函数中的Python工作减法
【发布时间】:2018-07-25 19:19:31
【问题描述】:

我想创建一个名为 bank 的函数。我输入了一个叫做money的输入,询问你想从第二个变量“存储”中取出多少钱。 Storage = 10000,如果 storage > 0:做减法存储 - 钱。 如果存储

def bank():
    money = int(input("How much money you want? "))
    storage = 10000
    if storage > 0:
        storage = storage - money
        print(storage)
        bank()
    if storage <= 0:
        print("we dont have money")
        quit()
bank()

问题是如果钱 == 1000 所以存储 == 9000,但如果第二次钱 == 2000,存储应该显示 7000,但显示 8000

【问题讨论】:

  • 你总是在第 3 行分配 storage = 10000

标签: python


【解决方案1】:

每次您递归调用 bank() 时,它都会将存储重置为 10000。因此您需要在函数之外对其进行初始化。

所以

def bank(storage):
    money = int(input("How much money you want? "))
    if storage > 0:
        storage = storage - money
        print(storage)
        bank(storage)
    if storage <= 0:
        print("we dont have money")
        quit()

storage = 10000
bank(storage)

【讨论】:

  • 谢谢,我认为这可能与该变量有关
猜你喜欢
  • 1970-01-01
  • 2017-04-21
  • 2017-05-30
  • 1970-01-01
  • 1970-01-01
  • 2023-03-24
  • 2019-03-05
  • 2012-02-04
  • 2018-07-23
相关资源
最近更新 更多