首页 > 解决方案 > 无法让它发挥作用。不断重复没有足够的信用

问题描述

choice="y"
again="y"
coin=0
credit=0
allowed=[0,10,20,50,100,200]
def money_insert():
    global again
    global coin
    global credit
    global allowed
    while again=="y":
        try:
            coin=int(input("insert coin"))
        except:
            print("thats not a coin")
        while coin not in allowed:
            print("invalid coin")
            coin = 0
        credit+=coin
        again=input("another coin y/n?")
money_insert()
print("you have",credit,"p")
print("")
print("**********")
print("**1 coke 100p**")
print("*2 haribo 100p*")
print("*3 galaxy 100p*")
print("**4 mars 100p**")
print("*5 crisps  50p*")
selection=int(input("what would you like? 1-5"))
while choice=="y":
  if selection==1:
    if credit>99:
      print("Here's your coke")
      credit-=100
    else:
        print("not enough credit")
        money_insert()

最后一点一直显示信用不足,我不知道该怎么办

抱歉,如果这是一个非常愚蠢的问题,我对 python 真的很陌生

标签: pythonpython-3.x

解决方案


choice永远不会改变,所以你永远无法逃脱while choice='y':循环。然后假设您选择的选择是1您继续购买可乐。如果您之前通过该money_insert功能输入了硬币,大概您会在某个时候对“另一枚硬币是/否?”的问题回答否。您永远不会重置again变量,因此后续调用money_insert只会跳过您的 for 循环,不会让您输入更多的钱。然后,您基本上一遍又一遍地遵循相同的路径:while choice='y':→→→if selection==1:if credit>99: ... else:print("not enough credit")

我还想指出您的money_insert函数的问题是在不需要的地方使用全局变量的直接结果。全局变量在某些情况下可能很有用,但在这种情况下,它们通常不受欢迎. 在这种情况下,您不需要again是全局的,因为它没有在其他任何地方使用,因此您可以again='y'在函数定义中移动并删除该行global again来解决该特定问题。这同样适用于coinallowed因为它们只能在函数内部使用,虽然它们目前没有引起问题,但是如果您尝试在某处用相同的名称命名其他东西,则将它们留在要更改的函数之外可能会导致问题别的。


推荐阅读