2 回答

TA貢獻1982條經驗 獲得超2個贊
該行for answer in random.choice(quizzes)實際上獲取一個隨機測驗字符串,然后迭代字符串中的每個字符;這就是為什么循環看起來沒有停止,因為它迭代的項目比您預期的要多。
最初在循環中的行random.choice(quizzes), 不執行任何操作;該random.choice()函數從列表中返回一個隨機項目。如果您不對返回值執行任何操作(例如打印它),那么什么也不會發生。
您原來的行if quizzes == q1 and asking == 'A cold':不會起作用,因為quizzes是您的測驗列表,所以檢查quizzes == q1將始終是False。在我的代碼中,由于我循環通過quizzesvia for quiz in quizzes,這意味著quiz在我的代碼中是來自 的測驗字符串quizzes,因此當我quiz == q1這樣做時,可以正確地將當前quiz與q1,q2或進行比較q3。
a1我注意到您在、a2和中定義了答案a3,因此您可以簡化代碼并使用它們進行比較asking,例如asking == a1代替asking == 'A cold'。
import random
quizzes = [q1, q2, q3] #catagorise to quizzes
random.shuffle(quizzes) # randomize the quiz order
for quiz in quizzes: # loop through the list of quizzes
guesses = 3 # limits to 3 guesses
print(quiz) # prompt the user with the quiz question
while True: # keep asking for answers until guesses run out, or the user gets a correct answer
asking = input('Your Answer is?\n')
if quiz == q1 and asking == a1:
print( 'Bingo!!')
break
elif quiz == q2 and asking == a2:
print( 'Bingo!!')
break
elif quiz == q3 and asking == a3:
print( 'Bingo!!')
break
elif guesses == 0:
print( 'Sorry, you are reached the maximum guesses. Bye~now~')
break
else:
guesses -= 1 #reducing the max. guesses of 3 to 2 to 1
print( "Sorry, it's incorrect.")

TA貢獻1815條經驗 獲得超6個贊
你的問題是猜測的位置?,F在它在你的 for 循環內。將其放在 for 循環之外,它應該可以工作。
您還應該看看您的
elif guesses == 0:
現在,即使猜測次數為 0,玩家也能猜出。它可能應該是<=1。
您的代碼將按照您想要的方式運行,如下所示:
q1 = 'What can one catch that is not thrown?'
a1 = 'A cold'
q2 = 'If you had only one match and entered a dark room containing an oil lamp, some kindling wood, and a newspaper, which would you light first?'
a2= 'The match'
q3 = 'Some months have 31 days, others have 30 days, but how many have 28 days?'
a3= 'All the months'
import random
quizzes = [q1, q2, q3] #catagorise to quizzes
guesses = 3
for answer in random.choice(quizzes):
# limits to 3 guesses
random.choice(quizzes)
asking = input('Your Answer is?\n')
if quizzes == q1 and asking == 'A cold':
print( 'Bingo!!')
break
elif quizzes == q2 and asking == 'The match':
print( 'Bingo!!')
break
elif quizzes == q3 and asking == 'All the months':
print( 'Bingo!!')
break
elif guesses <=1:
print( 'Sorry, you are reached the maximum guesses. Bye~now~')
exit()
else:
guesses -= 1 #reducing the max. guesses of 3 to 2 to 1
print( "Sorry, it's incorrect.")
result = asking
添加回答
舉報