2012-07-25 91 views
0

所以我想作一個簡單的循環程序,但我有一個問題:的Python:簡單的循環程序

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「現金」的最後一行將自動重置爲200再次重啓循環時。也許有一個非常簡單的解決方案,但我已經搜索並嘗試沒有任何結果。

+4

請修改您的代碼以修復縮進。目前還不清楚代碼應該在哪裏。 – BrenBarn 2012-07-25 22:27:19

回答

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) 
+0

這會讓'Lottery'遞歸調用自己,永遠不會結束..我有一種感覺,OP設計程序時犯了一個錯誤。 – jmetz 2012-07-25 22:31:09

+0

@mutzmatron:怎麼樣?它將以'Cash'中的'200'開始,然後每次減少或到達'else'部分,在那裏它會以更多'Cash'重新開始。如果「現金」達到零,所有功能都將結束。沒有無限遞歸。 – Ryan 2012-07-25 22:33:50

+0

啊,右側錯過了'break' - 所以...有限遞歸。彩票自稱並不是一個好主意......請參閱上面的答案。 – jmetz 2012-07-25 22:35:52

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 
+2

'現金<0'應該可以是'現金<= 0',因爲您在那裏也會有錢,對不對? – hexparrot 2012-07-25 22:37:30

+0

@hexparrot:哈哈,可能 - 好點! – jmetz 2012-07-25 22:38:09

+0

那麼問題是我想要200開始,所以你有更多的機會獲勝。我不知道如何讓200開始,然後在每次獲勝時都不重置。 – 2012-07-25 22:42:43