Learn how to use Python’s input() function to interact with users, collect data, and build dynamic programs.
When you first start learning Python, you might write programs that just show text on the screen. That’s a great start—but what if you want your program to ask the user a question and wait for them to type an answer?
That’s where the input() function comes in.
In this post, I’ll teach you how to use the input() function in Python, even if you’re a complete beginner. We’ll go through easy examples so you can understand how to get user input in Python, step by step.
Whether you want to make a simple quiz, a calculator, or just greet someone by name, the input() function is the tool that helps your program talk to the user.
By the end of this post, you’ll understand:
input() function doesLet’s start learning.
input() Function in Python?Let’s say you want your Python program to ask the user something — maybe their name or age. You want the user to type a response, and you want your program to use that response.
To do this, we use the input() function.
input() do?The input() function does three simple things:
Whatever the user types is stored as text — even if they type a number.
This is what people mean when they say:
“input() returns a string.”
input("Your message here")
That part inside the quotation marks is optional, but it’s a good way to tell the user what to type.
Now let’s try a real example.
name = input("Enter your name: ")
print("Hello, " + name)
et me break it down for you:
input("Enter your name: ") shows the message: Enter your name:Alex) gets saved into the variable name.Pretty cool, right?
This is something many beginners miss.
Even if you type a number, like 25, Python will treat it as "25" — which is a string, not a number.
That’s why if you want to do math with input, you’ll need to convert it. But don’t worry — I’ll show you how to do that next.
Great! Now that you understand the basics of the input() function, let’s take it a step further and learn how to work with numbers.
Remember, the input() function always gives you text (string), even if the user types a number. So, if you want to do math with that input (like adding, subtracting, or multiplying), you need to convert the input into a number.
Let me show you how to do this.
When you’re asking for a number, you can use the int() or float() functions to convert the user input from a string into a number.
int() — Convert to an IntegerIf you want to ask the user for a whole number (no decimal points), you’ll use int() to turn the input into an integer.
Here’s how you do it:
age = input("Enter your age: ")
age = int(age) # This converts the input to an integer
print("Next year, you'll be", age + 1)
Let me explain what happens here:
25).input() function gives you "25" as a string.int(age) part converts that string "25" into the number 25.1 to the number and says:float() — Convert to a Float (Decimal Number)If you want to ask for a decimal number (like 5.5), use float(). This will convert the input into a float (a number with a decimal point).
Here’s an example:
price = input("Enter the price of the item: ")
price = float(price) # This converts the input to a float
print("The price with tax is", price * 1.2)
In this example:
19.99).input() function gives you "19.99" as a string.float(price) part converts "19.99" into the decimal number 19.99.1.2 to add tax, and shows the result.If you forget to convert the input and try doing math directly, Python will give you an error. Here’s an example of what won’t work:
age = input("Enter your age: ")
print(age + 5) # This will cause an error
The program will try to add a string (age) and a number (5), which doesn’t make sense to Python.
That’s why you always need to convert the input to the correct type—either int() for whole numbers or float() for decimals.
Let’s see how you do with a simple exercise:
# Ask for a number
num1 = input("Enter a number: ")
num2 = input("Enter another number: ")
# Convert to integers
num1 = int(num1)
num2 = int(num2)
# Add the two numbers
print("The sum of the numbers is:", num1 + num2)
This one will ask for two numbers, convert them into integers, and then add them together. Try it out!
Now, let’s take things to the next level: handling invalid user input. This is super important when you’re building real programs because users can sometimes type things that you didn’t expect—like letters when you’re asking for numbers. You don’t want your program to crash because of that!
Let’s walk through how we can handle invalid input in Python using try-except blocks. This is a technique that lets you catch errors and respond to them without crashing the program.
When you use input(), users might type something that doesn’t match what you expect. For example, if you ask for a number and they type in letters, it will cause an error.
To prevent your program from crashing, you can use a try-except block.
Let’s say you ask the user to enter a number, but they might type something like “abc” (instead of a number). You can catch that and show a helpful message.
Here’s how you do it:
try:
# Ask for a number
number = int(input("Enter a number: "))
# Print the square of the number
print("Squared:", number ** 2)
# Handle the error if the user didn't enter a valid number
except ValueError:
print("Oops! That wasn't a number.")
int().5), it squares the number and prints it.ValueError (because int() can’t handle non-numeric input).except block catches that error and prints a friendly message: Oops! That wasn’t a number.Without this, if the user types something wrong (like “hello”), the program will crash. With input validation in Python using try-except, your program keeps running smoothly, even if users make mistakes.
Let’s expand this a bit. Sometimes you want to handle multiple kinds of bad input—like asking for a float but the user enters letters or a blank space.
Here’s how you can handle more than one type of input error:
try:
# Ask for a number
number = float(input("Enter a number: "))
# Print the square of the number
print("Squared:", number ** 2)
except ValueError:
print("Oops! That wasn't a valid number.")
except KeyboardInterrupt:
print("\nYou cancelled the input.")
Ctrl + C to stop the program.Now, if the user does something wrong, like typing a letter or cancelling the input, the program handles it gracefully and doesn’t crash.
Try this: Let’s make a simple program that asks the user to enter their age, and if they type anything other than a number, the program tells them to try again.
while True:
try:
age = int(input("Enter your age: "))
print("Your age is:", age)
break # Exit the loop if the input is valid
except ValueError:
print("Oops! Please enter a valid number for your age.")
In this example:
Now you know how to handle invalid user input in Python! By using try-except blocks, your program can stay smooth and user-friendly even if someone types the wrong thing. This is essential for making reliable programs that don’t crash unexpectedly.
Alright, let’s take this to the next level and learn how to loop with input() for multiple entries. This is useful when you want your program to ask the user for input repeatedly until they decide to stop. You can do this with while loops or for loops.
input() for Multiple EntriesWhen you want to ask the user for input multiple times—maybe a list of items, numbers, or anything else—you can use loops to keep asking until certain conditions are met.
while LoopLet’s say we want the program to keep asking for text until the user types “exit”. This is where we use a while loop.
while True:
# Ask for input
text = input("Type 'exit' to stop: ")
# Check if the user typed "exit"
if text == "exit":
break # Exit the loop if they typed "exit"
# Otherwise, show what they typed
print("You typed:", text)
"exit", the program stops the loop with break."exit", the program simply shows what they typed and asks again.while LoopLet’s take this concept and ask the user for multiple numbers to add together. The loop will stop when they type "done".
total = 0
while True:
number = input("Enter a number (or 'done' to stop): ")
if number == "done":
break # Stop the loop if the user types 'done'
try:
# Convert the input to an integer
total += int(number)
except ValueError:
print("Oops! That wasn't a valid number.")
print("The total is:", total)
total = 0: We start by setting the total to zero."done"."done", the loop stops.try-except: We handle the case where the user types something other than a number."done" is typed, it shows the final total.55 to the total.1010 to the total."done"for Loops for Fixed RepetitionsIf you know exactly how many times you want to ask for input, a for loop can be useful. For example, let’s say we want to ask the user for their favorite 3 foods.
for i in range(3):
food = input("Enter your favorite food: ")
print("You like", food)
while loop when you don’t know how many times you’ll need to ask the user for input (like until they type "exit" or "done").for loop when you know the exact number of repetitions (like asking for 3 favorite foods).Let’s take a look at how the input() function can be used in real-world scenarios! We’ll cover a few practical examples: a simple calculator, a user login prompt, and a survey system. These examples show how to use user input to make your programs more interactive and dynamic.
We’re going to build a simple calculator that lets the user enter two numbers and an operator, then performs a calculation based on that input.
input(): Used to gather input from the user.float(): We’ll convert the input into numbers (because input from input() is always a string).if-else conditions: To choose which operation to perform (add, subtract, multiply, etc.).def calculator():
print("Welcome to the interactive calculator!")
while True: # This will make the calculator keep asking for input until the user decides to stop
# Step 1: Ask the user for the first number
num1 = float(input("Enter the first number: "))
# Step 2: Ask the user for an operator
operator = input("Enter operator (+, -, *, /): ")
# Step 3: Ask the user for the second number
num2 = float(input("Enter the second number: "))
# Step 4: Perform the operation based on the operator
if operator == "+":
result = num1 + num2
elif operator == "-":
result = num1 - num2
elif operator == "*":
result = num1 * num2
elif operator == "/":
if num2 != 0: # Prevent division by zero
result = num1 / num2
else:
print("Error: Division by zero!")
continue # Skip the rest of the loop if there's an error
else:
print("Invalid operator! Please try again.")
continue # Skip the rest of the loop and ask again
# Step 5: Display the result
print(f"The result is: {result}")
# Step 6: Ask if the user wants to continue
again = input("Do you want to calculate again? (yes/no): ")
if again.lower() != 'yes':
break # Exit the loop if the user says no
calculator()
+, -, *, or /, they’re asked to enter a valid operator.Now, let’s move on to creating a user login system. This is a very basic login system where the user is asked for a username and a password, and the system checks if they match pre-set values.
input(): Used to capture user input.if-else conditions: To check whether the username and password match.def login_system():
stored_username = "user123"
stored_password = "password456"
print("Welcome to the login system!")
# Step 1: Ask for the username
username = input("Enter your username: ")
# Step 2: Ask for the password
password = input("Enter your password: ")
# Step 3: Check if both match the stored values
if username == stored_username and password == stored_password:
print("Login successful!")
else:
print("Invalid username or password.")
login_system()
user123 and password456).stored_username and stored_password to see how the program behaves.Next up is a survey system where you ask users for their input (name, age, favorite language), and then format and display their responses in a clean way.
input(): To collect responses for different questions.def survey():
print("Welcome to the User Survey!")
# Step 1: Ask the user for their name
name = input("What is your name? ")
# Step 2: Ask for the user's age
age = input("How old are you? ")
# Step 3: Ask for their favorite programming language
favorite_language = input("What is your favorite programming language? ")
# Step 4: Display the survey results
print("\nSurvey Results:")
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Favorite Language: {favorite_language}")
survey()
Now, you can take these examples and make them your own:
** for exponentiation).Now, let’s explore some advanced techniques for using input in Python! We’ll look at faster alternatives and how to read multiple values at once from a single line. These can be very helpful for efficient input handling in certain scenarios.
sys.stdin.readline() for Faster InputThe input() function is very useful, but it might not be the most efficient when you’re working with large amounts of data. For faster input handling, especially when reading multiple lines of input, we can use sys.stdin.readline().
sys.stdin.readline() reads input as raw bytes, which is generally quicker than input(), especially when you’re reading large amounts of data or working with competitive programming challenges.import sys
# Using sys.stdin.readline() to read input
name = sys.stdin.readline().strip() # .strip() removes the newline character
print(f"Hello, {name}")
sys.stdin.readline() reads a full line of input..strip() is used to remove any trailing newline characters that are automatically included when reading input.input().Try using sys.stdin.readline() and compare it with input() to see the difference in performance when handling large amounts of input.
In many cases, you’ll want to get multiple pieces of data from the user at once. For example, asking for multiple numbers in a single line and processing them separately.
We can use split() with input() to handle this efficiently. This allows you to read multiple space-separated values in one go.
# Reading multiple values in one line
x, y = input("Enter two numbers separated by space: ").split()
# Convert the strings to integers
x = int(x)
y = int(y)
# Perform some operation
print(f"The sum of {x} and {y} is {x + y}")
input().split() reads the entire input line as a string and splits it into a list based on spaces.x and y.input() always returns a string)..split() breaks up the input string by spaces by default. You can also specify a different delimiter if needed (e.g., commas, semicolons).Try using split() with input() and experiment with reading more than two values. You could read three or more numbers, process them, and perform different operations like multiplication or division.
sys.stdin.readline(): sys.stdin.readline() is a great alternative to input() when you need faster input handling, especially in situations where performance is key (like competitive programming).input().split() allows you to gather multiple pieces of data at once from a single line of input.These techniques will make your programs more efficient and flexible, especially when dealing with larger or more complex input scenarios.
In this blog post, we explored the powerful input() function in Python and its various uses. Whether you’re just starting out with Python or building more complex programs, understanding how to gather user input is a crucial skill.
We covered:
input() to interact with the user.input() in different scenarios.sys.stdin.readline() and reading multiple values in one line using split().By mastering these techniques, you’ll be able to create programs that are not only interactive but also efficient and user-friendly. Whether you’re building simple scripts or complex applications, the ability to collect and process user input is essential for creating responsive and engaging programs.
Keep experimenting with these techniques and make your Python programs even more dynamic!
Feel free to revisit the examples and try modifying them to suit your needs
input() function in Python? The input() function allows the user to enter data during the execution of a program. It reads input as a string and can be used to interact with users, asking for their input in real-time.
input() handle different types of data? By default, input() returns data as a string. If you need to work with numbers or other types, you must explicitly convert the input using functions like int() or float().
To handle invalid input, you can use try-except blocks. This ensures that if the user enters data of the wrong type (e.g., a letter instead of a number), the program doesn’t crash, and you can display an error message instead.
You can use input().split() to take multiple inputs in one line. This method splits the input string into separate values based on spaces, and you can then process each value individually.
If you’d like to explore more about handling user input in Python, here are some helpful resources you can check out:
input() function from Python’s official docs.These resources will help you practice more, explore advanced examples, and strengthen your confidence in building interactive Python programs.
Want to explore more Python topics step by step?
👉 Check out more guides at emitechlogic.com for hands-on tutorials
💡 Found this helpful?
Do me a favor — share this post with your friends, colleagues, or on your social media. You never know who might need a quick Python refresher before their next interview.
📸 Instagram: https://www.instagram.com/emi_techlogic/
💼 LinkedIn: https://www.linkedin.com/in/emmimal-alexander/
#PythonQuiz #CodingInterview #PythonInterviewQuestions #MCQChallenge #PythonMCQ #EmitechLogic #UncoveredAI #PythonTips #AIwithEmi #PythonCoding #TechWithEmi
After debugging production systems that process millions of records daily and optimizing research pipelines that…
The landscape of Business Intelligence (BI) is undergoing a fundamental transformation, moving beyond its historical…
The convergence of artificial intelligence and robotics marks a turning point in human history. Machines…
The journey from simple perceptrons to systems that generate images and write code took 70…
In 1973, the British government asked physicist James Lighthill to review progress in artificial intelligence…
Expert systems came before neural networks. They worked by storing knowledge from human experts as…
This website uses cookies.