2016-07-15 60 views
0

我正在學習python,其中一個練習是製作一個簡單的乘法遊戲,每當你正確回答時進行。雖然我已經完成了遊戲,但我希望能夠計數嘗試的次數,以便在我幾次正確回答循環/函數時結束。我的問題是,在代碼結束時,函數被再次調用,顯然,嘗試的次數可以追溯到我最初設置的次數。我怎麼能去一點,這樣我可以指望每個循環,並在指定的嘗試次數?:計算循環的次數python

def multiplication_game(): 
    num1 = random.randrange(1,12) 
    num2 = random.randrange(1,12) 

    answer = num1 * num2 

    print('how much is %d times %d?' %(num1,num2)) 

    attempt = int(input(": ")) 

    while attempt != answer: 
     print("not correct") 

     attempt = int(input("try again: ")) 
    if attempt == answer: 
     print("Correct!") 

multiplication_game() 
+0

你能格式化你的代碼嗎?縮進不正確 –

+1

從代碼中不清楚您是否遞歸調用它 - 您能格式化代碼嗎? – nagyben

+0

三種可能性:添加全局計數器變量;將當前的轉數作爲參數傳遞給函數,或(首選)將遞歸更改爲另一個循環。 –

回答

1

end你可以在一個循環的結束環繞你的multiplication_game()電話。例如:

for i in range(5): 
    multiplication_game() 

將允許您在節目結束前玩5次遊戲。如果你想真正地計算你正在使用哪一輪,你可以創建一個變量來跟蹤,並在遊戲結束時增加該變量(你可以把它放在函數定義中)。

1

我會用一個for環和break出來的:

attempt = int(input(": ")) 

for count in range(3): 
    if attempt == answer: 
     print("correct") 
     break 

    print("not correct") 
    attempt = int(input("try again: ")) 
else: 
    print("you did not guess the number") 

這裏有else clauses for for loops一些文件,如果你想它是如何工作的更多信息。

0
NB_MAX = 10 #Your max try 
def multiplication_game(): 
    num1 = random.randrange(1,12) 
    num2 = random.randrange(1,12) 

    answer = num1 * num2 
    i = 0 
    while i < NB_MAX: 
      print('how much is %d times %d?' %(num1,num2)) 

      attempt = int(input(": ")) 

      while attempt != answer: 
       print("not correct") 

      attempt = int(input("try again: ")) 
      if attempt == answer: 
       print("Correct!") 
      i += 1 

multiplication_game()