我有一些代碼是這樣:如何防止循環中的布爾值無限循環?
maybeYes = raw_input("Please enter Yes to continue.")
if maybeYes != "Yes":
print "Try again."
# ask for input again
else:
pass
我填,我希望把它再次要求輸入什麼?
我有一些代碼是這樣:如何防止循環中的布爾值無限循環?
maybeYes = raw_input("Please enter Yes to continue.")
if maybeYes != "Yes":
print "Try again."
# ask for input again
else:
pass
我填,我希望把它再次要求輸入什麼?
你應該直接在循環中執行raw_input。
while True:
result = raw_input("...")
if result != "Yes":
print "Try again."
continue
else:
break
我已經開始工作了。謝謝你的幫助。 –
它在我看來像你想在這裏一個無限循環。
maybeYes = raw_input("Please enter Yes to continue.")
while maybeYes != "Yes":
maybeYes = raw_input("Please try again.")
但是,您可以隨時添加計數器/轉義。
maybeYes = raw_input("Please enter Yes to continue.")
attempts = 0
while maybeYes != "Yes" and attempts < 10:
maybeYes = raw_input("Please try again.")
attempts += 1
這將循環打印wrong
直到用戶類型yes
,Yes
,YEs
,YES
,yEs
或yeS
作爲輸入對YES
檢查之前轉換爲大寫,那麼你的代碼就可以繼續...
while raw_input("Please enter Yes to start: ").upper() != 'YES':
print 'Wrong'
print 'Correct'
#Carry on here
輸出:
Please enter Yes to start: nowg
Wrong
Please enter Yes to start: wggwe
Wrong
Please enter Yes to start: Yes
Correct
不知道爲什麼這次被拒絕投票,它不僅是正確的,而且比其他兩個當前的答案更清晰和更強大? –
可能是因爲人們開始熱愛downvoting .. :) – MKJParekh
我想通過這一行 - 「會給你聲望」,你試圖說......「將增加你作爲SO的提問者的聲望,而不是以分數來表示」 – MKJParekh