我正在學習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()
你能格式化你的代碼嗎?縮進不正確 –
從代碼中不清楚您是否遞歸調用它 - 您能格式化代碼嗎? – nagyben
三種可能性:添加全局計數器變量;將當前的轉數作爲參數傳遞給函數,或(首選)將遞歸更改爲另一個循環。 –