Getting User Input in Python

In Python, you can get input from the user using the input() function. This function reads a line of text from the user and returns it as a string.

Basic User Input

Python
name = input("Enter your name: ")
print(f"Hello, {name}!")

# Example interaction:
# Enter your name: Alice
# Output: Hello, Alice!

Converting Input Data Types

Since the input() function returns a string, you may need to convert the input to another data type:

Python
age = input("Enter your age: ")
age = int(age)
print(f"You are {age} years old.")

# Example interaction:
# Enter your age: 30
# Output: You are 30 years old.

Handling Invalid Input

You can handle invalid input using a try...except block:

Python
try:
    age = int(input("Enter your age: "))
    print(f"You are {age} years old.")
except ValueError:
    print("Please enter a valid number.")

# Example interaction:
# Enter your age: abc
# Output: Please enter a valid number.

Getting user input is essential for interactive programs and command-line tools.