How do I read user input and print output in Python?
· Category: Python Programming
Short answer
Use input() to read a line of text from the user and print() to display output. By default, input() returns a string, so convert it when you need numbers.
Steps
- Prompt the user with
input("Prompt: "). - Convert the result if needed (e.g.,
int(),float()). - Display results with
print().
name = input("Enter your name: ")
age = int(input("Enter your age: "))
print("Hello,", name)
print(f"Next year you will be {age + 1} years old.")
Tips
print()accepts multiple arguments separated by commas and adds a space between them.- Use the
sepandendparameters to customize spacing and line endings. - f-strings (formatted string literals) are the cleanest way to embed expressions inside strings.
# Customizing print
print("Loading", "dots", sep=".", end="
")
# f-strings
value = 3.14159
print(f"Pi rounded: {value:.2f}")
Common issues
- Forgetting to convert
input()results to numbers before math operations causes aTypeError. input()always blocks execution until the user presses Enter, which can be problematic in GUI or async contexts.- Extra whitespace from user input can be stripped with
.strip().