Intern
234
How to properly request user input in Python?
Answer from AI
sobes.tech AI
The built-in function input() is used. It always returns a string. To get a number, you need to convert the type.
# Request for string input
name = input("Enter your name: ")
# Request for numeric input and convert to int
try:
age = int(input("Enter your age: "))
print(f"In 10 years, you will be {age + 10}.")
except ValueError:
print("Invalid age input.")
You can also use float() for floating-point numbers.
# Request for numeric input and convert to float
try:
price = float(input("Enter the price: "))
print(f"Price with VAT: {price * 1.2}")
except ValueError:
print("Invalid price input.")