所以我想制作一个简单的循环程序但是我有一个问题:
def Lottery():
Cash = 200
YourNumber = randint(1, 10)
while YourNumber != WinningNumber:
Cash = Cash - 10
if Cash < 0:
print("You are out of money!")
break
YourNumber = randint(1, 10)
else:
Cash = Cash + 100
Lottery()
问题是在def的最后一行,“cash”会在重新启动循环时自动重置为200。也许这有一个非常简单的解决方案,但我用Google搜索并尝试没有任何结果。
答案 0 :(得分:2)
同样的事情(无限循环,但如果没钱,没有递归调用就会中断),
def Lottery():
Cash = 200
YourNumber = randint(1,10)
while 1:
if YourNumber != WinningNumber:
Cash = Cash - 10
if Cash <= 0:
print("You are out of money!")
break
YourNumber = randint(1,10)
else:
Cash = Cash + 100
答案 1 :(得分:1)
将Cash
作为参数传递,设置默认值:
def Lottery(Cash = 200):
YourNumber = randint(1,10)
while YourNumber != WinningNumber:
Cash = Cash - 10
if Cash < 0:
print("You are out of money!")
break
YourNumber = randint(1,10)
else:
Cash = Cash + 100
Lottery(Cash)
代码提示:您可以使用+=
和-=
作为加/减和分配的快捷方式,以及其他一些更改:
def lottery(cash = 200):
while randint(1, 10) != WinningNumber:
cash -= 10
if cash <= 0:
print("You are out of money!")
break
else:
lottery(cash + 100)