2017-02-17 29 views
0

我正在創建一個簡單的Python程序,要求提供有關用戶的基本信息。如果基本信息輸入中的語句錯誤

myAge= input() 
if myAge > 20:  
    print ('You must be old enough to party legally now.') 
else:  
    print ('Put that drink down!') 

我的錯誤

if myAge > 20: TypeError: '>' not supported between instances of 'str' and 'int'

回答

0

至於myAge必須是整數,最好把它只要用戶輸入其轉換:

myAge= int(input()) 
... 
if myAge > 20: 
... 

等等,如果他沒有進入有效年齡,立即失敗。

您還可以捕獲錯誤並再次問:

while True: 
    try: 
     myAge= int(input("Please enter your age: ")) 
     break 
    except ValueError: 
     print("Your age must be an integer") 

if myAge > 20:  
    print ('You must be old enough to party legally now.') 
else:  
    print ('Put that drink down!') 
+0

非常酷的另外,謝謝!現在,我如何查看我可以使用的功能以及它們的工作方式。例如查找什麼嘗試:手段或什麼破解等手段。 – SplendidMallard

+0

Python教程是一個有用的參考 - https://docs.python.org/3.6/tutorial/errors.html(並解釋了相同的例子,事實上...)。你仍然可以谷歌任何你需要的,你會發現很多答案! –

1

input()函數返回一個字符串值,你不能比較一個字符串和一個整數,爲了做到這一點,你需要執行類似下面的在如:

myAge= input() 
if int(myAge) > 20:  
    print ('You must be old enough to party legally now.') 
else:  
    print ('Put that drink down!') 
+0

這將提高'ValueError'任何東西,不能強制轉換爲'int' ... – zwer

+0

是@zwer用戶輸入,但我相信這只是一些簡單的使用,當然我們可以把它放在一個try塊中,但它似乎是一個簡單的例子。 –