0

Im trying to make my variable integer input to be only == to an integer, and if its not I want to print and error message. I have put this in a if statement. I always get an error when I input a string instead of my error message.

age = int(input("Enter age:")) if age != int: print("Not a number") 
2
  • here is a discussion about how to test if a string represents an integer in python or not: stackoverflow.com/questions/3501382/… Commented Oct 7, 2015 at 17:20
  • this is for python 3, right? Commented Oct 7, 2015 at 17:26

2 Answers 2

2

you have to use raw_input instead of input

if you want this to repeat until you have the correct value you can do this

while True: try: age = int(raw_input("Enter age:")) except ValueError: print("Not a number") if age == desired_age: # note I changed the name of your variable to desired_age instead of int break 

I dont recommend you use variable names like int... its generally a bad practice

Sign up to request clarification or add additional context in comments.

7 Comments

still getting a traceback error. thanks for the suggestion though.
@PatrickCallahan did you see my latest edit? there isn't a way you could be
that looks like something the OP might want. let's see... +1
yea that answered my question on how to handle an input if its not an integer. im new to programming so forgive me lol
@PatrickCallahan cool! yea StackOverflow is the place to go for programming questions. some basic things to know... when you cast anything to a type you need to wrap it in a try except because it will raise an exception if the input is invalid. the while loop I put in there will continue to prompt user input until the correct value is inputted.. if you want to get a specific age :) dont forget to mark an answer as accepted (doesn't have to be mine) so this question can be closed! :)
|
2

from the discussion i posted the link above:

age = input("Enter age:") # raw_input("Enter age:") in python 2 try: age = int(age) except ValueError: print('not a number!') 

the idea is to try to cast age to an integer.

your attempt of age != int will always fail; age is a string (or an int if you were successful in casting it) and int is a class.

4 Comments

not sure that is the problem the OP had. he was already casting it to an int in the previous line. It looks like int is a variable name
yea.... Its hard to tell since people use types as variable names O.o strange imo. but nice answer all around +1 :)
So i have to convert the variable using the int()? And that did work, thanks
yes, you try to cast it to an int an hope that works. checking for a string that is a valid int yourself is surprisingly difficult...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.