The input() method in Python

The input() method is a built-in method offered by Python that allows a user to provide their input in any desired format by pausing the normal execution of the code.

Let’s take an example where we prompt the user for input. When the code reaches the line, it will pause until the input is entered.

user_input = input()
print(user_input)

Enter the input below

input() with prompt

The input() method also provides an option to give the user a specific prompt that explains what they’re expected to input. For instance, the prompt could be a question or the name of the desired variable.

user_name = input("Add your name here = ")
print("Welcome to Educative, ", user_name)

Enter the input below

Input type casting

No matter what input the user gives to the program, Python will always convert it to a string literal by default. If any other input is expected from the user, it can be converted to the desired type by input type casting.

while True:
try:
total_marks = input("Enter your score here = ")
total_marks_int = float(total_marks)
break
except ValueError:
print("The input added was not a valid value")
print("Total marks entered = ", total_marks_int)

Enter the input below

Input validation

An important concept when handling user input is to ensure that inputs with unexpected formats are not entered. For instance, if the code is asking for the user’s age and the user enters letters or characters, variable assignment could result in an error. Such concerns can be resolved by validating the input before processing it.

Let’s suppose the following code retrieves the total marks from a user and validates the type of input before it assigns or uses the input elsewhere.

while True:
try:
total_marks = input("Enter your score here = ")
total_marks_int = float(total_marks)
break
except ValueError:
print("The input added was not a valid value")
print("Total marks entered = ", total_marks_int)

Enter the input below