What is Python Input?
With Python, input can be requested from the user by typing input()
. This input will usually be assigned to a variable, and it’s often best to have a user-friendly prompt when requesting the input.
If you’re expecting a specific type of input, such as an integer, it’s useful to perform an explicit conversion on the input before storing it in your variable.
For example, an explicit conversion to an int
:
integer_input = int(input("Please enter an integer between 1 and 10"))
Throughout this guide, you’ll find a wide range of code samples for retrieving input from a user.
Single Input
Retrieving a single input from the user is a good starting point. The code below shows how to request a single input, convert it, and assign it to a variable. We’ll then confirm that the conversion was successful by checking the data type of the variable.
Example 1: Simple single input requests from user# Explicit conversion to each of the 4 primitive variable types in Python: # These are: String, Int, Float, Boolean # Simple string input string_input_1 = input("Please type your first name: ") print("Name is {}. Data Type: {}".format(string_input_1, type(string_input_1))) # Simple string input string_input_2 = str(input("Please type your first name: ")) print("Name is {}. Data Type: {}".format(string_input_2, type(string_input_1))) # Simple integer input integer_input = int(input("Please type a number between 1 and 10: ")) print("Number is {}. Data Type: {}".format(integer_input, type(integer_input))) # Simple float input float_input = float(input("Please type a decimal between 1 and 2: ")) print("Decimal is {}. Data Type: {}".format(float_input, type(float_input))) # Simple Boolean input bool_input = bool(input("Please type true or false: ")) print("Boolean is {}. Data Type: {}".format(bool_input, type(bool_input)))
Output:
Please type your first name: Daniel
Name is Daniel. Data Type:
Please type your first name: Daniel
Name is Daniel. Data Type:
Please type a number between 1 and 10: 5
Number is 5. Data Type:
Please type a decimal between 1 and 2: 1.67
Decimal is 1.67. Data Type:
Please type true or false: true
Boolean is True. Data Type:
Multiple Inputs
There are many situations where you may need to read in multiple inputs from a user. One example is where a user will enter a number on the first line, representing how many lines of data they plan to enter next.
This is a common feature of Python coding questions on sites such as HackerRank, so we’ll build up to demonstrating one of these in our examples.
Multiple Inputs on a Single Line
By comma separating multiple calls to input()
, we’re able to display multiple prompts to the user, and store the responses in variables.
Example 1 shows two inputs; one integer and one string. The integer is assigned to var1
and the string is assigned to var2
.
# Create the variables and assign the user inputs var1, var2 = (int(input("Enter an integer: ")), input("Enter a string: ")) # Input provided by user: # ----------------------- # Enter an integer: 1 # Enter a string: test # Display the inputs entered by the user print("var1 = {0}\nvar2 = {1}".format(var1, var2))
Output:
var1 = 1
var2 = test
Example 2 shows two inputs; one integer and one being a collection of strings separated by spaces. The integer is assigned to var1
and the collection of strings is split into a list, before being assigned to var2
.
# Create the variables and assign the user inputs var1, var2 = (int(input("Enter an integer: ")), input("Enter strings separated by a space: ").split()) # Input provided by user: # ----------------------- # Enter an integer: 1 # Enter a string: This is a split string. # Display the inputs entered by the user print("var1 = {0}\nvar2 = {1}".format(var1, var2))
Output:
var1 = 5
var2 = ['This', 'is', 'a', 'split', 'string.']
Multiple Inputs from Multiple Lines
Now we’re going to look at a more complex example. This is taken from the Collections.namedtuple() problem on HackerRank.
Collections.namedtuple() Task:In short, we’re looking for 3 main inputs:
- Input 1: The number of lines of data to be entered
- Input 2: The column names for the data
- Input 3: The data
So, using what we’ve learned about input()
, let’s look at how this can be solved.
The first input will be the number of lines of data to accept after the column names. We’ll store this in the students
variable.
The second input will be a series of space-separated strings, to be used as the column names. We’ll store this in the column_names
variable.
# Assign our first 2 inputs to their variable names (students, column_names) = (int(input("No. of students: ")), input("Column Names:\n").split())Step 2: Create a namedtuple() and use Input 2 as a source for the field names
The list we created by splitting Input 2 now contains the column names. We can pass this to the field_names
parameter of our named tuple.
# Create the Grade named tuple Grade = namedtuple('Grade', column_names)
You can find out more about named tuples and their use cases in our guide to the Python collections module.
Step 3: Prompt user for data rowsThis is the step that requires most of the logic.
We know how many lines of data to expect from Input 1, which we stored in the students
variable. This is how many times we’ll need to send the input
prompt to the user.
We also know how many fields of data to expect, and that we can split the input on white space, same as we did for the field names.
So, all that’s left is to:
- Iterate
students
number of times - At each iteration, prompt the user for input
- At each iteration, split this input and assign values to the fields of our
Grade
named tuples - Store the
MARKS
values in an object that can easily be used to find the average
This can all be done with a single line:
# Create a list of MARKS collected from user input marks = [int(Grade._make(input().split()).MARKS) for _ in range(students)]Step 4: Calculate the average grade
So, now we have a list containing all our MARKS, the easy part is calculating the average, by dividing the sum
by the len
.
# Calculate the average mark print("\nAverage Grade = {}".format((sum(marks) / len(marks))))Step 5: Full solution
So, let’s combine steps 1 to 4 and check that our code produces the correct output.
from collections import namedtuple (students, column_names) = (int(input("No. of students: ")), input("Column Names:\n").split()) Grade = namedtuple('Grade', column_names) marks = [int(Grade._make(input().split()).MARKS) for _ in range(students)] print("\nAverage Grade = {}".format((sum(marks) / len(marks))))
Output:
No. of students: 5
Column Names:
ID MARKS NAME CLASS
1 97 Raymond 7
2 50 Steven 4
3 91 Adrian 9
4 72 Stewart 5
5 80 Peter 6
Average Grade = 78.0