为什么python在这方面给出了一个错误?

2024-04-29 11:01:46 发布

您现在位置:Python中文网/ 问答频道 /正文

这是到Wikibooks Python tutorial的链接。我在练习那一页上的“组合数字和字符串”。第一个代码肯定会产生错误(它是在那里写的),但第二个代码也会产生错误:

print ("Please give me a number:",) 
response = raw_input()   
number = int(response) 
Traceback (most recent call last):   File "<pyshell#2>", line 1, in <module>
number = int(response) ValueError: invalid literal for int() with base 10: ''

我好像不知道怎么修理它。 我使用的是python3.3.0,我知道它是input()而不是raw_input()。 请帮忙。在


Tags: 字符串代码numberinputraw链接response错误
2条回答

您正在组合字符串和整数。在

print ("Please give me a number: ")
number = input()

plusTen = int(number) + 10
print ("If we add 10 to your number, we get " + str(plusTen))

是正确的代码。在

您正在向int()传递一个空字符串,这就是它抛出ValueError的原因:

>>> int('')

ValueError: invalid literal for int() with base 10: ''

您可以使用try-except块来解决这个问题。在

^{pr2}$

相关问题 更多 >