0

I'm studying Zed shaw's learn python 3 the hard way book and there's a part in the code i'm trying to improve.

My aim was to have an if statement with the condition that the input the user gives is of int type.

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()

It works if the input is indeed an integer but if I type in a string i get the error:
NameError: name 'string' is not defined

I tried to use int() but then if the input is a string I get an error. Is there a way to do this?

  • Is `eval(input("> "))` really from the book? You should not use `eval` esp. on user inputs, because it is [dangerous](https://nedbatchelder.com/blog/201206/eval_really_is_dangerous.html). – Austin Jul 15 '20 at 08:29
  • The `eval` function is for running code from text ("it evaluates the text as code"). What you said you want is to check that what the user typed is an integer. So I think that `eval` is not the way to go. – Lenormju Jul 15 '20 at 08:48
  • No I learned about eval() form the internet while reading up on input(). That article you gave went mostly over my head. So if I shouldn't use eval() is their an another way to check whether the input is an int in an if statement? – Gunwant Atwal Jul 15 '20 at 08:49
  • Does this answer your question? [Checking whether a variable is an integer or not](https://stackoverflow.com/questions/3501382/checking-whether-a-variable-is-an-integer-or-not) – Lenormju Jul 15 '20 at 08:49
  • @Lenormju not really, the methods there do work with the if statement, but I still get the same error if the input is a string. And even for that to work I still have to use eval() because input() converts to strings. – Gunwant Atwal Jul 15 '20 at 09:08

2 Answers2

0

Use choice = int(input("> ")). The 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), that you may want to try-except.

Lenormju
  • 4,078
  • 2
  • 8
  • 22
0

Using @Lenormju 's answer I wrote this and it worked like a charm.

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!")

Thank you to everyone who took the time out to respond