我跑这个代码通过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