Wednesday, July 20, 2011

How to get user input in python?

In Python we can use the raw_input() and input() to take inputs from user.

Example for raw_input()..
>>> lastName = raw_input("What is your Last Name?")
What is your Last Name?pk
>>> firstName = raw_input("What is your First Name?")
What is your First Name?amala
>>> print("Is your name {0} {1}?".format(firstName, lastName))
Is your name amala pk?
>>>

Example for input()..
>>> x = input("Enter a number:")
Enter a number:6
>>> print x
6

Now let's think how these inputs are interpreted....
Using raw_input, the data is always interpreted as a string...Using input, the data is always interpreted as integer type...

We can check this...

>>> a=raw_input()
5
>>> print type(a)
>>> digit=int(a)
>>> print type(digit)
>>>

also

>>> a=input()
6
>>> print type(a)
>>> string=str(a)
>>> print type(string)

Thus we can use int() and str() to convert to integer type and string type respectively.



No comments:

Post a Comment