input()
to Get User Input
In Python, you can use the input()
function to prompt the user for input. The input()
function displays a message to the user and waits for them to enter text. The entered text is returned as a string.
# Basic example
name = input("Enter your name: ")
print("Hello, " + name + "!")
# You can also use input() without a prompt
age = input("Enter your age: ")
print("You are " + age + " years old.")
The input()
function returns user input as a string. If you need to use the input as a different data type, like an integer or a float, you can convert it using functions like int()
or float()
.
# Converting user input to an integer
num1 = int(input("Enter a number: "))
num2 = int(input("Enter another number: "))
result = num1 + num2
print("The sum is:", result)
# Converting user input to a float
price = float(input("Enter the price: "))
quantity = int(input("Enter the quantity: "))
total = price * quantity
print("Total cost:", total)
When using input()
, it's essential to handle user input carefully. For example, if you expect an integer input, you should validate the input to avoid errors. You can use loops and conditionals to handle various scenarios.
# Handling invalid input with a while loop
valid_input = False
while not valid_input:
try:
age = int(input("Enter your age: "))
if age < 0:
print("Please enter a positive number.")
else:
valid_input = True
except ValueError:
print("Invalid input. Please enter a valid integer.")
print("Your age is:", age)
Using input()
to get user input makes your Python programs interactive and allows users to provide dynamic data to your applications.