Getting Information from the Keyboard

In Chapter 3, Designing and Using Functions, we 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 looks like a number:

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

The second and sixth lines of that example, Homo sapiens and 6973738433, were typed by us in response to the calls on 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()
 6973738433
 >>>​​ ​​population
 '6973738433'
 >>>​​ ​​population​​ ​​=​​ ​​int(population)
 >>>​​ ​​population
 6973738433
 >>>​​ ​​population​​ ​​=​​ ​​population​​ ​​+​​ ​​1
 >>>​​ ​​population
 6973738434

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

 >>>​​ ​​population​​ ​​=​​ ​​int(input())
 6973738433
 >>>​​ ​​population​​ ​​=​​ ​​population​​ ​​+​​ ​​1
 6973738434

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

 >>>​​ ​​species​​ ​​=​​ ​​input(​​"Please enter a species: "​​)
 Please enter a species: ​Python curtus
 >>>​​ ​​print(species)
 Python curtus
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.139.97.40