In Python, the input()
function is used to take input from the user. This function allows users to interact with the program by providing data during runtime. In this article, we will explore various ways to handle user input with examples.
input()
The input()
function reads user input as a string. Here is a simple example:
# Example 1: Basic user input
name = input("Enter your name: ")
print("Hello,", name)
Output (if the user enters "Alice"):
Enter your name: Alice Hello, Alice
By default, input()
returns data as a string. To use it as another data type, you need to explicitly convert it.
# Example 2: Input as an integer
age = input("Enter your age: ")
age = int(age) # Convert to integer
print("Next year, you will be", age + 1, "years old.")
Output (if the user enters "25"):
Enter your age: 25 Next year, you will be 26 years old.
For floating-point numbers:
# Example 3: Input as a float
height = input("Enter your height in meters: ")
height = float(height) # Convert to float
print("Your height is", height, "meters.")
Output (if the user enters "1.75"):
Enter your height in meters: 1.75 Your height is 1.75 meters.
Using the split()
method, you can take multiple inputs in a single line.
# Example 4: Multiple inputs
x, y = input("Enter two numbers separated by space: ").split()
x = int(x)
y = int(y)
print("Sum:", x + y)
Output (if the user enters "5 10"):
Enter two numbers separated by space: 5 10 Sum: 15
The input()
function allows you to display a message that prompts the user for input.
# Example 5: Default input message
city = input("Which city do you live in? ")
print("You live in", city)
Output (if the user enters "New York"):
Which city do you live in? New York You live in New York
You can validate the user input using conditions to ensure it meets specific requirements.
# Example 6: Validating user input
age = input("Enter your age: ")
if age.isdigit():
age = int(age)
print("Your age is", age)
else:
print("Invalid input. Please enter a numeric value.")
Output (if the user enters "twenty"):
Enter your age: twenty Invalid input. Please enter a numeric value.
To handle errors caused by invalid input, use a try-except
block.
# Example 7: Handling invalid input with try-except
try:
age = int(input("Enter your age: "))
print("Your age is", age)
except ValueError:
print("Error: Please enter a valid number.")
Output (if the user enters "abc"):
Enter your age: abc Error: Please enter a valid number.
input()
in LoopsThe input()
function can be used in loops to repeatedly take input until a condition is met.
# Example 8: Repeated input in a loop
while True:
answer = input("Type 'exit' to quit: ")
if answer.lower() == 'exit':
print("Goodbye!")
break
Output:
Type 'exit' to quit: hello Type 'exit' to quit: exit Goodbye!
The input()
function is a versatile tool for gathering user input in Python programs. Whether you need simple string inputs, numeric data, or multiple values, input()
offers the flexibility to handle it all effectively. With proper validation and exception handling, you can create robust and user-friendly programs.