2017-03-17 77 views
0

我跑這個代碼通過Visual Studio代碼:Python的輸入總是返回一個字符串

counter = 0 
while True: 
    max_count = input('enter an int: ') 
    if max_count.isdigit(): 
     break 
    print('sorry, try again') 

max_count = int(max_count) 

while counter < max_count: 
    print(counter) 
    counter = counter + 1 

,很驚訝地看到這樣的響應:

python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py"         
[email protected]:~$ python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py"    
enter an int: 5                       
Traceback (most recent call last):                   
    File "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py", line 7, in <module>    
    if max_count.isdigit():                    
AttributeError: 'int' object has no attribute 'isdigit' 

因爲輸入()總是應該返回的字符串: https://docs.python.org/3.5/library/functions.html#input

我把帶引號的字符串:

[email protected]:~$ python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py"    
enter an int: '5' 
0                   
1 
2 
3 
4 

現在它按預期工作。然後,我跑了我的標準問題的Ubuntu終端上:

[email protected]:~/Documents/PYTHON/Blaikie Python$ python3 flatnested.py 
enter an int: 5 
0 
1 
2 
3 
4 

和它的工作正如所料,注意周圍的5

沒有引號這是怎麼回事? Visual Studio代碼是否重寫了Python的規則?

+3

在你的第一種情況下,你似乎在Python 2.7下運行。 input()函數在版本2.7和版本3之間改變 - 請參閱https://docs.python.org/2/library/functions.html#input。 – Mac

回答

1

簡答

看來,當您運行通過Visual Studio代碼的代碼,Python 2.7版被用來運行代碼。

如果您希望繼續使用Python 2.7,請使用raw_input而不是input函數。

說明

看看Python的2.7 documentation的輸入功能。它與Python 3.x中使用的輸入函數不同。在Python 2.7中,輸入函數使用eval函數來處理程序接收的輸入,就像輸入是一行Python代碼一樣。

python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py"         
[email protected]:~$ python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py"    
enter an int: 5                       
Traceback (most recent call last):                   
    File "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py", line 7, in <module>    
    if max_count.isdigit():                    
AttributeError: 'int' object has no attribute 'isdigit' 

什麼上面發生的情況下,與Python 2.7,是:

以上的Python

eval("5").isdigit() # 5.isdigit()

聲明是無效的,因爲它導致了試圖調用上一個整數的.isdigit()方法。但是,Python中的整數沒有這個方法。

[email protected]:~$ python "/home/malikarumi/Documents/PYTHON/Blaikie Python/flatnested.py"    
enter an int: '5' 
0                   
1 
2 
3 
4 

在上述情況下,與Python 2.7,發生的事情是:

eval("'5'").isdigit() # '5'.isdigit()

上面的語句是有效的,因爲它會導致一個字符串調用.isdigit()方法,它確實存在字符串。

我希望這可以回答你的問題,讓你更清楚地瞭解Python 2.7和Python 3.x中的input函數之間的區別。

+0

你們都給出了很好的答案,但是你們的答案稍微詳細一點,所以我給了你們要點。謝謝,我知道raw_input()已經成爲輸入()從2到3,但我不知道2有自己的輸入()是不同的。 –

+0

謝謝。我很高興你學到了新的東西。快樂的編碼! –

0

如果你鍵入終端python時使用Ubuntu(或其他Linux發行版),它與python2等於,所以第一次你python運行,你使用Python 2,而不是Python 3中,這錯誤很明顯。 爲什麼你把報價字符串,並將其在Python 2,因爲工作的原因,input()等於eval(raw_input())

>>> input() 
5 
5 
# equal with eval(5), which is 5 

用引號字符串

>>> input() 
'5' 
'5' 
# equal with eval('5'), which is '5' 

在第二次它和預期一樣,因爲你明確地python3運行

相關問題