Input and Output (I/O) are fundamental concepts in programming. Input refers to data that your program receives from external sources (like user typing on keyboard), while Output refers to data that your program sends out (like displaying text on screen).
In Python, the most common I/O operations involve:
- Getting input from users with input()
- Displaying output with print()
- Reading from and writing to files
The print()
function is your primary tool for displaying output to the console.
print("Hello, World!")
print("Welcome to Python programming")
# Printing variables
name = "Emma"
age = 25
print(name)
print(age)
name = "David"
age = 30
city = "Chicago"
# Separate items with commas
print("Name:", name, "Age:", age, "City:", city)
# Output: Name: David Age: 30 City: Chicago
# Changing the separator
print("apple", "banana", "orange", sep=", ")
# Output: apple, banana, orange
print("2025", "06", "20", sep="-")
# Output: 2025-06-20
# Changing the end character (default is newline)
print("Loading", end="...")
print("Done!")
# Output: Loading...Done!
# Printing on same line
for i in range(5):
print(i, end=" ")
print() # Add newline at the end
# Output: 0 1 2 3 4
# Print to a file instead of console
with open("output.txt", "w") as file:
print("This goes to the file", file=file)
print("So does this", file=file)
The input()
function allows your program to receive data from the user.
# Getting user input
name = input("What's your name? ")
print("Hello,", name)
# Input without prompt
data = input() # User types and presses Enter
print("You entered:", data)
# This is ALWAYS a string, even if user types numbers
age = input("Enter your age: ")
print(type(age)) # <class 'str'>
# To use as number, convert it
age_number = int(age)
next_year = age_number + 1
print("Next year you'll be", next_year)
# Getting string input
name = input("Enter your name: ")
# Getting integer input
age = int(input("Enter your age: "))
# Getting float input
height = float(input("Enter your height in feet: "))
# Getting boolean-like input
response = input("Do you like Python? (yes/no): ")
likes_python = response.lower() == "yes"
print(f"Name: {name}")
print(f"Age: {age}")
print(f"Height: {height}")
print(f"Likes Python: {likes_python}")
When converting user input, errors can occur if the user enters invalid data.
# Safe integer input
try:
age = int(input("Enter your age: "))
print(f"You are {age} years old")
except ValueError:
print("Please enter a valid number")
# Safe float input
try:
price = float(input("Enter price: $"))
tax = price * 0.08
print(f"Tax: ${tax:.2f}")
except ValueError:
print("Please enter a valid price")
def get_integer_input(prompt):
"""Get valid integer input from user"""
while True:
try:
value = int(input(prompt))
return value
except ValueError:
print("Please enter a valid integer")
def get_float_input(prompt):
"""Get valid float input from user"""
while True:
try:
value = float(input(prompt))
return value
except ValueError:
print("Please enter a valid number")
# Using the functions
age = get_integer_input("Enter your age: ")
salary = get_float_input("Enter your salary: ")
print(f"Age: {age}, Salary: ${salary:,.2f}")
name = "Sarah"
age = 28
salary = 65000.75
# Basic f-string
print(f"Hello, {name}!")
# Expressions inside f-strings
print(f"In 5 years, {name} will be {age + 5} years old")
# Number formatting
print(f"Salary: ${salary:,.2f}") # $65,000.75
print(f"Age: {age:03d}") # Age: 028 (zero-padded)
# Percentage formatting
success_rate = 0.847
print(f"Success rate: {success_rate:.1%}") # Success rate: 84.7%
number = 1234.5678
# Decimal places
print(f"{number:.2f}") # 1234.57
print(f"{number:.0f}") # 1235
# Width and alignment
print(f"{number:10.2f}") # " 1234.57" (right-aligned in 10 chars)
print(f"{number:<10.2f}") # "1234.57 " (left-aligned)
print(f"{number:^10.2f}") # " 1234.57 " (center-aligned)
# Thousands separator
print(f"{number:,.2f}") # 1,234.57
# Different number bases
num = 255
print(f"Decimal: {num}") # 255
print(f"Binary: {num:b}") # 11111111
print(f"Octal: {num:o}") # 377
print(f"Hex: {num:x}") # ff
text = "python"
print(f"{text.upper()}") # PYTHON
print(f"{text:>10}") # " python" (right-aligned in 10 chars)
print(f"{text:<10}") # "python " (left-aligned)
print(f"{text:^10}") # " python " (centered)
print(f"{text:*^10}") # "**python**" (centered with * padding)
# Method 1: Split by spaces
data = input("Enter name, age, city (separated by spaces): ")
name, age_str, city = data.split()
age = int(age_str)
# Method 2: Split by commas
data = input("Enter three numbers separated by commas: ")
num1, num2, num3 = map(int, data.split(","))
print(f"Numbers: {num1}, {num2}, {num3}")
print(f"Sum: {num1 + num2 + num3}")
# Collecting multiple items
shopping_list = []
print("Enter items for your shopping list (type 'done' to finish):")
while True:
item = input("Item: ")
if item.lower() == 'done':
break
shopping_list.append(item)
print("\nYour shopping list:")
for i, item in enumerate(shopping_list, 1):
print(f"{i}. {item}")
Creating programs with user choices:
def show_menu():
print("\n=== Calculator Menu ===")
print("1. Add")
print("2. Subtract")
print("3. Multiply")
print("4. Divide")
print("5. Exit")
def get_numbers():
num1 = float(input("Enter first number: "))
num2 = float(input("Enter second number: "))
return num1, num2
def calculator():
while True:
show_menu()
choice = input("Choose an option (1-5): ")
if choice == '5':
print("Goodbye!")
break
elif choice in ['1', '2', '3', '4']:
num1, num2 = get_numbers()
if choice == '1':
result = num1 + num2
operation = "+"
elif choice == '2':
result = num1 - num2
operation = "-"
elif choice == '3':
result = num1 * num2
operation = "*"
elif choice == '4':
if num2 != 0:
result = num1 / num2
operation = "/"
else:
print("Error: Cannot divide by zero!")
continue
print(f"Result: {num1} {operation} {num2} = {result}")
else:
print("Invalid choice. Please try again.")
calculator()
For sensitive input like passwords, you can use the getpass
module:
import getpass
username = input("Username: ")
password = getpass.getpass("Password: ") # Hidden input
print(f"Welcome, {username}!")
# Password is not echoed to screen
# Writing text to a file
filename = "user_data.txt"
name = input("Enter your name: ")
age = input("Enter your age: ")
with open(filename, "w") as file:
file.write(f"Name: {name}\n")
file.write(f"Age: {age}\n")
print(f"Data saved to {filename}")
# Reading from a file
try:
with open("user_data.txt", "r") as file:
content = file.read()
print("File contents:")
print(content)
except FileNotFoundError:
print("File not found!")
# Adding new data to existing file
with open("log.txt", "a") as file:
import datetime
timestamp = datetime.datetime.now()
message = input("Enter log message: ")
file.write(f"{timestamp}: {message}\n")
def register_user():
print("=== User Registration ===")
# Get user information
username = input("Choose a username: ")
while True:
email = input("Enter your email: ")
if "@" in email and "." in email:
break
print("Please enter a valid email address")
while True:
try:
age = int(input("Enter your age: "))
if age >= 13:
break
else:
print("You must be at least 13 years old")
except ValueError:
print("Please enter a valid age")
# Confirm information
print(f"\n=== Confirm Registration ===")
print(f"Username: {username}")
print(f"Email: {email}")
print(f"Age: {age}")
confirm = input("Is this information correct? (yes/no): ")
if confirm.lower() == 'yes':
print("Registration successful!")
return {"username": username, "email": email, "age": age}
else:
print("Registration cancelled")
return None
user_info = register_user()
def grade_calculator():
print("=== Grade Calculator ===")
student_name = input("Enter student name: ")
subject = input("Enter subject: ")
grades = []
print("Enter grades (type 'done' when finished):")
while True:
grade_input = input("Grade: ")
if grade_input.lower() == 'done':
break
try:
grade = float(grade_input)
if 0 <= grade <= 100:
grades.append(grade)
else:
print("Grade must be between 0 and 100")
except ValueError:
print("Please enter a valid number")
if grades:
average = sum(grades) / len(grades)
# Determine letter grade
if average >= 90:
letter_grade = 'A'
elif average >= 80:
letter_grade = 'B'
elif average >= 70:
letter_grade = 'C'
elif average >= 60:
letter_grade = 'D'
else:
letter_grade = 'F'
# Display results
print(f"\n=== Grade Report ===")
print(f"Student: {student_name}")
print(f"Subject: {subject}")
print(f"Grades: {grades}")
print(f"Average: {average:.1f}")
print(f"Letter Grade: {letter_grade}")
# Save to file
with open(f"{student_name}_{subject}_grades.txt", "w") as file:
file.write(f"Student: {student_name}\n")
file.write(f"Subject: {subject}\n")
file.write(f"Grades: {', '.join(map(str, grades))}\n")
file.write(f"Average: {average:.1f}\n")
file.write(f"Letter Grade: {letter_grade}\n")
print("Grade report saved to file!")
else:
print("No grades entered!")
grade_calculator()
def conduct_survey():
print("=== Customer Satisfaction Survey ===")
responses = {}
# Basic information
responses['name'] = input("Name (optional): ") or "Anonymous"
# Rating questions
questions = [
"How would you rate our product quality? (1-5): ",
"How would you rate our customer service? (1-5): ",
"How likely are you to recommend us? (1-5): "
]
ratings = []
for question in questions:
while True:
try:
rating = int(input(question))
if 1 <= rating <= 5:
ratings.append(rating)
break
else:
print("Please enter a number between 1 and 5")
except ValueError:
print("Please enter a valid number")
responses['quality'] = ratings[0]
responses['service'] = ratings[1]
responses['recommendation'] = ratings[2]
# Open-ended feedback
responses['comments'] = input("Additional comments (optional): ")
# Calculate overall satisfaction
overall = sum(ratings) / len(ratings)
responses['overall'] = overall
# Display summary
print(f"\n=== Survey Summary ===")
print(f"Respondent: {responses['name']}")
print(f"Product Quality: {responses['quality']}/5")
print(f"Customer Service: {responses['service']}/5")
print(f"Recommendation: {responses['recommendation']}/5")
print(f"Overall Satisfaction: {overall:.1f}/5")
if responses['comments']:
print(f"Comments: {responses['comments']}")
# Save results
import datetime
timestamp = datetime.datetime.now().strftime("%Y%m%d_%H%M%S")
filename = f"survey_{timestamp}.txt"
with open(filename, "w") as file:
for key, value in responses.items():
file.write(f"{key.title()}: {value}\n")
print(f"Survey saved as {filename}")
return responses
survey_data = conduct_survey()
def get_valid_input(prompt, validator_func, error_message):
"""Generic function for validated input"""
while True:
try:
value = input(prompt)
if validator_func(value):
return value
else:
print(error_message)
except Exception as e:
print(f"Error: {e}")
# Usage examples
def is_valid_email(email):
return "@" in email and "." in email
def is_valid_age(age_str):
try:
age = int(age_str)
return 0 <= age <= 150
except ValueError:
return False
email = get_valid_input(
"Enter your email: ",
is_valid_email,
"Please enter a valid email address"
)
age = get_valid_input(
"Enter your age: ",
is_valid_age,
"Please enter a valid age (0-150)"
)
def print_table(data, headers):
"""Print data in a formatted table"""
# Calculate column widths
col_widths = [max(len(str(item)) for item in col) for col in zip(headers, *data)]
# Print headers
header_row = " | ".join(f"{header:<{width}}" for header, width in zip(headers, col_widths))
print(header_row)
print("-" * len(header_row))
# Print data rows
for row in data:
data_row = " | ".join(f"{item:<{width}}" for item, width in zip(row, col_widths))
print(data_row)
# Example usage
students = [
["Alice", 85, "A"],
["Bob", 92, "A"],
["Charlie", 78, "B"]
]
headers = ["Name", "Score", "Grade"]
print_table(students, headers)
# Wrong
age = input("Enter age: ") # This is a string
# next_year = age + 1 # Error!
# Correct
age = int(input("Enter age: ")) # Convert to integer
next_year = age + 1
# Wrong - program crashes on invalid input
price = float(input("Enter price: "))
# Correct - handle errors gracefully
try:
price = float(input("Enter price: "))
except ValueError:
print("Invalid price entered")
price = 0.0
# Poor formatting
name = "John"
age = 25
salary = 50000
print("Name:", name, "Age:", age, "Salary:", salary)
# Better formatting
print(f"Employee: {name}")
print(f"Age: {age} years")
print(f"Salary: ${salary:,}")
Input and Output are essential for creating interactive programs:
Key Points:
- print()
displays output with customizable formatting
- input()
gets user input (always returns strings)
- Always validate and convert input when necessary
- Use f-strings for modern, readable string formatting
- Handle errors gracefully with try-except blocks
- Create user-friendly interfaces with clear prompts and feedback
Best Practices:
- Validate all user input
- Provide clear error messages
- Use descriptive prompts
- Format output clearly and consistently
- Save important data to files when appropriate
- Test your programs with various inputs
Mastering input and output operations will make your programs interactive and user-friendly, forming the foundation for more complex applications!