Input Python – keyboard input

by Alex
Input Python - keyboard input

As discussed in the previous article, a program is, more often than not, a data processor that requires both input and output of that very data. In this lesson, we will talk about the easiest way to get data from the user in Python: read it from the console with input().

Input in Python

Python has an input() function designed to read data entered by the user into the console from the keyboard. When input() is called, the program flow is stopped until the user has input to the terminal. The user must press “Enter” to complete the input. The input() function then reads the data entered by the user and automatically converts it to a string type, even if it is numbers:


variable = input()
print('variable:', variable)
print(type(variable))
# Output:
2
variable: 2

Converting input data

If you want to use the data you enter as something other than a string type, you have to convert the data type yourself. We already talked about type conversions, but let’s refresh our knowledge.

Input() to int

If you need to get an integer, use the int() function:


variable = input()
print('variable:', variable)
print(type(variable))
new_variable = int(variable)
print('new_variable:', new_variable)
print(type(new_variable))
# Output:
3
variable: 3
new_variable: 3

The same can be done much shorter using the power of Python:


print('variable: {}'.format(variable := int(input())), type(variable), sep='\n')
# Output:
10
variable: 10

Input() to float

If you want to get a floating-point number (not an integer), use float().


variable = float(input())
print('variable:', variable)
print(type(variable))
# output:
5
variable: 5.0

Input() to list

Using some tricks, you can convert the data returned by input() into a list or other list-like collection. To do this, use the split() method of the string to split it into elements, using some separator. An example with a space as a separator:


variable = input().split()
print(variable)
print(type(variable))
# output:
1 2 3
['1', '2', '3']

Example with a comma as separator:


variable = input().split(',')
print(variable)
print(type(variable))
# Output:
1,2,3
['1', '2', '3']

In both cases, the elements are still of string type:


variable = input().split(',')
print(variable)
print(type(variable))
print(list(map(type, variable)))
# Output:
1,2,3
['1', '2', '3']
[, , ]

If you need to convert them too, you can use the type conversion function again in conjunction with the loop:


variable = list()
for element in input().split():
variable.append(complex(element))
print(variable)
print([type(num) for num in variable])
# Output:
999 333 666
[(999+0j), (333+0j), (666+0j)]
[, , ]

You can also use list inclusion, which looks more concise:


variable = [complex(element) for element in input().split()]
print(variable)
print([type(num) for num in variable])
# Output:
999 333 666
[(999+0j), (333+0j), (666+0j)]
[, , ]

But perhaps the “cleanest” and most productive way to do this is located in the very bowels of functional programming – a higher-order function:


variable = list(map(complex, input().split()))
print(variable)
print([type(num) for num in variable])
# Output:
999 333 666
[(999+0j), (333+0j), (666+0j)]
[, , ]

input() to dict (dictionary)

Unfortunately, attempts to simply convert input() to dict only lead to perversions:


variable = dict()
input_data = input().split()
for i, element in enumerate(input_data):
if i % 2 == 0 and len(entered_data) - i > 1:
variable[element] = complex(entered_data[i + 1])
print(variable)
print('Key type:', [type(num) for num in variable])
print('Type of values:', [type(num) for num in variable.values()])
# Output:
{'first_element 12 second_element 54
{'first_element': (12+0j), 'second_element': (54+0j)}
Key type: [, ]
Value type: [, ]

But, as you can see, it works.

Entering into multiple variables

If you need to fill several variables at once with a single keyboard input, use unpacking:


variable, more_variable, last_variable = input().split()
print('Variable:', variable)
print('another_variable:', another_variable)
print('Last_variable:', last_variable)
# Conclusion:
Don't_believe Don't_fear Don't_ask
Variable: don't_believe
# Another_variable: Don't_be_fearful
Last_variable: Don't_ask

Don’t forget that all variables after unpacking will be of string type, and that there should be as many inputs as variables:

  • if there are more entered values than variables, you will get an error – ValueError: too many values to unpack (expected 3);
  • if entered values are less than variables, you will get an error – ValueError: not enough values to unpack (expected 3, got 2);

This can be avoided by using another trick: unpacking from the left))


variable, *other_variable, *other_items = input().split()
print('Variable:', variable)
print('another_variable:', another_variable)
print('other_items:', other_items)
# Conclusion:
Don't_believe Don't_fear Don't_ask And_behave
Variable: Don't_believe
Another_variable: Don't_be_fear
Other_elements: ['Don't_ask', 'And_be_fear']

Parameter prompt

If you use the input() function as we did in the examples above, it will not be clear to the user what is required of him, because the program will simply stop. It would be a good idea to print an explanation:


print('enter something: ')
input()
# output:
Type something:
anything

Fortunately, the input() function itself provides this feature – you can pass the message to the user as a positional argument to the function (or by the name of the promt parameter, but nobody does that) and the message will be displayed on the screen:


input('input something: ')
# Output:
Enter something: something

Handling input exceptions

An ancient computer wisdom says, “don’t trust the user.” The point is that user input is the place through which information gets into the program. Here you can draw an analogy with the mouth through which the food gets into the body. You don’t put everything in your mouth, do you? We certainly hope not! To continue the analogy, food (user input) can be dangerous (viruses, sql injections and other attacks) or simply not edible (we expect an e-mail address from the user and he enters his home address). There are a number of professions dedicated to dealing with these threats: pintsters and various information security engineers. In general, it is always worth sticking to the rule: user input must be verified! Let’s have a little fight with an imaginary programmer. Here is a code that trustingly expects the user to enter a number from 1 to 100:


from math import sqrt
variable = input('Enter a number between 1 and 100: ')
variable = int(variable)
print('The root of your number is: ', sqrt(variable))
# Output:
Enter a number between 1 and 100: six
Traceback (most recent call last):
File "C:\Users\ivand\AppData\Roaming\JetBrains\PyCharm2021.2\scratches\scratch.py", line 4, in
variable = int(variable)
ValueError: invalid literal for int() with base 10: 'six'
Process finished with exit code 1

Let’s add a check that it’s not letters:


from math import sqrt
variable = input('input a number between 1 and 100: ')
while True:
for i in variable:
if i.isalpha():
print('Enter a number (in DIGITS)!')
variable = input('input a number between 1 and 100: ')
break
else:
break
variable = int(variable)
print('The root of your number is: ', sqrt(variable))
# Output:
Enter a number between 1 and 100: six
Type a number (in DIGITS)!
Enter a number between 1 and 100: ,,
Traceback (most recent call last):
File "C:\Users\ivand\AppData\Roaming\JetBrains\PyCharm2021.2\scratches\scratch.py", line 13, in
variable = int(variable)
ValueError: invalid literal for int() with base 10: ',,'
Process finished with exit code 1

Well, let’s add a check to make sure it’s a number:


from math import sqrt
variable = input('input a number between 1 and 100: ')
while True:
for i in variable:
if not i.isnumeric():
print('Enter a number (in NUMERIC)!')
variable = input('input a number between 1 and 100: ')
break
else:
break
variable = int(variable)
print('The root of your number is: ', sqrt(variable))
# Output:
Enter a number between 1 and 100: 20.5
Print a number (in DIGITAL NUMBER)!
Type a number between 1 and 100: Ⅻ
Traceback (most recent call last):
File "C:\Users\ivand\AppData\Roaming\JetBrains\PyCharm2021.2\scratches\scratch.py", line 13, in
variable = int(variable)
ValueError: invalid literal for int() with base 10: 'Ⅻ'
Process finished with exit code 1

That’s it, no more of this! Let’s check that the user enters an integer:


from math import sqrt
variable = input('input a number between 1 and 100: ')
while True:
for i in variable:
if not i.isdigit():
print('Enter a NUMBER (NUMBER ONLY)!!!')
variable = input('enter a number between 1 and 100: ')
break
else:
break
variable = int(variable)
print('The root of your number is: ', sqrt(variable))
# Output:
Enter a number between 1 and 100: Ⅻ
Enter a NUMBER (NUMBER ONLY)!!!
Enter a number between 1 and 100: 1000000
The root of your number is:  1000.0
Process finished with exit code 0

Here, technically, everything went smoothly, but the entered value is not in the required range. As you can see, it’s not that easy. Another way is to accept any user input and then “catch” errors inside the program:


from math import sqrt
while True:
variable = input('Enter a number between 1 and 100: ')
try:
variable = int(variable)
except:
print('Enter a NUMBER (NUMBER ONLY)!!!')
else:
break
print('The root of your number is: ', sqrt(variable))
# Output:
Enter a number between 1 and 100: six
Enter a NUMBER (NUMBER ONLY)!!!
Enter a number between 1 and 100: 6
The root of your number is:  2.449489742783178
Process finished with exit code 0

But exception handling is not as simple as it may seem (you can read more about exceptions in our article). Moreover, this approach does not protect against targeted attacks:


while True:
variable = input('Enter expression: ')
try:
print('Expression result:', eval(variable))
except:
print('Enter a Python expression!')
else:
break
# Output:
Type expression: Attempted attack
Type a Python expression!
Type the expression: 'I' + ' downloading' + ' scary' + ' virus!
Expression result: I'm downloading a scary virus!

Terminal emulation with input().

To demonstrate the power of this function, here is an excerpt from the official documentation:


def run_user_code(envdir):
source = input(">>> ")
try:
# Execute the entered code from the keyboard
exec(source, envdir)
except Exception as e:
print("Exception in user code:")
print("-"*60)
print(str(e))
print("-"*60)
# dictionary for storing typed variables
envdir = {}
while True:
run_user_code(envdir)
# output:
>>> variable = 2
>>> second_variable = 3
>>> print('sum of variables is:', variable + second_variable)
sum of variables equals: 5
>>> 1 / 0
Exception in user code:
------------------------------------------------------------
division by zero
------------------------------------------------------------
>>>

Practical work

  1. Write a program that would ask the user for his first name, middle name and last name. After that, it would print a string:

“Hello,

  1. Write a program that prompts the user to solve an example 666 * 333 // 54. Then it would display the correct answer and the user’s answer.
  2. Ask the user for three numbers and two arithmetic signs. Print the result of performing these operations in sequence.

Related Posts

LEAVE A COMMENT