Книга: Practical Programming, Fourth Edition
Назад: Printing Information
Дальше: Formatted Strings

Getting Information from the Keyboard

Provide input values using the input function

In Chapter 3, , you explored some built-in functions. Another built-in function is input, which reads a single line of text from the keyboard. It returns whatever the user enters as a string, even if it appears to be a number:

 >>>​​ ​​species​​ ​​=​​ ​​input()
 Homo sapiens
 >>>​​ ​​species
 'Homo sapiens'
 >>>​​ ​​population​​ ​​=​​ ​​input()
 8232458392
 >>>​​ ​​population
 '8232458392'
 >>>​​ ​​type(population)
 <class 'str'>

The second and sixth lines of that example, Homo sapiens and 8232458392, were typed in response to the calls to the function input.

If you are expecting the user to enter a number, you must use int or float to get an integer or a floating-point representation of the string:

 >>>​​ ​​population​​ ​​=​​ ​​input()
 8232458392
 >>>​​ ​​population
 '8232458392'
 >>>​​ ​​population​​ ​​=​​ ​​int(population)
 >>>​​ ​​population
 8232458392
 >>>​​ ​​population​​ ​​=​​ ​​population​​ ​​+​​ ​​1
 >>>​​ ​​population
 8232458393

You don’t actually need to stash the value that the call to input produces before converting it. This time, the function int is called on the result of the call to input and is equivalent to the previous code:

 >>>​​ ​​population​​ ​​=​​ ​​int(input())
 8232458392
 >>>​​ ​​population​​ ​​=​​ ​​population​​ ​​+​​ ​​1
 8232458393

Finally, input can be given a string argument s, which is used to prompt the user for input (notice the space at the end of your prompt):

 >>>​​ ​​species​​ ​​=​​ ​​input(​​"Please enter a species: "​​)
 Please enter a species: ​Python curtus
 >>>​​ ​​print(species)
 Python curtus

Since a Python program stops and waits for the user input when it encounters a call to input, it is fair to explain the reason for the pause to the users, especially when they are expected to enter more than one value.

Назад: Printing Information
Дальше: Formatted Strings