[英]Counting the number of loops 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()
您可以在循環的結尾處結束對multiplication_game()
調用。 例如:
for i in range(5):
multiplication_game()
可以讓您在程序結束前玩5次游戲。 如果您想真正計算自己正在進行的比賽,則可以創建一個變量來跟蹤,並在每次游戲結束時遞增該變量(您可以將其放入函數定義中)。
我會使用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")
如果需要for
循環的更多詳細信息,這是有關for
循環的else
子句的一些文檔。
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()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.