对 if 语句使用 eval((input)) 时出现名称未定义错误

Name not defined error while using eval((input)) for an if statement

我正在学习 Zed shaw 的 learn python 3 the hard way book,代码中有一部分我正在努力改进。

我的目标是有一个 if 语句,条件是用户提供的输入是 int 类型。

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

    choice = eval(input("> "))
    if type(choice) is int:
        how_much = choice
    else:
        print("Man, learn to type a number.")

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

gold_room()

如果输入确实是一个整数,它会工作,但如果我输入一个字符串,我会得到错误:
NameError: name 'string' is not defined

我尝试使用 int() 但如果输入是字符串,我会收到错误消息。 有办法吗?

使用choice = int(input("> "))int function will convert the string that the input function gives you into an integer. But if it can't, it will raise an exception (ValueError),你可能想试试-except。

使用@Lenormju 的回答,我写了这个并且它很有魅力。

def gold_room():
    print("This room is full of gold. How much do you take?")
    #  used try to check whether the code below raises any errors
    try:
        choice = int(input("> "))
        how_much = choice
    # except has code which would be executed if there is an error
    except:
        dead("Man, learn to type a number.")
    # else has code which would be executed if no errors are raised
    else:
        if how_much < 50:
            print("Nice, you're not greedy, you win!")
            exit(0)
        else:
            dead("You greedy bastard!")

感谢所有抽出时间回复的人