Verifying type in input

Posted on 2004-10-13
Last Modified: 2010-04-16
I would like to be able to verify the type of input from an input statement, but I can't seem to be able to figure it out.  For example:

num=raw_input("Enter a number: ")

I would like to then verify that num is an int.

I am sure that it is a bit more easy than in java, and that is probably my problem...I am looking to far into it and can't see the forest through the trees.

Thanks for your help,
Question by:bnblazer
  • 2
LVL 11

Expert Comment

ID: 12305582
num = None
while not num:
        num = int( raw_input( "Enter a number: " ) )
        print 'num is definitely an integer number'
        num = None

LVL 11

Accepted Solution

cjjclifford earned 125 total points
ID: 12305593
basically, cast the result of raw_input() to int() (or float() if you want decimal places), catching exception in the case where the cast fails...

probably better to explicitly catch the correct exception, so other errors are not hidden...

num = None
while not num:
        num = int( raw_input( "Enter a number: " ) )
        print 'num is definitely an integer number'
    except ValueError:
        num = None

Author Comment

ID: 12306921
Thank you, that is exactly what I was looking for.


Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Dictionaries contain key:value pairs. Which means a collection of tuples with an attribute name and an assigned value to it. The semicolon present in between each key and values and attribute with values are delimited with a comma.  In python we can…
When we want to run, execute or repeat a statement multiple times, a loop is necessary. This article covers the two types of loops in Python: the while loop and the for loop.
Learn the basics of strings in Python: declaration, operations, indices, and slicing. Strings are declared with quotations; for example: s = "string": Strings are immutable.: Strings may be concatenated or multiplied using the addition and multiplic…
Learn the basics of while and for loops in Python.  while loops are used for testing while, or until, a condition is met: The structure of a while loop is as follows:     while <condition>:         do something         repeate: The break statement m…

867 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

21 Experts available now in Live!

Get 1:1 Help Now