在python中无法将字符串转换为整数

时间:2015-10-24 01:06:33

标签: python python-3.x

我在尝试将字符串转换为整数时遇到此错误:

Traceback (most recent call last):                                                                                                                                              
  File "main.py", line 9, in <module>                                                                                                                                           
    n = int(input())                                                                                                                                                            
ValueError: invalid literal for int() with base 10: 'python3 main.py'      

这是代码:

n = int(input())
    if num>0:
        cantPos = cantPos+1

1 个答案:

答案 0 :(得分:2)

您可能没有意识到口译员正在提示您输入。 input()函数接受一个字符串参数,该参数将是提示符。这里要做的常见模式是:

n = None
while n is None:
    try:
        n = int(input('Please enter an integer: '))
    except ValueError:
        print('That was not an integer!')