In this tutorial, I will explain how to use the input() function in Python. As a Python programmer it very essential to know the uses of the input() function to take user input in Python. Let us learn more about the input() function with suitable examples and screenshots.
Use the Input() Function in Python
The input() function in Python is used to take user input. By default, it returns the user input as a string. The basic syntax of the input() function is as follows:
user_input = input(prompt)Here, prompt is an optional parameter that allows you to display a message to the user before waiting for their input. This message acts as a prompt, guiding the user on what kind of input is expected.
Read How to Use Default Function Arguments in Python?
Capture User Input with the Input Function
Let’s get into a real-world example to understand how the input() function works. Suppose you’re developing a program that collects user information for a survey in the United States. Here’s how you can use the input() function to capture the user’s name and age:
name = input("Please enter your name: ")
age = input("Please enter your age: ")
print("Hello, " + name + "! You are " + age + " years old.")Output:
Please enter your name:
Please enter your age:You can look at the output in the screenshot below.

In this example, the input() function is used twice. The first input() prompts the user to enter their name, while the second input() prompts for their age. The user’s responses are stored in the variables name and age, respectively. Finally, the captured information is printed back to the user.
Check out How to Exit a Function in Python?
Handle Different Data Types
It’s important to note that the input() function always returns a string. If you need to work with other data types, such as integers or floats, you’ll need to explicitly convert the user input. Here’s an example that demonstrates how user input is converted to an integer:
num_students = input("Enter the number of students in your class: ")
num_students = int(num_students)
print("There are " + str(num_students) + " students in your class.")Output:
Enter the number of students in your class:You can look at the output in the screenshot below.

In this case, the user’s input is initially stored as a string in the num_students variable. To perform mathematical operations or comparisons, we convert the input to an integer using the int() function. When printing the result, we convert the integer back to a string using the str() function to concatenate it with the rest of the message.
Read How to Call a Function Within a Function in Python?
Validate User Input
When working with user input, it’s crucial to validate the data to ensure it meets your program’s requirements. Let’s consider a scenario where you’re asking users to enter their state of residence. You want to make sure that the input is a valid two-letter state code. Here’s how you can validate the user input:
state = input("Enter your state code (e.g., CA for California): ")
valid_states = ["AL", "AK", "AZ", "AR", "CA", "CO", "CT", "DE", "FL", "GA",
"HI", "ID", "IL", "IN", "IA", "KS", "KY", "LA", "ME", "MD",
"MA", "MI", "MN", "MS", "MO", "MT", "NE", "NV", "NH", "NJ",
"NM", "NY", "NC", "ND", "OH", "OK", "OR", "PA", "RI", "SC",
"SD", "TN", "TX", "UT", "VT", "VA", "WA", "WV", "WI", "WY"]
while state.upper() not in valid_states:
state = input("Invalid state code. Please enter a valid two-letter state code: ")
print("You reside in " + state.upper() + ".")Output:
Enter your state code (e.g., CA for California):You can look at the output in the screenshot below.

In this example, we define a list called valid_states that contains all the valid two-letter state codes for the United States. After prompting the user to enter their state code, we use a while loop to continuously prompt the user until a valid state code is provided. The upper() function is used to convert the user input to uppercase for case-insensitive comparison.
Check out How to Use Static Variables in Python Functions?
Handle Empty Input
Sometimes, users may accidentally or intentionally provide empty input. It’s important to handle such cases gracefully to prevent errors or unexpected behavior in your program. Here’s an example that demonstrates how to handle empty input:
while True:
city = input("Enter your city: ")
if city.strip():
break
print("City cannot be empty. Please enter a valid city.")
print("You live in " + city + ".")In this code snippet, we use a while loop to repeatedly prompt the user for their city until a non-empty value is provided. The strip() function is used to remove any leading or trailing whitespace from the user input. If the input is empty (i.e., contains only whitespace or nothing), the loop continues, and an error message is displayed. Once a non-empty city is entered, the loop breaks and the city is printed.
Read How to Use Python Functions with Optional Arguments?
Incorporate Input Validation into Functions
To promote code reusability and maintainability, it’s a good practice to encapsulate input validation logic into functions. Here’s an example that demonstrates how to ask for user input within a function:
def get_positive_number(prompt):
while True:
num = input(prompt)
try:
num = float(num)
if num > 0:
return num
else:
print("Please enter a positive number.")
except ValueError:
print("Invalid input. Please enter a valid number.")
age = get_positive_number("Enter your age: ")
height = get_positive_number("Enter your height in inches: ")
print("You are " + str(age) + " years old and " + str(height) + " inches tall.")In this example, we define a function called get_positive_number() that takes a prompt as input and repeatedly asks the user for a positive number until a valid input is provided. The function handles invalid inputs by catching the ValueError exception and displaying an appropriate error message. The function returns the validated positive number.
Read How to Use Lambda Functions in Python?
Conclusion
In this tutorial, I helped you learn how to use the input() function in Python. I discussed capturing user input with the input function, handling different data types, validating user input, handling empty input, and incorporating input validation into functions.
You may like to read:
- How to Use Counter Function in Python?
- How to Use Exponential Functions in Python?
- How to Use the Python Main Function with Arguments?

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.