下面的代碼所做的是生成 2 個隨機整數并將它們相乘。在用戶放置輸入并使其正確后,它會自動生成另一對隨機整數。
我怎樣才能做到當用戶輸入錯誤時,它不會生成一個數字,而是等到用戶最終計算出正確的答案,然后生成一組新的整數?
我一直在玩主回圈中的回圈,但它沒有解決我的問題
while loop:
new_ints = True
while new_ints:
random_int_1 = random.randint(2,9)
random_int_2 = random.randint(2,9)
answer = random_int_1*random_int_2
equation = (f"{random_int_1}x{random_int_2} = ? ")
print(equation)
user_answer = int(input())
if answer == user_answer:
print("correct")
new_ints = True
loop = True
else:
print("Wrong")
new_ints = True
loop = False
uj5u.com熱心網友回復:
除了if陳述句之外,您還可以簡單地使用另一個 while 回圈來檢查這樣的猜測:
while int(input()) != answer:
print('Incorrect. Guess again')
uj5u.com熱心網友回復:
只需在生成整數之前添加一個 if 條件:
while True:
if new_ints:
random_int_1 = random.randint(2,9)
random_int_2 = random.randint(2,9)
answer = random_int_1*random_int_2
您需要決定哪個條件會打破回圈。恕我直言,您也可以消除外部回圈,只需保持while True并建立一個break條件
uj5u.com熱心網友回復:
您可以利用while-else來解決問題。如果用戶的輸入不等于實際答案,回圈將不斷重復,否則將列印“正確”并繼續下一個問題。下面是修改后的完整代碼。
import random
while True:
random_int_1 = random.randint(2,9)
random_int_2 = random.randint(2,9)
answer = random_int_1*random_int_2
equation = (f"{random_int_1}x{random_int_2} = ? ")
print(equation)
user_answer = ''
while int(input()) != answer:
print("Wrong")
else:
print("correct")
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/383315.html
