我跑這個代碼通過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的規則?
在你的第一種情況下,你似乎在Python 2.7下運行。 input()函數在版本2.7和版本3之間改變 - 請參閱https://docs.python.org/2/library/functions.html#input。 – Mac