0

所以我想做一个简单的循环程序,但我有一个问题:

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。也许有一个非常简单的解决方案,但我已经用谷歌搜索并尝试过没有任何结果。

4

2 回答 2

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
于 2012-07-25T22:32:51.703 回答
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)

代码提示:您可以使用+=and-=作为加法/减法和赋值的快捷方式,以及其他一些更改:

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)
于 2012-07-25T22:28:24.617 回答