The input function in Python
Now let's study the input function. It allows you to enter data in the console and save it for later use. Its optional parameter can be a string with a request for the user. After running the code, the user can enter data in the field to the right of the string. To save the entered data, you need to press the Enter key. The function returns a string as its result.
Example . Data output
Let's create a variable tst, the value of which will be the result of the function input. In its parameter, we will write a line asking to enter a number:
tst = input('enter number: ')
After running the code, the following line will be displayed in the console:
'enter number:'
To the right of the line you can enter any value. Let's write the number 12:
'enter number:' 12
After the user enters a number, it goes into the variable tst. Let's add a line to the code to display the variable value in the console for clarity:
print(tst)
Now, after entering the number, the console will also display the value of the variable tst:
'enter number:' 12
'12'
Example . Mathematical operations with entered numbers
Let's add one to the entered value:
tst = input('enter number: ')
print(tst + 1) # will display an error
This happens because the input function always returns a string as its result. Therefore, to perform mathematical operations, it must be converted to a number. This is done using the int function:
print(int(tst) + 1) # 13
Practical tasks
Ask the user to enter the current day of the week. Output it to the console.
Let there be two variables:
num1 = 10
num2 = input('enter number: ')
Get their sum and output it to the console.