python week1 day 4
For "Python week 1 day 4," most beginner-friendly courses focus on foundational topics such as
Python data structures (lists, tuples, dictionaries, sets) and simple coding exercises to reinforce
your understanding of these concepts. Some tutorials may also cover your first programs, like
"print('Hello World')" and how to use the print function, variables, and scripts. [1] [2]
Common Topics on Day 4
Data Structures: Introduction to lists, tuples, sets, and dictionaries. These are the basic
ways to store and organize data in Python. For example, lists are ordered and mutable,
tuples are ordered and immutable, dictionaries store key-value pairs, and sets contain
unique values. [2]
First Scripts & Print Function: Writing your first script, using the print function correctly,
and understanding basic syntax errors. Practicing with multiple print statements and running
them together as a simple script is common. [1]
Practical Exercises: Step-by-step exercises to help you code along and get hands-on
experience with the concepts from the lesson. [2]
Example Code
# Example of different data structures
my_list = [1, 2, 3] # List
my_tuple = (4, 5, 6) # Tuple
my_set = {7, 8, 9} # Set
my_dict = {'a': 1, 'b': 2} # Dictionary
# Printing each data structure
print(my_list)
print(my_tuple)
print(my_set)
print(my_dict)
How to Practice
Try creating and modifying each type of data structure.
Print values from each, add or remove items, and understand their behavior.
Write comments in your code, which is a good habit as a beginner.
These basics form the backbone of most beginner Python curriculums on week 1 day 4.
Practicing these makes it easier to move to more advanced topics in upcoming lessons. [1] [2]
⁂
File I/O & Comprehensions - Day 4 Complete Guide
Requirements Before Starting
Before diving into File I/O and comprehensions, make sure you have:
Python 3.x installed on your system
A text editor or IDE (VS Code, PyCharm, or even Notepad)
Basic understanding of Python variables, loops, and functions
A folder/directory to save your practice files
Part 1: File I/O (Input/Output)
What is File I/O?
File I/O allows your Python programs to read data from files and write data to files, making your
programs interact with external data sources. [8] [9]
Opening Files in Python
The open() function is used to open files with this syntax: [10] [8]
file_object = open("filename", "mode")
Common File Modes:
'r' - Read mode (default)
'w' - Write mode (overwrites existing content)
'a' - Append mode (adds to end of file)
'x' - Exclusive creation (fails if file exists)
'r+' - Read and write mode [8] [10]
Reading from Text Files
There are three main methods to read files: [9] [8]
Method 1: read() - Read entire file
# Read entire file at once
with open("[Link]", "r") as file:
content = [Link]()
print(content)
Method 2: readline() - Read one line at a time
# Read line by line
with open("[Link]", "r") as file:
line = [Link]()
while line:
print([Link]()) # strip() removes newline characters
line = [Link]()
Method 3: readlines() - Read all lines into a list
# Read all lines into a list
with open("[Link]", "r") as file:
lines = [Link]()
for line in lines:
print([Link]())
Writing to Text Files
Method 1: write() - Write a single string
# Write a single string
with open("[Link]", "w") as file:
[Link]("Hello, World!\n")
[Link]("This is line 2\n")
Method 2: writelines() - Write multiple lines
# Write multiple lines from a list
lines_to_write = ["First line\n", "Second line\n", "Third line\n"]
with open("[Link]", "w") as file:
[Link](lines_to_write)
File Handling Best Practices
The with Statement - Most Important!
Always use the with statement for file handling: [11] [12] [13]
# GOOD - Automatic file closing
with open("[Link]", "r") as file:
content = [Link]()
# File automatically closes when exiting the with block
# BAD - Manual closing (avoid this)
file = open("[Link]", "r")
content = [Link]()
[Link]() # Easy to forget!
Why use with?
Automatically closes files even if errors occur
Prevents resource leaks
More readable and cleaner code [12] [13]
Error Handling
# Handle potential file errors
try:
with open("[Link]", "r") as file:
content = [Link]()
except FileNotFoundError:
print("File not found!")
except PermissionError:
print("Permission denied!")
except Exception as e:
print(f"An error occurred: {e}")
Part 2: List Comprehensions
What are List Comprehensions?
List comprehensions provide a concise way to create lists based on existing iterables. [14] [15] [16]
Basic Syntax:
[expression for item in iterable if condition]
Simple List Comprehension Examples
Example 1: Squares of numbers
# Traditional way using for loop
squares = []
for x in range(1, 6):
[Link](x**2)
print(squares) # [1, 4, 9, 16, 25]
# Using list comprehension - much cleaner!
squares = [x**2 for x in range(1, 6)]
print(squares) # [1, 4, 9, 16, 25]
Example 2: Filtering with conditions
# Get even numbers from 0 to 9
evens = [x for x in range(10) if x % 2 == 0]
print(evens) # [0, 2, 4, 6, 8]
# Get words with letter 'a'
fruits = ["apple", "banana", "cherry", "grape"]
fruits_with_a = [fruit for fruit in fruits if 'a' in fruit]
print(fruits_with_a) # ['apple', 'banana', 'grape']
Example 3: String manipulation
# Convert to uppercase
names = ["alice", "bob", "charlie"]
upper_names = [[Link]() for name in names]
print(upper_names) # ['ALICE', 'BOB', 'CHARLIE']
# Get first letter of each name
first_letters = [name[^2_0] for name in names]
print(first_letters) # ['a', 'b', 'c']
Part 3: Dictionary Comprehensions
What are Dictionary Comprehensions?
Dictionary comprehensions create dictionaries using a similar syntax to list comprehensions. [17]
[18]
Basic Syntax:
{key: value for item in iterable if condition}
Dictionary Comprehension Examples
Example 1: Basic dictionary creation
# Create a dictionary of numbers and their squares
squares_dict = {x: x**2 for x in range(1, 6)}
print(squares_dict) # {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}
# Create from two lists
keys = ['name', 'age', 'city']
values = ['Alice', 25, 'New York']
person = {k: v for k, v in zip(keys, values)}
print(person) # {'name': 'Alice', 'age': 25, 'city': 'New York'}
Example 2: Filtering dictionaries
# Filter dictionary by condition
original_dict = {'a': 1, 'b': 2, 'c': 3, 'd': 4}
filtered_dict = {k: v for k, v in original_dict.items() if v > 2}
print(filtered_dict) # {'c': 3, 'd': 4}
Practical Sessions
Practice 1: Count Word Frequency in Text File
Let's create a complete word frequency counter: [19] [20]
# Step 1: Create a sample text file
sample_text = """
The quick brown fox jumps over the lazy dog.
The lazy dog sleeps in the sun.
A quick brown fox is very clever.
"""
# Write sample text to file
with open("[Link]", "w") as file:
[Link](sample_text)
# Step 2: Count word frequency
def count_word_frequency(filename):
"""
Count frequency of each word in a text file
Returns a dictionary with word counts
"""
word_count = {} # Dictionary to store word frequencies
try:
# Open and read the file
with open(filename, "r") as file:
# Read each line
for line in file:
# Convert to lowercase and split into words
line = [Link]().lower()
words = [Link]()
# Remove punctuation from words
clean_words = []
for word in words:
# Remove common punctuation
clean_word = [Link](".", "").replace(",", "").replace("!", "").
if clean_word: # Only add non-empty words
clean_words.append(clean_word)
# Count each word
for word in clean_words:
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1
except FileNotFoundError:
print(f"File '{filename}' not found!")
return {}
return word_count
# Step 3: Use the function and display results
word_frequencies = count_word_frequency("[Link]")
print("Word Frequencies:")
print("-" * 20)
for word, count in word_frequencies.items():
print(f"{word}: {count}")
Enhanced Version with Dictionary Comprehension:
def count_words_advanced(filename):
"""
Advanced word frequency counter using comprehensions
"""
try:
with open(filename, "r") as file:
# Read entire file and process
content = [Link]().lower()
# Remove punctuation (simple approach)
import string
for punct in [Link]:
content = [Link](punct, " ")
# Split into words and count using dictionary comprehension
words = [Link]()
# Create set of unique words
unique_words = set(words)
# Count frequency using dictionary comprehension
word_freq = {word: [Link](word) for word in unique_words}
return word_freq
except FileNotFoundError:
print("File not found!")
return {}
# Test the advanced function
frequencies = count_words_advanced("[Link]")
print("\nAdvanced Word Count:")
for word, count in sorted([Link]()):
print(f"{word}: {count}")
Practice 2: Store User Data in File
Create a simple user data storage system: [21] [22]
def collect_and_store_user_data():
"""
Collect user data and store it in a file
"""
users_data = []
print("User Data Collection System")
print("=" * 30)
while True:
print("\nEnter user information:")
# Collect user input
name = input("Name: ")
age = input("Age: ")
email = input("Email: ")
city = input("City: ")
# Create user record
user_record = f"{name},{age},{email},{city}\n"
users_data.append(user_record)
# Ask if user wants to continue
more_data = input("\nAdd another user? (y/n): ").lower()
if more_data != 'y':
break
# Store data in file
filename = "users_data.txt"
try:
with open(filename, "w") as file:
# Write header
[Link]("Name,Age,Email,City\n")
# Write user data
[Link](users_data)
print(f"\nData successfully saved to {filename}")
except Exception as e:
print(f"Error saving data: {e}")
def read_user_data():
"""
Read and display user data from file
"""
try:
with open("users_data.txt", "r") as file:
print("\nStored User Data:")
print("-" * 40)
lines = [Link]()
for i, line in enumerate(lines):
if i == 0: # Header line
print("Header:", [Link]())
print("-" * 40)
else:
data = [Link]().split(",")
print(f"User {i}: Name={data[^2_0]}, Age={data[^2_1]}, Email={data[^2
except FileNotFoundError:
print("No user data file found!")
# Run the data collection
# collect_and_store_user_data()
# read_user_data()
Advanced Version with Error Handling:
import os
from datetime import datetime
def advanced_user_data_system():
"""
Advanced user data system with validation and error handling
"""
def validate_email(email):
"""Simple email validation"""
return "@" in email and "." in email
def validate_age(age):
"""Validate age is a number"""
try:
age_num = int(age)
return 0 < age_num < 150
except ValueError:
return False
users = []
while True:
print("\n" + "="*40)
print("ADVANCED USER DATA SYSTEM")
print("="*40)
# Get and validate name
while True:
name = input("Enter name: ").strip()
if name and len(name) >= 2:
break
print("Please enter a valid name (at least 2 characters)")
# Get and validate age
while True:
age = input("Enter age: ").strip()
if validate_age(age):
break
print("Please enter a valid age (1-149)")
# Get and validate email
while True:
email = input("Enter email: ").strip()
if validate_email(email):
break
print("Please enter a valid email address")
# Get city
city = input("Enter city: ").strip() or "Not specified"
# Create user dictionary
user = {
'name': name,
'age': int(age),
'email': email,
'city': city,
'timestamp': [Link]().strftime("%Y-%m-%d %H:%M:%S")
}
[Link](user)
print(f"\nUser {name} added successfully!")
# Ask to continue
if input("\nAdd another user? (y/n): ").lower() != 'y':
break
# Save to file with error handling
filename = "advanced_users.txt"
try:
with open(filename, "w") as file:
# Write header
[Link]("Name,Age,Email,City,Timestamp\n")
# Write user data
for user in users:
line = f"{user['name']},{user['age']},{user['email']},{user['city']},{use
[Link](line)
print(f"\n✅ Data successfully saved to {filename}")
print(f"📁 File location: {[Link](filename)}")
except Exception as e:
print(f"❌ Error saving data: {e}")
# Run the advanced system
# advanced_user_data_system()
Practice 3: Generate Lists using Comprehensions
A. List of Squares
# Generate squares of numbers from 1 to 10
def generate_squares():
"""Generate list of squares using comprehensions"""
# Method 1: Simple squares
squares = [x**2 for x in range(1, 11)]
print("Squares 1-10:", squares)
# Method 2: Squares of even numbers only
even_squares = [x**2 for x in range(1, 11) if x % 2 == 0]
print("Even squares:", even_squares)
# Method 3: Squares with custom range
start = int(input("Enter start number: "))
end = int(input("Enter end number: "))
custom_squares = [x**2 for x in range(start, end + 1)]
print(f"Squares from {start} to {end}:", custom_squares)
return squares
# Test squares generation
squares_list = generate_squares()
B. List of Prime Numbers
def is_prime(n):
"""
Check if a number is prime
A prime number is only divisible by 1 and itself
"""
if n < 2:
return False
# Check divisibility from 2 to square root of n
for i in range(2, int(n**0.5) + 1):
if n % i == 0:
return False
return True
def generate_primes_traditional(limit):
"""Generate primes using traditional for loop"""
primes = []
for num in range(2, limit + 1):
if is_prime(num):
[Link](num)
return primes
def generate_primes_comprehension(limit):
"""Generate primes using list comprehension"""
return [num for num in range(2, limit + 1) if is_prime(num)]
def prime_number_generator():
"""Complete prime number generation system"""
print("Prime Number Generator")
print("=" * 25)
# Get limit from user
while True:
try:
limit = int(input("Enter upper limit for prime numbers: "))
if limit >= 2:
break
else:
print("Please enter a number >= 2")
except ValueError:
print("Please enter a valid number")
# Generate using both methods
primes_traditional = generate_primes_traditional(limit)
primes_comprehension = generate_primes_comprehension(limit)
print(f"\nPrime numbers up to {limit}:")
print("Traditional method:", primes_traditional)
print("Comprehension method:", primes_comprehension)
print("Both methods give same result:", primes_traditional == primes_comprehension)
# Show some statistics
print(f"\nStatistics:")
print(f"Total primes found: {len(primes_comprehension)}")
print(f"Largest prime: {max(primes_comprehension) if primes_comprehension else 'None'
print(f"Smallest prime: {min(primes_comprehension) if primes_comprehension else 'None
return primes_comprehension
# Test prime generation
primes = prime_number_generator()
C. Advanced Comprehensions
def advanced_comprehensions_examples():
"""
Advanced examples of list and dictionary comprehensions
"""
print("Advanced Comprehensions Examples")
print("=" * 35)
# 1. Nested list comprehensions
print("\n1. Creating a multiplication table:")
multiplication_table = [[i * j for j in range(1, 6)] for i in range(1, 6)]
for row in multiplication_table:
print(row)
# 2. Flattening nested lists
print("\n2. Flattening nested lists:")
nested_list = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
flattened = [num for sublist in nested_list for num in sublist]
print("Original:", nested_list)
print("Flattened:", flattened)
# 3. Dictionary comprehension with conditions
print("\n3. Dictionary comprehensions:")
# Create dictionary of numbers and their properties
numbers = range(1, 11)
num_properties = {
num: {
'square': num**2,
'cube': num**3,
'is_even': num % 2 == 0,
'is_prime': is_prime(num)
}
for num in numbers
}
# Display some examples
for num in [2, 3, 4, 5]:
print(f"Number {num}: {num_properties[num]}")
# 4. Set comprehension
print("\n4. Set comprehensions:")
words = ["hello", "world", "python", "programming", "hello", "world"]
unique_lengths = {len(word) for word in words}
print("Words:", words)
print("Unique word lengths:", unique_lengths)
# 5. Generator comprehension (memory efficient)
print("\n5. Generator comprehensions:")
squares_generator = (x**2 for x in range(1, 1000000)) # Memory efficient!
print("First 10 squares from generator:", [next(squares_generator) for _ in range(10)
# Run advanced examples
advanced_comprehensions_examples()
Complete Project: File Processing with Comprehensions
Let's create a complete project that combines everything:
import os
import string
from datetime import datetime
class FileProcessor:
"""
Complete file processing system using comprehensions
"""
def __init__(self, filename):
[Link] = filename
self.word_stats = {}
self.line_stats = {}
def create_sample_file(self):
"""Create a sample text file for testing"""
sample_content = """
Python is a powerful programming language.
It is easy to learn and very versatile.
You can use Python for web development, data science, and automation.
Many companies use Python for their projects.
Learning Python opens many career opportunities.
Python Python Python is everywhere!
"""
with open([Link], 'w') as file:
[Link](sample_content.strip())
print(f"✅ Sample file '{[Link]}' created successfully!")
def analyze_file(self):
"""Analyze the file and generate statistics"""
if not [Link]([Link]):
print(f"❌ File '{[Link]}' not found!")
return
try:
with open([Link], 'r') as file:
lines = [Link]()
# Line statistics using comprehensions
self.line_stats = {
'total_lines': len(lines),
'non_empty_lines': len([line for line in lines if [Link]()]),
'line_lengths': [len([Link]()) for line in lines],
'longest_line_length': max([len([Link]()) for line in lines] or [^2_0
'shortest_line_length': min([len([Link]()) for line in lines if line.
}
# Word analysis
all_text = ' '.join(lines).lower()
# Remove punctuation using comprehension
clean_text = ''.join([char if char not in [Link] else ' ' for cha
words = clean_text.split()
unique_words = set(words)
# Word statistics using comprehensions
self.word_stats = {
'total_words': len(words),
'unique_words': len(unique_words),
'word_frequencies': {word: [Link](word) for word in unique_words},
'words_by_length': {length: [word for word in unique_words if len(word) =
for length in set(len(word) for word in unique_words)},
'long_words': [word for word in unique_words if len(word) > 5]
}
print("✅ File analysis completed!")
except Exception as e:
print(f"❌ Error analyzing file: {e}")
def display_statistics(self):
"""Display comprehensive file statistics"""
if not self.word_stats or not self.line_stats:
print("❌ No statistics available. Run analyze_file() first.")
return
print("\n" + "="*50)
print("FILE ANALYSIS REPORT")
print("="*50)
print(f"File: {[Link]}")
print(f"Analysis Date: {[Link]().strftime('%Y-%m-%d %H:%M:%S')}")
# Line Statistics
print(f"\n📊 LINE STATISTICS:")
print(f" Total lines: {self.line_stats['total_lines']}")
print(f" Non-empty lines: {self.line_stats['non_empty_lines']}")
print(f" Longest line: {self.line_stats['longest_line_length']} characters")
print(f" Shortest line: {self.line_stats['shortest_line_length']} characters")
print(f" Average line length: {sum(self.line_stats['line_lengths'])/len([Link]
# Word Statistics
print(f"\n📚 WORD STATISTICS:")
print(f" Total words: {self.word_stats['total_words']}")
print(f" Unique words: {self.word_stats['unique_words']}")
print(f" Long words (>5 chars): {len(self.word_stats['long_words'])}")
# Top word frequencies
print(f"\n🔤 TOP 10 MOST FREQUENT WORDS:")
sorted_words = sorted(self.word_stats['word_frequencies'].items(),
key=lambda x: x[^2_1], reverse=True)[:10]
for i, (word, freq) in enumerate(sorted_words, 1):
print(f" {i:2}. {word}: {freq} times")
# Words by length
print(f"\n📏 WORDS BY LENGTH:")
for length in sorted(self.word_stats['words_by_length'].keys()):
words_of_length = self.word_stats['words_by_length'][length]
print(f" {length} chars: {len(words_of_length)} words - {words_of_length[:5
def save_report(self, report_filename=None):
"""Save analysis report to file"""
if not report_filename:
timestamp = [Link]().strftime("%Y%m%d_%H%M%S")
report_filename = f"analysis_report_{timestamp}.txt"
try:
with open(report_filename, 'w') as file:
[Link](f"FILE ANALYSIS REPORT\n")
[Link](f"="*50 + "\n")
[Link](f"Source File: {[Link]}\n")
[Link](f"Analysis Date: {[Link]().strftime('%Y-%m-%d %H:%M:%S')
# Write statistics
[Link]("LINE STATISTICS:\n")
for key, value in self.line_stats.items():
[Link](f" {key}: {value}\n")
[Link]("\nWORD STATISTICS:\n")
[Link](f" Total words: {self.word_stats['total_words']}\n")
[Link](f" Unique words: {self.word_stats['unique_words']}\n")
[Link](f" Long words: {len(self.word_stats['long_words'])}\n")
[Link]("\nWORD FREQUENCIES:\n")
sorted_words = sorted(self.word_stats['word_frequencies'].items(),
key=lambda x: x[^2_1], reverse=True)
for word, freq in sorted_words:
[Link](f" {word}: {freq}\n")
print(f"✅ Report saved to '{report_filename}'")
except Exception as e:
print(f"❌ Error saving report: {e}")
# Usage example and testing
def main():
"""Main function to demonstrate the file processor"""
print("🐍 FILE PROCESSING WITH COMPREHENSIONS")
print("="*40)
# Create processor instance
processor = FileProcessor("sample_text.txt")
# Create sample file
processor.create_sample_file()
# Analyze the file
processor.analyze_file()
# Display results
processor.display_statistics()
# Save report
processor.save_report()
print("\n🎉 File processing complete!")
# Run the main program
if __name__ == "__main__":
main()
Study Tips and Best Practices
For File I/O:
1. Always use with statement - It's the most important best practice [13] [12]
2. Handle exceptions - Files might not exist or permissions might be denied
3. Choose appropriate read methods - read() for small files, readline() for large files
4. Specify encoding when working with non-ASCII text (e.g., encoding='utf-8')
5. Close files properly - with statement does this automatically
For Comprehensions:
1. Start simple - Begin with basic comprehensions before complex ones
2. Use comprehensions for readability - They should make code clearer, not more complex
3. Avoid complex nested comprehensions - Break them into multiple steps if needed
4. Consider memory usage - Use generator expressions for large datasets
5. Add conditions wisely - Use if conditions to filter effectively
Common Mistakes to Avoid:
1. Forgetting to close files (solved by using with)
2. Not handling file exceptions
3. Making comprehensions too complex
4. Not validating user input
5. Hardcoding file paths (use [Link] for better portability) [12]
This comprehensive guide covers all the essential concepts of File I/O and comprehensions with
practical examples and best practices. Practice these examples step by step, and gradually
work on more complex projects to solidify your understanding.
⁂
1. [Link]
2. [Link]
3. [Link]
4. [Link]
5. [Link]
6. [Link]
7. [Link]
8. [Link]
9. [Link]
10. [Link]
11. [Link]
12. [Link]
13. [Link]
14. [Link]
15. [Link]
16. [Link]
17. [Link]
18. [Link]
19. [Link]
20. [Link]
21. [Link]
22. [Link]
23. [Link]
24. [Link]
25. [Link]
26. [Link]
27. [Link]
28. [Link]
29. [Link]
30. [Link]
31. [Link]
32. [Link]
33. [Link]
34. [Link]
35. [Link]
36. [Link]
in_python
37. [Link]
38. [Link]
39. [Link]
40. [Link]
41. [Link]
42. [Link]
43. [Link]
44. [Link]
hension
45. [Link]
46. [Link]