How to obtain an user input with Python raw_input function example

The Python raw_input() function is used to read a string from standard input such as keyboard. This way a programmer is able to include user inserted data into a program. Let’s start with a simple example using python script to ask for an user name.

print "What is your name?"
name = raw_input()
print "Hello %s!" % name

First, we print string What is your name? telling the user what we expect him to input. Next, using the raw_input() function the standard input is assigned to a variable name. Lastly, we print the value of variable name to standard output.

$ python input.py 
What is your name?
Monty Python
Hello Monty Python!

Depending on your needs the above python raw_input() example program can be also abbreviated to a single line while including additional new line character \n:

print "Hello %s!" % raw_input("What is your name?\n")

It is important to point out that python function raw_input() will produce string and thus its output cannot be treated as an integer. Therefore, when using python’s raw_input() function to obtain an integer as an user input, the obtained input string must be first converted to an integer before it can be used as an integer.
Example:

print "What integer you wish to multiply by 2?"
number = int(raw_input())
print "The answer is: %s" % (number * 2)

# Alternative shortened version
print "The answer is: %s" % (int(raw_input("What integer you wish to multiply by 3?\n")) * 3)

Output:

$ python input.py 
What integer you wish to multiply by 2?
33
The answer is: 66
What integer you wish to multiply by 3?
33
The answer is: 99


Comments and Discussions
Linux Forum