[英]Python loop restarting even though there is a try: except:
這是我剛剛編寫的一個小程序的代碼,用於測試我學到的一些新知識。
while 1:
try:
a = input("How old are you? ")
except:
print "Your answer must be a number!"
continue
years_100 = 100 - a
years_100 = str(years_100)
a = str(a)
print "You said you were "+a+", so that means you still have "+years_100+" years"
print "to go until you are 100!"
break
while 2:
try:
b = str(raw_input('Do you want to do it again? If yes enter "yes", otherwise type "no" to stop the script.'))
except:
print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
continue
if b == "yes":
print 'You entered "yes". Script will now restart... '
elif b == "no":
print 'You entered "no". Script will now stop.'
break
對於for循環,它工作正常。 如果您鍵入的不是數字,它將告訴您僅允許數字。
但是,在第二個循環中,它要求您輸入“是”或“否”,但是如果您輸入其他內容,它只會重新啟動循環,而不是在打印完之后再顯示消息。
except:
我做錯了什么,該如何解決,這樣才能顯示告訴我的消息?
您不會得到異常,因為使用raw_input()
時總是輸入一個字符串。 因此, raw_input()
返回值上的str()
永遠不會失敗。
相反,在您的yes
或no
測試中添加else
語句:
if b == "yes":
print 'You entered "yes". Script will now restart... '
elif b == "no":
print 'You entered "no". Script will now stop.'
break
else:
print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
continue
請注意, except
聲明except
切勿使用毯子; 捕獲特定的異常。 否則,您將掩蓋不相關的問題,使您更難發現這些問題。
您的第一個除外處理程序應僅捕獲NameError
, EOFError
和SyntaxError
例如:
try:
a = input("How old are you? ")
except (NameError, SyntaxError, EOFError):
print "Your answer must be a number!"
continue
因為這就是input()
會拋出的結果。
還要注意, input()
采用任何 python表達式。 如果輸入"Hello program"
(帶引號),則不會引發任何異常,但這也不是數字。 使用int(raw_input())
代替,然后捕獲ValueError
(如果您輸入的不是整數,會拋出該錯誤),並為raw_input
捕獲EOFError
:
try:
a = int(raw_input("How old are you? "))
except (ValueError, EOFError):
print "Your answer must be a number!"
continue
要使用第二個循環控制第一個循環,請使其成為返回True
或False
的函數:
def yes_or_no():
while True:
try:
cont = raw_input('Do you want to do it again? If yes enter "yes", otherwise type "no" to stop the script.'))
except EOFError:
cont = '' # not yes and not no, so it'll loop again.
cont = cont.strip().lower() # remove whitespace and make it lowercase
if cont == 'yes':
print 'You entered "yes". Script will now restart... '
return True
if cont == 'no':
print 'You entered "no". Script will now stop.'
return False
print 'Please try again. Enter "yes" to do it again, or "no" to stop.'
在另一個循環中:
while True:
# ask for a number, etc.
if not yes_or_no():
break # False was returned from yes_or_no
# True was returned, we continue the loop
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.