Previous | Next


You may have written a program that you need an input from user in order to continue the processing. Let’s take a look at the useful function to handle this.

input()

Let’s try to get user input with the following sample code:

>>> input("Enter value: ")
Enter value: 90
90

When you press the Enter button after key in 90, it then accepted by the interpreter and print it out. Let’s try with another sample using the input function.

>>> input("Enter name: ")
Enter name: askyb

Traceback (most recent call last):
  File "<pyshell#34>", line 1, in <module>
    input("Enter name: ")
  File "<string>", line 1, in <module>
NameError: name 'askyb' is not defined

Aaarrhhhh…. the interpreter raise a NameError exception. What’s wrong with the input? The problem is that input assumes that what you enter is a valid Python expression rather than a string. Try again with the following sample

>>> input("Enter name: ")
Enter name: 'askyb'
'askyb'

It work! Noticed that I’ve included a single quote at the beginning and closing of the string. This tell the interpreter that my input is rather a string than an expression. Try again with the following sample and it should work as well.

>>> name = 'askyb'
>>> input("Enter name: ")
Enter name: name
'askyb'

Well, if you think input() may not sound handy for you, then you should consider using the raw_input() function for general input from users.

raw_input()

raw_input() read input from user and it converts the value to a string (stripping a trailing newline). Let’s try to get user input with the following sample code:

>>> raw_input("Enter value: ")
Enter value: 90
'90'

>>> raw_input("Enter name: ")
Enter name: askyb
'askyb'

Noticed that all the value are converted into string format which come with a single open quote and close quote.

 


Previous | Next