2016-07-22 45 views
-5

我是編程新手。根據我的書,這段代碼應該會出錯。Python崩潰過程:使用int()接受數值輸入

>>> age = input("How old are you? ") 
How old are you? 21 
>>> age >= 18 
    Traceback (most recent call last): 
    File "<stdin>", line 1, in <module> 
vTypeError: unorderable types: str() >= int() 

在卓異我保存的一個.py文件:This is my .py file.

然後,在終端當我試圖運行它。它沒有給我一個錯誤。 第一次,我跑進了21歲,沒有任何郵票,它返回True。 然後,我進入17,它返回False。

首先,我的電腦如何知道它們是整數?我沒有輸入age = int(年齡)。

其次,當我輸入「21」時,它返回True。沒有錯誤。爲什麼會發生?

它如何比較字符串和整數?
當我輸入「17」作爲我的年齡,它再次返回True。 **爲什麼會發生這種情況?

它不僅比較刺和一個整數,但給出錯誤的答案也是這個時間。**

This is the screenshot of my terminal window

This is the respective terminal window after i installed python 3This is my new .py file after installing python 3.

+2

您正在使用python2並且該書正在使用python3,python 2中的輸入等效於'eval(raw_input())' –

+0

請參閱http://stackoverflow.com/a/4915366/1222951 –

回答

2

您正在使用Python 2和該書作者是使用Python 3.

在Python 2中input試圖評估輸入的值,所以字符串'21'實際上變成了21作爲int

正如@Siddharth在評論中指出的,str > int將總是在Python 2中評估爲True。在Python 3中,它會引發本書中提到的錯誤。

+0

在python 2中,解釋器在字符串到int比較的情況下不會拋出錯誤,而是總是考慮字符串具有比int更高的值。 –

+0

@DeepSpace我輸入raw_input而不是輸入。並保存該文件。當我在終端中輸入21:時,它仍然沒有給出任何錯誤。 –

+0

@RishabhChopra正如Siddharth指出的那樣,'str> int'在Python 2中總是評估爲'True'。在Python 3中,它會引發本書中提到的錯誤。 – DeepSpace