Python Input & Output Complete Guide
Learn Python input/output operations: Reading user input with input(), displaying output with print(), formatted strings, and various output formatting techniques.
input()
Read user input
print()
Display output
f-strings
Formatted strings
Formatting
Advanced formatting
Python Input/Output Basics
Input/Output (I/O) operations are fundamental to interactive Python programs. Python provides simple yet powerful functions for reading input from users and displaying output to the screen.
Key Functions
Input Function
input(prompt) - Reads a line from input, converts to string
Output Function
print(*objects, sep=' ', end='\n') - Prints objects to console
Input/Output Flow
# Simple Input/Output Example
name = input("Enter your name: ") # Read input
age = input("Enter your age: ")
# Display output
print("Hello,", name)
print(f"You are {age} years old")
# Type conversion example
age_int = int(age) # Convert string to integer
birth_year = 2024 - age_int
print(f"You were born in {birth_year} (approximately)")
input() function always returns a string. If you need numbers, you must convert using int() or float().
The input() Function
The input() function reads a line from input (usually keyboard) and returns it as a string. An optional prompt can be displayed to guide the user.
Syntax: input([prompt])
prompt: Optional string displayed to user before input
# Example 1: Simple input without prompt
user_input = input() # Just waits for user input
print(f"You entered: {user_input}")
# Example 2: Input with prompt
name = input("What is your name? ")
print(f"Hello, {name}!")
# Example 3: Multiple inputs
print("=== User Registration ===")
username = input("Enter username: ")
email = input("Enter email: ")
password = input("Enter password: ")
print(f"\nRegistration Complete!")
print(f"Username: {username}")
print(f"Email: {email}")
# In real applications, never print passwords!
# Example 4: Input with default value suggestion
country = input("Enter your country (default: USA): ") or "USA"
print(f"Country: {country}")
Reading Single Values with Type Conversion
# Reading integers
age = int(input("Enter your age: "))
print(f"Age: {age}, Type: {type(age)}")
# Reading floats
price = float(input("Enter price: $"))
print(f"Price: ${price:.2f}, Type: {type(price)}")
# Reading boolean (through string comparison)
response = input("Do you agree? (yes/no): ").lower()
is_agreed = response == 'yes'
print(f"Agreed: {is_agreed}, Type: {type(is_agreed)}")
# Reading with validation
while True:
try:
number = int(input("Enter a positive number: "))
if number > 0:
break
else:
print("Please enter a positive number!")
except ValueError:
print("Invalid input! Please enter a valid number.")
print(f"Valid number entered: {number}")
Reading Multiple Values
# Method 1: Separate inputs
print("=== Method 1: Separate Inputs ===")
name = input("Enter name: ")
age = input("Enter age: ")
city = input("Enter city: ")
# Method 2: Single line with split
print("\n=== Method 2: Split Input ===")
data = input("Enter name, age, city (comma-separated): ")
name, age, city = data.split(',')
print(f"Name: {name.strip()}, Age: {age.strip()}, City: {city.strip()}")
# Method 3: Multiple values with map
print("\n=== Method 3: Using map() ===")
numbers = list(map(int, input("Enter 3 numbers (space-separated): ").split()))
print(f"Numbers: {numbers}, Sum: {sum(numbers)}")
# Method 4: Reading until specific condition
print("\n=== Method 4: Reading Until 'quit' ===")
items = []
while True:
item = input("Enter item (or 'quit' to stop): ")
if item.lower() == 'quit':
break
items.append(item)
print(f"Items entered: {items}")
# Method 5: Reading fixed number of values
print("\n=== Method 5: Fixed Number of Values ===")
n = 3
values = []
for i in range(n):
value = input(f"Enter value {i+1}/{n}: ")
values.append(value)
print(f"All values: {values}")
- Always provide clear prompts that guide the user
- Validate user input to prevent errors
- Use try-except blocks for numeric inputs
- For multiple values, consider using split() with clear separators
- Convert input to appropriate data types immediately
- Handle empty inputs gracefully (use default values if appropriate)
The print() Function
The print() function displays output to the console. It's highly configurable with parameters for separators, line endings, and output destinations.
Syntax: print(*objects, sep=' ', end='\n', file=sys.stdout, flush=False)
*objects: Values to print, sep: Separator, end: Line ending
# Basic printing
print("Hello, World!")
print(42)
print(3.14)
print([1, 2, 3])
# Printing multiple values
name = "Alice"
age = 30
print("Name:", name, "Age:", age) # Default separator is space
# Custom separator
print("Name:", name, "Age:", age, sep=" | ")
print("192", "168", "1", "1", sep=".") # IP address format
# Custom end character (no newline)
print("Loading", end="")
print("...", end="")
print(" Done!")
# Multiple prints on same line
for i in range(1, 6):
print(i, end=" ") # Prints: 1 2 3 4 5
print() # New line after loop
# Printing to a file
with open('output.txt', 'w') as f:
print("This goes to a file", file=f)
# Flush parameter (useful for progress bars)
import time
for i in range(10):
print(f"Progress: {i+1}/10", end='\r', flush=True)
time.sleep(0.5)
print("\nDone!")
Output Formatting Techniques
# Method 1: String concatenation
name = "John"
age = 25
print("Name: " + name + ", Age: " + str(age))
# Method 2: Comma separation (automatic spacing)
print("Name:", name, "Age:", age)
# Method 3: Old style string formatting (% operator)
print("Name: %s, Age: %d" % (name, age))
print("Price: $%.2f" % 19.99)
# Method 4: str.format() method
print("Name: {}, Age: {}".format(name, age))
print("Name: {0}, Age: {1}".format(name, age))
print("Name: {n}, Age: {a}".format(n=name, a=age))
# Method 5: f-strings (Python 3.6+) - RECOMMENDED
print(f"Name: {name}, Age: {age}")
print(f"Next year you'll be {age + 1} years old")
# Alignment and padding
print(f"Name: {name:<10} Age: {age:>5}")
print(f"Price: ${19.99:>8.2f}")
# Multi-line f-strings
message = f"""
User Information:
---------------
Name: {name}
Age: {age}
Status: {"Adult" if age >= 18 else "Minor"}
"""
print(message)
Formatted Output with f-strings
f-strings (formatted string literals) provide a concise and readable way to embed expressions inside string literals. They're the modern way to format strings in Python.
f-string Syntax
Prefix string with f or F and embed expressions in curly braces {expression}
# Basic variable insertion
name = "Alice"
age = 30
print(f"My name is {name} and I'm {age} years old.")
# Expressions inside f-strings
a = 10
b = 20
print(f"{a} + {b} = {a + b}")
print(f"Square of {a} is {a ** 2}")
# Function calls inside f-strings
def get_greeting(name):
return f"Hello, {name}!"
print(f"{get_greeting('Bob')} How are you?")
# Method calls
text = "python programming"
print(f"Uppercase: {text.upper()}")
print(f"Title case: {text.title()}")
# Conditional expressions
score = 85
print(f"Score: {score} - {'Pass' if score >= 60 else 'Fail'}")
# List comprehension
numbers = [1, 2, 3, 4, 5]
print(f"Squares: {[x**2 for x in numbers]}")
# Dictionary access
person = {"name": "John", "age": 25}
print(f"Name: {person['name']}, Age: {person['age']}")
# Multi-line f-strings
message = f"""
User Profile
-----------
Name: {name}
Age: {age}
Status: {"Adult" if age >= 18 else "Minor"}
"""
print(message)
Format Specifiers in f-strings
| Format Specifier | Description | Example | Output |
|---|---|---|---|
| {value:.2f} | 2 decimal places | f"Price: ${3.14159:.2f}" |
Price: $3.14 |
| {value:10} | Width of 10 characters | f"Name: {'John':10}" |
Name: John______ |
| {value:<10} | Left aligned, width 10 | f"|{'Left':<10}|" |
|Left______| |
| {value:>10} | Right aligned, width 10 | f"|{'Right':>10}|" |
|______Right| |
| {value:^10} | Center aligned, width 10 | f"|{'Center':^10}|" |
|__Center__| |
| {value:,.2f} | Thousands separator, 2 decimals | f"${1234567.89:,.2f}" |
$1,234,567.89 |
| {value:0>5} | Zero-padded, width 5 | f"{42:0>5}" |
00042 |
| {value:0>5d} | Zero-padded integer | f"{42:0>5d}" |
00042 |
| {value:+.2f} | Show sign for numbers | f"{3.14:+.2f}" |
+3.14 |
| {value:.2%} | Percentage format | f"{0.125:.2%}" |
12.50% |
| {value:.2e} | Scientific notation | f"{1234567:.2e}" |
1.23e+06 |
| {value:b} | Binary format | f"{10:b}" |
1010 |
| {value:o} | Octal format | f"{10:o}" |
12 |
| {value:x} | Hexadecimal (lowercase) | f"{255:x}" |
ff |
| {value:X} | Hexadecimal (uppercase) | f"{255:X}" |
FF |
# Data for examples
products = [
{"name": "Laptop", "price": 999.99, "quantity": 5},
{"name": "Mouse", "price": 24.99, "quantity": 50},
{"name": "Keyboard", "price": 79.99, "quantity": 25},
{"name": "Monitor", "price": 299.99, "quantity": 15}
]
# Display product table with formatting
print("=" * 50)
print(f"{'PRODUCT INVENTORY':^50}")
print("=" * 50)
print(f"{'No.':<5} {'Product':<15} {'Price':>10} {'Quantity':>10} {'Total':>10}")
print("-" * 50)
total_value = 0
for i, product in enumerate(products, 1):
name = product["name"]
price = product["price"]
quantity = product["quantity"]
item_total = price * quantity
total_value += item_total
print(f"{i:<5} {name:<15} ${price:>9.2f} {quantity:>10} ${item_total:>9.2f}")
print("-" * 50)
print(f"{'TOTAL INVENTORY VALUE:':<40} ${total_value:>9.2f}")
print("=" * 50)
# Additional formatting examples
print("\n=== Number Formatting Examples ===")
number = 1234567.891234
print(f"Default: {number}")
print(f"2 decimal places: {number:.2f}")
print(f"With commas: {number:,.2f}")
print(f"Scientific: {number:.2e}")
print(f"Percentage: {0.125:.2%}")
print("\n=== Alignment Examples ===")
data = [("Alice", 95.5), ("Bob", 87.3), ("Charlie", 91.8)]
for name, score in data:
print(f"| {name:<10} | {score:>6.1f} |")
Other Formatting Methods
While f-strings are recommended, Python supports other string formatting methods that are useful in specific situations.
%-formatting (Old Style)
name = "John"
age = 30
score = 95.5
# Basic usage
print("Name: %s, Age: %d" % (name, age))
# Float formatting
print("Score: %.2f" % score)
# Multiple values
print("%s is %d years old" % (name, age))
# Format specifiers
# %s - String
# %d - Integer
# %f - Float
# %.2f - Float with 2 decimals
str.format() Method
name = "John"
age = 30
# Positional arguments
print("{} is {} years old".format(name, age))
# Indexed arguments
print("{0} is {1} years old".format(name, age))
# Named arguments
print("{n} is {a} years old".format(n=name, a=age))
# Format specifiers
print("Price: ${:.2f}".format(19.99))
print("Binary: {:b}".format(10))
# Alignment
print("|{:<10}|{:>10}|".format("Left", "Right"))
Advanced Output Techniques
# 1. Progress bar
import time
def show_progress(total):
for i in range(total + 1):
percent = (i / total) * 100
bar_length = 40
filled = int(bar_length * i // total)
bar = '█' * filled + '░' * (bar_length - filled)
print(f'\r[{bar}] {percent:.1f}%', end='', flush=True)
time.sleep(0.1)
print()
# 2. Colored output (ANSI codes)
def colored_text(text, color):
colors = {
'red': '\033[91m',
'green': '\033[92m',
'yellow': '\033[93m',
'blue': '\033[94m',
'purple': '\033[95m',
'cyan': '\033[96m',
'white': '\033[97m',
'reset': '\033[0m'
}
return f"{colors.get(color, colors['white'])}{text}{colors['reset']}"
print(colored_text("Success!", "green"))
print(colored_text("Warning!", "yellow"))
print(colored_text("Error!", "red"))
# 3. Table formatting with tabulate
try:
from tabulate import tabulate
data = [
["Alice", 30, "Engineer"],
["Bob", 25, "Designer"],
["Charlie", 35, "Manager"]
]
headers = ["Name", "Age", "Job"]
print("\n" + tabulate(data, headers=headers, tablefmt="grid"))
except ImportError:
print("Install tabulate: pip install tabulate")
# 4. Spinner animation
import itertools
import sys
import time
def spinner(message="Loading"):
spinner_chars = itertools.cycle(['-', '/', '|', '\\'])
for _ in range(20):
sys.stdout.write(f'\r{message} {next(spinner_chars)}')
sys.stdout.flush()
time.sleep(0.1)
sys.stdout.write('\r' + ' ' * 30 + '\r')
print(f"{message} complete!")
# 5. Pretty printing for complex data
import pprint
complex_data = {
"users": [
{"name": "Alice", "details": {"age": 30, "skills": ["Python", "JavaScript"]}},
{"name": "Bob", "details": {"age": 25, "skills": ["Java", "C++"]}}
]
}
print("\nPretty printed data:")
pprint.pprint(complex_data, indent=2)
Practical I/O Applications
Here are real-world examples of Python input/output operations in action.
def calculator():
"""Interactive calculator with formatted output"""
print("=" * 40)
print(f"{'PYTHON CALCULATOR':^40}")
print("=" * 40)
print("Operations: +, -, *, /, %, **")
print("-" * 40)
while True:
try:
# Get input
num1 = float(input("Enter first number: "))
operation = input("Enter operation (+, -, *, /, %, **): ")
num2 = float(input("Enter second number: "))
# Perform calculation
if operation == '+':
result = num1 + num2
symbol = '+'
elif operation == '-':
result = num1 - num2
symbol = '-'
elif operation == '*':
result = num1 * num2
symbol = '×'
elif operation == '/':
if num2 == 0:
print("Error: Cannot divide by zero!")
continue
result = num1 / num2
symbol = '÷'
elif operation == '%':
result = num1 % num2
symbol = '%'
elif operation == '**':
result = num1 ** num2
symbol = '^'
else:
print("Invalid operation!")
continue
# Display formatted result
print("-" * 40)
print(f"{num1:10.2f} {symbol:^3} {num2:10.2f} = {result:12.2f}")
print("=" * 40)
# Ask to continue
again = input("Another calculation? (yes/no): ").lower()
if again != 'yes':
print("Goodbye!")
break
except ValueError:
print("Error: Please enter valid numbers!")
except Exception as e:
print(f"Unexpected error: {e}")
# Run the calculator
calculator()
def student_grade_manager():
"""Manage and display student grades"""
students = []
print("=== STUDENT GRADE MANAGEMENT ===")
print("Enter student details (enter 'done' for name to finish)")
# Collect student data
while True:
name = input("\nStudent name (or 'done'): ")
if name.lower() == 'done':
break
try:
grade = float(input(f"Enter grade for {name} (0-100): "))
if 0 <= grade <= 100:
students.append({"name": name, "grade": grade})
else:
print("Grade must be between 0 and 100!")
except ValueError:
print("Please enter a valid number!")
# Display results
if students:
print("\n" + "=" * 50)
print(f"{'STUDENT GRADE REPORT':^50}")
print("=" * 50)
print(f"{'No.':<5} {'Student Name':<20} {'Grade':<10} {'Status':<15}")
print("-" * 50)
total = 0
for i, student in enumerate(students, 1):
name = student["name"]
grade = student["grade"]
total += grade
# Determine status
if grade >= 90:
status = "Excellent (A)"
elif grade >= 80:
status = "Good (B)"
elif grade >= 70:
status = "Average (C)"
elif grade >= 60:
status = "Pass (D)"
else:
status = "Fail (F)"
print(f"{i:<5} {name:<20} {grade:<10.1f} {status:<15}")
# Calculate statistics
average = total / len(students)
highest = max(students, key=lambda x: x["grade"])
lowest = min(students, key=lambda x: x["grade"])
print("-" * 50)
print(f"Total Students: {len(students)}")
print(f"Average Grade: {average:.1f}")
print(f"Highest Grade: {highest['grade']:.1f} ({highest['name']})")
print(f"Lowest Grade: {lowest['grade']:.1f} ({lowest['name']})")
print("=" * 50)
else:
print("\nNo student data entered.")
# Run the grade manager
student_grade_manager()
Key Takeaways
input()always returns a string - convert to numbers withint()orfloat()print()has useful parameters:sep(separator),end(line ending),file(output destination)- f-strings (Python 3.6+) are the recommended way for string formatting
- Format specifiers:
{value:.2f}(2 decimals),{value:>10}(right align),{value:,.2f}(thousands separator) - Always validate user input and handle errors with try-except blocks
- For multiple values, use
split()or multipleinput()calls - Use
end='\r'andflush=Truefor progress indicators and animations - Consider using libraries like
tabulateorpprintfor complex output formatting