Solved

Verifying type in input

Posted on 2004-10-13
3
264 Views
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,
Brian
0
Comment
Question by:bnblazer
  • 2
3 Comments
 
LVL 11

Expert Comment

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

 
0
 
LVL 11

Accepted Solution

by:
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:
    try:
        num = int( raw_input( "Enter a number: " ) )
        print 'num is definitely an integer number'
    except ValueError:
        num = None
0
 
LVL 1

Author Comment

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

Brian
0

Featured Post

Networking for the Cloud Era

Join Microsoft and Riverbed for a discussion and demonstration of enhancements to SteelConnect:
-One-click orchestration and cloud connectivity in Azure environments
-Tight integration of SD-WAN and WAN optimization capabilities
-Scalability and resiliency equal to a data center

Question has a verified solution.

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

Plenty of writing has gone on the web trying to compare Python with other competitive programming languages and vice versa. However, not much has been put into a wholistic perspective. This article should help you decide whether to adopt Python as a…
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…

820 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