benjiboi79
benjiboi79

Reputation: 33

How do I check an input for an integer in Python?

I used:

day = int(input('Please input the day you were born: e.g 8th=8 21st = 21 : '))
month = int(input('Please input the month you were born: e.g may = 5 december = 12 : '))
year = int(input('Please input the year you were born: e.g 2001 / 1961 : '))

if day == int and month == int and year == int:

But it always even when it's an integer says it's wrong.

Upvotes: 3

Views: 77

Answers (3)

Joran Beasley
Joran Beasley

Reputation: 114048

def get_int(p,error_msg="Thats Not An Int!"):
    while True:
         try:
            return int(raw_input(p))
         except (ValueError,TypeError):
            print "ERROR: %s"%error_msg

day = get_int('Please input the day you were born: e.g 8th=8 21st = 21 : ')
#day is guaranteed to be an int

I like to take this and abstract it further

 def force_type(type_class,prompt,error_msg):
     while True:
         try:
            return type_class(prompt)
         except (ValueError,TypeError):
            print error_msg

then it simply becomes

 def get_int(p,err_msg):
     return force_type(int,p,err_msg)
 def get_float(p,err_msg):
     return force_type(float,p,err_msg)
 ...

allthat said if you want to typecheck you should ~not~ use type(var) you should use isinstance(var,int)

Upvotes: 9

Mr. E
Mr. E

Reputation: 2120

To check type you can do:

type(aVar) is aType

Anyway, as Kevin said in a comment you're already wrapping input to int, so either it's actually an int or your program crashed

Upvotes: 1

AbtPst
AbtPst

Reputation: 8018

try

if type(day) == int and type(month) == int and type(year) == int

Upvotes: 0

Related Questions