2017-03-17 80 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运行

相关问题