0

I am trying to test if my user input is a string or an integer.

feet = input ("Enter your feet.")
inches = input ("Enter your inches.")

if type(eval(feet)) and type(eval(inches)) == int:
    print ("both are numbers!")
else:
    print ("That's not a Number!")

Here is my code, it works if I enter numbers for the values for feet and inches. However, if feet = a I get an error stating that a is undefined.

What am I doing wrong?

2
  • As an aside: if type(eval(feet)) and type(eval(inches)) == int means if bool(type(eval(feet))) and (type(eval(inches)) == int). It does not mean if type(eval(feet)) == int and type(eval(inches)) == int. Commented Feb 6, 2017 at 21:55
  • Or more succinctly: x and y == z means bool(x) and (y == z) not (x == z) and (y == z) If you need to test multiple items you can do all(item==z for item in (x, y)). If you need all items to be the same you can do {x, y} == {z}. Commented Feb 6, 2017 at 21:58

2 Answers 2

3

What you're doing wrong is using eval. That's never a good way to do anything.

Instead, try to convert to int and catch the exception:

try:
    feet = int(feet)
    inches = int(inches)
except ValueError:
    print("not numbers!")
else:
    print("numbers!")
Sign up to request clarification or add additional context in comments.

2 Comments

interesting! I have never heard of the Try command. Granted I am very new to python. Is there a good source to read about this method? I would like to understand what is going on more.
0

Don't use eval to test if user input is an integer. You get an error because the interpreter is trying to find a variable called a but there isn't one defined. Instead you can check if a string only contains digits.

def is_integer(s):
    for c in s:
        if not c.isdigit():
            return False
    return True

feet = input ("Enter your feet.")
inches = input ("Enter your inches.")

if is_integer(feet) and is_integer(inches):
    print ("both are numbers!")
else:
    print ("That's not a Number!")

This assumes that negative numbers are invalid.

1 Comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.