0

我阅读了有关追溯错误的 Python 问题的答案,可惜我不理解所提供的答案。当我运行以下代码时,如果用户不输入任何内容,我会收到回溯错误。我怎样才能避免它?请只给出具体和简短的答案。谢谢!

Error: Python Traceback Error: Invalid Literal for int() with base 10

def gold_room():
    print "This room is full of gold. How much do you take?"

    next = (raw_input(">>> "))
    how_much = int(next)

    if how_much < 50: 
        print "Nice, you're not greedy, you win!"
        exit(0)

    elif how_much > 50:
        print "You greedy bastard!"
        exit(0)
    else: 
        dead("Man, learn to type!")
4

2 回答 2

3

你得到的原因是当有人简单地按回车时,程序得到一个空白字符串'',然后程序尝试转换''为 int。

>>> int('')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: invalid literal for int() with base 10: ''

所以试试这个:

try:
   how_much = int(next)
except ValueError:
   dead("Dude, enter a value!")
于 2012-09-08T08:43:25.770 回答
0

作为 Burhan Khalid 答案的扩展,如果您想在用户输入有效号码之前提示用户,请执行以下操作:

how_much = None
while how_much is None:
    next = (raw_input(">>> "))
    try:
       how_much = int(next)
    except ValueError:
       print "Dude, enter a value!"
于 2012-09-08T09:57:08.107 回答