python - 无法让它发挥作用。不断重复没有足够的信用
问题描述
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 真的很陌生
解决方案
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
来解决该特定问题。这同样适用于coin
和allowed
因为它们只能在函数内部使用,虽然它们目前没有引起问题,但是如果您尝试在某处用相同的名称命名其他东西,则将它们留在要更改的函数之外可能会导致问题别的。
推荐阅读
- javascript - 从父级或最近的 div 获取数据值
- java - 如何在 Java 8 中将字符串(例如“01/01/2019”)转换为日期
- java - 如何找到两个日期之间的天数?
- makefile - 在 Makefile 中删除带有配方的目标失败
- python-3.x - 获取数据框字典的特征重要性
- corda - 状态发行的任何样本->更新->在corda中退出
- maven - 声纳分支插件不显示任何内容
- haskell - 使用 Aeson 读取对象的单个字段,无需编写 FromJSON 实例
- python - 如何计算我的数据集中的移动平均值?
- react-native - 无法将数据输入从一个屏幕传递到另一个屏幕。反应原生