Python “第二次输入取”&引用;没有我的选择
我的代码是这样的:Python “第二次输入取”&引用;没有我的选择,python,python-3.x,Python,Python 3.x,我的代码是这样的: x = int(input("Enter a number: ")) y = int(input("Enter a second number: ")) print('The sum of ', x, ' and ', y, ' is ', x+y, '.', sep='') 当我输入任何数字时,会出现此错误: Enter a number:15 Enter a second number: Traceback (most recent call last): File
x = int(input("Enter a number: "))
y = int(input("Enter a second number: "))
print('The sum of ', x, ' and ', y, ' is ', x+y, '.', sep='')
当我输入任何数字时,会出现此错误:
Enter a number:15
Enter a second number: Traceback (most recent call last):
File "C:/Users/mgt4/PycharmProjects/Beamy/test.py", line 5, in <module>
y = int(input("Enter a second number: "))
ValueError: invalid literal for int() with base 10: ''
输入一个数字:15
输入第二个号码:回溯(最近一次呼叫最后一次):
文件“C:/Users/mgt4/PycharmProjects/Beamy/test.py”,第5行,在
y=int(输入(“输入第二个数字:”)
ValueError:基数为10的int()的文本无效:“”
我知道它认为输入的第二个数字是一个空格,但我不知道为什么以及如何解决这个问题。int(input(“whatever”)
如果input()
返回一些不能解释为int的内容,那么它确实会引发一个ValueError
。一般来说,您不应该信任用户输入(无论它们来自哪里-input()
、命令行参数、sys.stdin
、文本文件、HTTP请求等等),并始终对它们进行清理和验证
对于您的用例,您希望在int(输入(…)
调用周围有一个包装函数:
def asknum(q):
while True:
raw = input(q)
try:
return int(raw.strip())
except ValueError:
print("'{}' is not a valid integer".format(raw)
num1 = asknum("enter an integer")
您可以通过提供验证函数使其更通用:
def ask(q, validate):
while True:
raw = input(q)
try:
return validate(raw.strip())
except ValueError as e:
print(e)
在这种情况下,您可以简单地使用int
类型作为验证函数:
num1 = ask("enter an integer", int)
尝试将代码转换为更通用的:
REPEATS = 2
counter = 1
values = []
while True:
value = raw_input("Enter number {}: ".format(counter))
try:
number = int(value)
except ValueError:
print("Entered value '{}' isn't a number".format(value))
continue
counter += 1
values.append(number)
if counter > REPEATS:
break
print('The sum of values {} is {}'.format(", ".join([str(v) for v in values]), sum(values)))
其中,重复
将是附加值的数量
Example of output:
Enter number 1: 56
Enter number 2: 88
The sum of values 56, 88 is 144
无法复制。是否尝试从终端运行代码?如果键入“return”有两次,您可能会得到这种效果。我有点困惑。即使用户选择为第二个输入提示输入空格,您是否希望您的程序尝试继续?仅供参考:如果您离开
sep=''
,您不需要手动在print
参数中插入空格。(我猜你这样做是有意避开
之前的空格,最好使用str.format
然后)@Jean-Françoisfare-Strange当我从终端运行时,它工作,但不使用PyCharm。你知道为什么吗?