[BangPypers] Basic of basic question

Noufal Ibrahim noufal at nibrahim.net.in
Tue May 7 07:33:37 CEST 2013


Umesh Tiptur <umeshreloaded at yahoo.com> writes:

> Hi,
>
> I am very new to programming in python. But I want to know is user
> hass inputted a number or a string
>
> Please help with this HOW to..

Python doesn't have anything like C's scanf that can read input into
variables of fixed types. 

Anything that you read from the user (using raw_input[1]), will be
returned as a string. So even if the user types 2 and hits enter, you
will get back "2" (which is a string). 

To check whether this can be converted into a number, the usual way is
to try to use it like a number and catch the exception which will be
raised if the conversion fails. Here is a simple example. 

>>> x = "2"
>>> try:
...   int(x)
... except ValueError:
...   print "Not a number"
... 
2


>>> x = "abcd"
>>> try:
...   int(x)
... except ValueError:
...   print "Not a number"
... 
Not a number


[...]


Footnotes: 
[1]  http://docs.python.org/2/library/functions.html#raw_input

-- 
Cordially,
Noufal
http://nibrahim.net.in


More information about the BangPypers mailing list