GETTING INPUT FROM THE USER
The builtin input function requests and obtains user input:
In [2]: name
Out[2]: 'Paul'
Paul
The snippet executes as follows:
- First, input displays its string argument—a prompt—to tell the user what to type and waits for the user to respond. We typed Paul and pressed Enter. We use bold text to distinguish the user’s input from the prompt text that input displays.
- Function input then returns those characters as a string that the program can use. Here we assigned that string to the variable name.
Snippet [2] shows name’s value. Evaluating name displays its value in single quotes as 'Paul' because it’s a string. Printing name (in snippet [3]) displays the string without the quotes. If you enter quotes, they’re part of the string, as in:
What's your name? 'Paul'
In [5]: name
Out[5]: "'Paul'"
Function input Always Returns a String
Consider the following snippets that attempt to read two numbers and add them:
Enter first number: 7
Enter second number: 3
In [9]: value1 + value2
Out[9]: '73'
Rather than adding the integers 7 and 3 to produce 10, Python “adds” the string values '7' and '3', producing the string '73'. This is known as string concatenation. It creates a new string containing the left operand’s value followed by the right operand’s value.
Getting an Integer from the User
If you need an integer, convert the string to an integer using the built-in int function:
Enter an integer: 7
In [11]: value = int(value)
In [12]: value
Out[12]: 7
We could have combined the code in snippets [10] and [11]:
Enter another integer: 13
In [14]: another_value
Out[14]: 13
Variables value and another_value now contain integers. Adding them produces an integer result (rather than concatenating them):
Out[15]: 20
If the string passed to int cannot be converted to an integer, a ValueError occurs:
Enter another integer: hello
ValueError: invalid literal for int() with base 10: 'hello'
Function int also can convert a floatingpoint value to an integer:
Out[17]: 10
To convert strings to floatingpoint numbers, use the built-in float function.