Python跟踪错误:基数为10的int()的文字无效

时间:2012-09-08 08:40:41

标签: python traceback

我阅读了关于追溯错误的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!")

2 个答案:

答案 0 :(得分: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!")

答案 1 :(得分: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!"