Input & Output
Learn how to get user input and display formatted output in Python
The input() Function
- input() reads user input as a string
- Always returns a string, even if user enters numbers
- Can display a prompt message to the user
- Use type casting to convert input to other types
# Basic input
name = input("Enter your name: ")
print("Hello, " + name)
# Input with type conversion
age = int(input("Enter your age: "))
print(f"Next year you will be {age + 1}")
# Multiple inputs
x = input("Enter first number: ")
y = input("Enter second number: ")
total = int(x) + int(y)
print(f"Sum: {total}")
The print() Function
- print() displays output to the console
- Can print multiple values separated by commas
- Default separator is space, can be changed with sep parameter
- Default end character is newline, can be changed with end parameter
# Basic print
print("Hello World")
# Multiple values
print("Python", "is", "awesome")
# Custom separator
print("apple", "banana", "cherry", sep=", ")
# Custom end character
print("Loading", end="...")
print("Done!")
String Formatting
- f-strings (formatted string literals) - modern and recommended
- .format() method - older but still widely used
- % formatting - legacy style, rarely used now
- f-strings support expressions inside curly braces
name = "Alice"
age = 25
score = 95.5
# f-strings (Python 3.6+)
print(f"Name: {name}, Age: {age}")
print(f"Score: {score:.1f}%")
print(f"Next year: {age + 1}")
# .format() method
print("Name: {}, Age: {}".format(name, age))
print("Name: {0}, Age: {1}".format(name, age))
# % formatting (old style)
print("Name: %s, Age: %d" % (name, age))
Advanced Formatting
- Alignment and padding with f-strings
- Number formatting (decimals, thousands separator)
- Date and time formatting
- Multi-line strings with triple quotes
# Alignment
text = "Python"
print(f"{text:>10}") # Right align
print(f"{text:<10}") # Left align
print(f"{text:^10}") # Center align
# Number formatting
pi = 3.14159
print(f"{pi:.2f}") # 2 decimal places
big_num = 1000000
print(f"{big_num:,}") # Thousands separator
# Multi-line output
message = """
Welcome to Python!
This is a multi-line string.
Enjoy learning!
"""
print(message)