1.問題描述
1 age=input('please enter your age') 2 if age >=18: 3 print('your age is',age) 4 print('adult') 5 elif age>=6: 6 print('teenager') 7 else: 8 print('kid')
今天在運行該代碼的時候,python解釋器報錯,錯誤信息如下:
F:\python>python3 elif.py
please enter your age5
Traceback (most recent call last):
File "elif.py", line 2, in <module>
if age >=18:
TypeError: unorderable types: str() >= int()
解釋一下錯誤信息:
1.Traceback指追蹤,即python的解釋器使用Traceback追蹤異常,出現Traceback說明你的程序出錯了;
2.接下來的一行表明文件名,位置;
3.再接下來顯示出錯語句;
4.最后一行顯示錯誤的原因。
unorderable types: str() > int()指類型不匹配,即age變量與18的類型不匹配。可是,我輸入的age是整數,為什么會出現這種情況呢?
原因是,在python3中,input函數返回的是字符串,即你輸入字符串,他就輸出字符串,你輸入數字,他還是輸出字符串,那么在執行接下來的操作時就可能出現類型不匹配的情況。
所以出現了字符串與數字比較的情況。
2.解決方法
既然input函數的返回值是字符串,我們不妨將字符串強制性轉化成整型,這樣就不會出現類型不匹配的情況了。
正確代碼如下:
1 age=int(input('please enter your age')) 2 if age >=18: 3 print('your age is',age) 4 print('adult') 5 elif age>=6: 6 print('teenager') 7 else: 8 print('kid')
運行結果:
F:\python>python3 elif.py
please enter your age25
your age is 25
adult