[英]Python condition not applying (if/elif)
我的python代碼中的條件有問題。 這是一個數學應用程序,這是部分代碼無法正常運行:
def askNumber():
"""Asks the number to test"""
a=raw_input("Select the number to test (type 'exit' for leaving):")
if len(a)!=0 and a.lower!="exit":
try:
b= int(a)
processing(b)
except ValueError:
print "Your input is not valid. Please enter a 'number'!"
time.sleep(1)
askNumber()
elif len(a)!=0 and a.lower=="exit":
answer()
else:
print "Your input can't be 'empty'"
time.sleep(1)
askNumber()
因此,當在raw_input中輸入“ a”時,我鍵入“ exit”,假定的適用條件是小數點,但最終應用if則結束,並顯示“您的輸入無效。請輸入一個數字”! ” 抱歉,如果很明顯,我是個乞討人,盡管我嘗試幾次發現錯誤。
您需要調用 .lower()
函數。
if len(a) != 0 and a.lower() != "exit":
# ...
elif len(a) != 0 and a.lower() == "exit":
真正不需要測試len(a)!=0
,只需測試a
自身:
if a and a.lower() != "exit":
# ...
elif a and a.lower() == "exit":
空字符串在布爾上下文中的值為False
。
您的程序流程由內而外,我是否可以提出一些改進建議?
def askNumber():
"""Asks the number to test"""
while True:
a = raw_input("Select the number to test (type 'exit' for leaving):")
if not a:
print "Your input can't be 'empty'"
continue
if a.lower() == "exit":
answer()
break
try:
b = int(a)
except ValueError:
print "Your input is not valid. Please enter a 'number'!"
continue
processing(b)
實際上, not a
分支也可以消除(空輸入將在中處理except
)。
您可以更改以下條件:
if a and a.lower() !="exit":
# .....
elif a and a.lower() == "exit":
answer()
elif a and not a.isdigit(): print "invalid input"
else:
#.............
請注意,您不需要len(a) != 0
,只需使用a
will可以評估它是否為空。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.