As you can print results on the screen, you can read data from the keyboard which is the standard input device. Python provides the raw_input function for that, which is used as follows:
>>> nb = raw_input("Enter a number, please:")
Enter a number, please:12
The prompt argument is optional and the input has to be terminated by a return.
![]() | Important |
|---|---|
raw_input always returns a string, even if you entered a number. Therefore you have to convert the string input by yourself into whatever you need. Table 4.3 gives an overview of all possible type conversion function.
>>> nb
'12'
>>> type(nb)
<type 'str'>
>>> nb = int(nb)
>>> nb
12
>>> type(nb)
<type 'int'>
Notice that a user can enter whatever he wants. So, the input is probably not what you want, and the type conversion can therefore fail. It is careful to test before converting input strings.
>>> nb = raw_input("Please enter a number:")
Please enter a number:toto
>>> nb
'toto'
>>> int(nb)
Traceback (most recent call last):
File "<stdin>", line 1, in ?
ValueError: invalid literal for int(): toto
The following function controls the input:
def read_number():
while 1:
nb = raw_input("Please enter a number:")
try:
nbconv = int(nb)
except:
print nb, "is not a number."
continue
else:
break
return nb
and produces the following output:
>>> read_number()
Please enter a number:toto
toto is not a number.
Please enter a number:12
'12'
| |
Table 4.3. Type conversion functions
| Function | Description |
|---|---|
| int(x [,base]) | converts x to an integer |
| long(x [,base]) | converts x to a long integer |
| float(x) | converts x to a floating-point number |
| complex(real [,imag]) | creates a complex number |
| str(x) | converts x to a string representation |
| repr(x) | converts x to an expression string |
| eval(str) | evaluates str and returns an object |
| tuple(s) | converts a sequence object to a tuple |
| list(s) | converts a sequence object to a list |
| chr(x) | converts an integer to a character |
| unichr(x) | converts an integer to a Unicode character |
| ord(c) | converts a character to its integer value |
| hex(x) | converts an integer to a hexadecimal string |
| oct(x) | converts an integer to an octal string |