For some reason, the book Introduction to Python3 that I read to study Python did not contain a description of standard input functions. : scream: However, it is a very convenient function to use, so I will leave a memorandum on how to use it.
The most basic usage is as follows. When executed, it will be in a state of waiting for input from standard input (usually keyboard). Enter the content you want to assign to the variable x, and finally enter Return to assign the input content to x.
Input example
>>> x = input()
5
>>> print(x)
5
It is also possible to display a message prompting for input. Pass the content you want to display as an argument of the input function.
Input example
>>> x = input("Enter a number: ")
Enter a number: 2
>>> print(x)
2
First, let's look at the return type of the input function. It is output as a character string type (str).
>>> x = input()
2
>>> print(type(x))
<class 'str'>
To extract it as an integer, cast it using the int function (float for floating point).
Input example
>>> x = int(input())
2
>>> print(type(x))
<class 'int'>
There are many cases where you want to enter multiple values from standard input at once. If you enter multiple values separated by spaces, they will be assigned to variables as shown below.
Input example
>>> x = input()
2 3 4
>>> print(x)
2 3 4
It is assigned as a string of multiple values concatenated with spaces. Therefore, multiple values can be retrieved at once by using the inclusion notation as shown below. (Casted with the int function and extracted as an integer type.)
Input example
>>> x, y, z = (int(x) for x in input().split())
2 3 4
>>> print(x, y, z)
2 3 4
>>> print(type(x), type(y), type(z))
<class 'int'> <class 'int'> <class 'int'>
You can assign it as a list by doing the following.
Input example
>>> x = input().split()
2 3 4
>>> print(x)
['2', '3', '4']
In this case, you end up with a list of strings. List comprehension is used to make a list of integer values.
Input example
>>> x = [int(x) for x in input().split()]
2 3 4
>>> x
[2, 3, 4]
You can control the number of values to retrieve by adding an enumerate statement and an if statement.
Input example
>>> x = [int(x) for i, x in enumerate(input().split()) if i < 3]
1 2 3
>>> print(x)
[1, 2, 3]
>>> x = [int(x) for i, x in enumerate(input().split()) if i < 3]
1 2 3 4
>>> print(x)
[1, 2, 3]
Recommended Posts