Skip to main content

Python Input Output

Input and output operations are essential components of any programming language. They allow your programs to interact with users, files, and other systems. In this tutorial, we'll explore how Python handles input from users and output to the console, as well as file operations for more persistent data storage.

Basic Input and Output

Output with print()

The print() function is the most basic way to display output in Python. It takes one or more arguments and displays them to the standard output (usually your terminal or console).

python
# Basic printing
print("Hello, Python!")

# Printing multiple items
print("The answer is:", 42)

# Using formatted strings
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

Output:

Hello, Python!
The answer is: 42
My name is Alice and I am 25 years old.

Formatting Output

Python offers several ways to format your output:

f-strings (Python 3.6+)

python
name = "Bob"
score = 95.5
print(f"{name} scored {score:.1f} points")

Output:

Bob scored 95.5 points

str.format() method

python
name = "Charlie"
score = 88.75
print("{} scored {:.2f} points".format(name, score))

Output:

Charlie scored 88.75 points

Format specifiers

python
# Width and alignment
print(f"{'Name':<10}|{'Score':>10}")
print(f"{'Bob':<10}|{95.5:>10.2f}")
print(f"{'Charlie':<10}|{88.75:>10.2f}")

Output:

Name      |     Score
Bob | 95.50
Charlie | 88.75

Input with input()

The input() function allows you to get input from users through the console:

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

When this code runs, it will:

  1. Display the prompt "Enter your name: "
  2. Wait for the user to type something and press Enter
  3. Store the entered text in the variable name
  4. Use that value in the print statement

Note that input() always returns a string. If you need a different data type, you'll need to convert it:

python
# Getting numeric input
age = int(input("Enter your age: "))
height = float(input("Enter your height in meters: "))

print(f"You are {age} years old and {height} meters tall.")
print(f"In 5 years, you'll be {age + 5} years old.")

File Input/Output Operations

File operations allow your programs to read from and write to files on your computer.

Opening and Closing Files

Use the open() function to open files:

python
# Basic syntax: open(filename, mode)
file = open("example.txt", "r") # Open for reading
# Do something with the file
file.close() # Close the file when done

File modes:

  • 'r': Read (default)
  • 'w': Write (creates new file or truncates existing file)
  • 'a': Append (adds to the end of file)
  • 'b': Binary mode
  • 't': Text mode (default)
  • '+': Update (read and write)

The with statement automatically handles closing the file, even if exceptions occur:

python
# Preferred way to work with files
with open("example.txt", "r") as file:
content = file.read()
print(content)
# File is automatically closed when the with block ends

Reading from Files

Python offers several ways to read file content:

python
# Reading the entire file at once
with open("example.txt", "r") as file:
content = file.read()
print(content)

# Reading line by line
with open("example.txt", "r") as file:
for line in file:
print(line.strip()) # strip() removes newline characters

# Reading all lines into a list
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines)

Writing to Files

python
# Writing to a file
with open("output.txt", "w") as file:
file.write("Hello, world!\n")
file.write("This is a test file.\n")

# Appending to a file
with open("output.txt", "a") as file:
file.write("This line is appended.\n")

Real-World Examples

Example 1: Simple Note-Taking App

python
def add_note():
note = input("Enter your note: ")
with open("notes.txt", "a") as file:
file.write(note + "\n")
print("Note added successfully!")

def view_notes():
try:
with open("notes.txt", "r") as file:
notes = file.readlines()
if not notes:
print("No notes found.")
else:
print("\n===== YOUR NOTES =====")
for i, note in enumerate(notes, 1):
print(f"{i}. {note.strip()}")
print("=====================\n")
except FileNotFoundError:
print("No notes file found. Add some notes first!")

def main():
while True:
print("\n1. Add a note")
print("2. View all notes")
print("3. Exit")

choice = input("Choose an option (1-3): ")

if choice == "1":
add_note()
elif choice == "2":
view_notes()
elif choice == "3":
print("Goodbye!")
break
else:
print("Invalid choice. Please try again.")

if __name__ == "__main__":
main()

This simple note-taking application demonstrates:

  • Getting user input with input()
  • Writing to files with file.write()
  • Reading from files with file.readlines()
  • Exception handling for file operations
  • A practical menu-driven interface

Example 2: CSV Data Processing

CSV (Comma-Separated Values) files are commonly used for data exchange. Here's how to work with them:

python
def save_users(users):
with open("users.csv", "w") as file:
# Write header
file.write("name,email,age\n")

# Write data
for user in users:
file.write(f"{user['name']},{user['email']},{user['age']}\n")

print(f"Saved {len(users)} users to users.csv")

def load_users():
users = []
try:
with open("users.csv", "r") as file:
lines = file.readlines()

# Skip header
for line in lines[1:]:
name, email, age = line.strip().split(',')
users.append({
"name": name,
"email": email,
"age": int(age)
})

print(f"Loaded {len(users)} users from users.csv")
except FileNotFoundError:
print("No users file found.")

return users

# Example usage
sample_users = [
{"name": "Alice", "email": "[email protected]", "age": 28},
{"name": "Bob", "email": "[email protected]", "age": 32},
{"name": "Charlie", "email": "[email protected]", "age": 22}
]

# Save users to CSV
save_users(sample_users)

# Load users from CSV
loaded_users = load_users()
for user in loaded_users:
print(f"{user['name']} ({user['age']}): {user['email']}")

This example demonstrates working with structured data in CSV format, showing both reading and writing operations.

Summary

In this tutorial, we've covered:

  1. Basic output with print() and various formatting options
  2. User input with input() and type conversion
  3. File operations:
    • Opening and closing files
    • Using the with statement
    • Reading from files with read(), readlines(), and iteration
    • Writing to files with write()
  4. Practical examples showing how to build simple applications using input/output

Input/output operations are fundamental to most Python programs, allowing you to interact with users, process data from files, and save results for later use.

Practice Exercises

  1. Create a program that asks for the user's name and favorite color, then outputs a personalized message.
  2. Write a program that reads a text file and counts the occurrences of each word.
  3. Build a simple address book application that can add contacts to a file and display all contacts.
  4. Create a program that reads a CSV file containing student names and grades, then calculates and outputs the average grade.
  5. Write a log file analyzer that reads a log file and reports on error occurrences.

Additional Resources

Learning to effectively use Python's input and output capabilities will help you create more interactive and useful applications as you continue your programming journey.



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)