Python coding
Advanced_Python_Architecture_Mastery.pdf
def exit(
self,
exc_type,
exc_val,
exc_tb
):
print(
"Connection Closed Safely"
)
with DatabaseConnection() as db:
print(
"Running queries..."
)
python
Open resource
Do work
Manually close resource
python
Open resource
Do work
Automatically close resource
text
OOP → Structure
Decorators → Flexibility
Generators → Scale
Asyncio → Speed
Context Managers → Safety
python
Robot
python
name
version
speak()
text
Function Started
Function Finished
python
1 to 100
python
asyncio.gather()
text
Resource Opened
text
Resource Closed
when exiting.
self,
exc_type,
exc_val,
exc_tb
):
print(
"Connection Closed Safely"
)
with DatabaseConnection() as db:
print(
"Running queries..."
)
---
## Why Context Managers Matter
Without context managers:
python
Open resource
Do work
Manually close resource
Easy to forget.
---
With context managers:
python
Open resource
Do work
Automatically close resource
Safer and cleaner.
---
Common Uses
- Files
- Databases
- Network connections
- Cloud resources
---
# The AI Architect Mindset
Advanced Python is not only about writing code.
It is about designing systems that are:
- Scalable
- Maintainable
- Efficient
- Professional
Use:
text
OOP → Structure
Decorators → Flexibility
Generators → Scale
Asyncio → Speed
Context Managers → Safety
These concepts form the foundation of professional software engineering and AI architecture. 5
---
# Practice Exercises
### 1. OOP Challenge
Create a class called:
python
Robot
Add:
python
name
version
speak()
---
### 2. Decorator Challenge
Create a decorator that prints:
text
Function Started
Function Finished
before and after execution.
---
### 3. Generator Challenge
Create a generator that yields:
python
1 to 100
one number at a time.
---
### 4. Async Challenge
Create three asynchronous functions and execute them using:
python
asyncio.gather()
---
### 5. Context Manager Challenge
Create a custom context manager that prints:
text
Resource Opened
when entering and:
text
Resource Closed
`when exiting.
❤1
━━━━━━━━━━━━━━━━━━━━━━
🎓 COURSE COMPLETED
━━━━━━━━━━━━━━━━━━━━━━
Congratulations!
You have successfully completed the Python Programming Masterclass.
From Python fundamentals to Advanced Python Architecture, you have gained the knowledge and skills needed to continue your journey in software development, data science, and AI.
However, learning does not stop here.
In the coming days, this channel will continue to provide:
✓ Practice Questions
✓ Quizzes and Tests
✓ Programming Challenges
✓ Projects
✓ Advanced Tips
✓ Learning Resources
✓ Course Updates
✓ AI & Technology Content
Make sure to stay active, participate in discussions, and complete the upcoming exercises to strengthen your understanding.
The course may be complete, but the journey of mastery has only begun.
Keep learning.
Keep building.
Keep improving.
━━━━━━━━━━━━━━━━━━━━━━
Course Status: COMPLETED ✓
Next Phase: Practice & Mastery
━━━━━━━━━━━━━━━━━━━━━━
By Yehya Oumer
Mizan Institute of Technology
2026
🎓 COURSE COMPLETED
━━━━━━━━━━━━━━━━━━━━━━
Congratulations!
You have successfully completed the Python Programming Masterclass.
From Python fundamentals to Advanced Python Architecture, you have gained the knowledge and skills needed to continue your journey in software development, data science, and AI.
However, learning does not stop here.
In the coming days, this channel will continue to provide:
✓ Practice Questions
✓ Quizzes and Tests
✓ Programming Challenges
✓ Projects
✓ Advanced Tips
✓ Learning Resources
✓ Course Updates
✓ AI & Technology Content
Make sure to stay active, participate in discussions, and complete the upcoming exercises to strengthen your understanding.
The course may be complete, but the journey of mastery has only begun.
Keep learning.
Keep building.
Keep improving.
━━━━━━━━━━━━━━━━━━━━━━
Course Status: COMPLETED ✓
Next Phase: Practice & Mastery
━━━━━━━━━━━━━━━━━━━━━━
By Yehya Oumer
Mizan Institute of Technology
2026
📢 New Chapter Started
The lessons are finished.
Now we focus on what matters most:
Building.
Expect daily Python content:
✓ Projects
✓ Useful Scripts
✓ Coding Challenges
✓ AI Tools
✓ Python Tips
✓ Career Advice
✓ Advanced Concepts
Don't become someone who completed a course.
Become someone who uses what they learned.
Stay tuned.
The lessons are finished.
Now we focus on what matters most:
Building.
Expect daily Python content:
✓ Projects
✓ Useful Scripts
✓ Coding Challenges
✓ AI Tools
✓ Python Tips
✓ Career Advice
✓ Advanced Concepts
Don't become someone who completed a course.
Become someone who uses what they learned.
Stay tuned.
🐍 Python Tip #1: List Comprehensions
List comprehensions allow you to create lists in a shorter and cleaner way.
Instead of:
You can write:
Output:
---
You can also perform operations while creating the list.
Example:
Output:
---
Using conditions:
Output:
---
Why use list comprehensions?
✓ Cleaner code
✓ Fewer lines
✓ Faster execution
✓ Widely used in Data Science and AI
Challenge:
Create a list comprehension that generates:
without manually typing the numbers.
List comprehensions allow you to create lists in a shorter and cleaner way.
Instead of:
numbers = []
for i in range(1, 6):
numbers.append(i)
print(numbers)
You can write:
numbers = [i for i in range(1, 6)]
print(numbers)
Output:
[1, 2, 3, 4, 5]
---
You can also perform operations while creating the list.
Example:
squares = [x**2 for x in range(1, 6)]
print(squares)
Output:
[1, 4, 9, 16, 25]
---
Using conditions:
even_numbers = [
x for x in range(1, 11)
if x % 2 == 0
]
print(even_numbers)
Output:
[2, 4, 6, 8, 10]
---
Why use list comprehensions?
✓ Cleaner code
✓ Fewer lines
✓ Faster execution
✓ Widely used in Data Science and AI
Challenge:
Create a list comprehension that generates:
[10, 20, 30, 40, 50]
without manually typing the numbers.
Python coding
🐍 Python Tip #1: List Comprehensions List comprehensions allow you to create lists in a shorter and cleaner way. Instead of: numbers = [] for i in range(1, 6): numbers.append(i) print(numbers) You can write: numbers = [i for i in range(1, 6)] print(numbers)…
💡 Python Tip #2: The
When looping through a list, you often need both the item's index and its value.
Instead of writing:
You can use
Output:
---
Starting the Index from a Different Number
By default,
You can change the starting number:
Output:
---
Why use
✓ Cleaner and more readable code
✓ No need to manually manage indexes
✓ Reduces common indexing mistakes
✓ Frequently used in real-world Python projects
---
Challenge:
Without using
using this list:
enumerate() FunctionWhen looping through a list, you often need both the item's index and its value.
Instead of writing:
fruits = ["Apple", "Banana", "Orange"]
for i in range(len(fruits)):
print(i, fruits[i])
You can use
enumerate():fruits = ["Apple", "Banana", "Orange"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 Apple
1 Banana
2 Orange
---
Starting the Index from a Different Number
By default,
enumerate() starts counting from 0.You can change the starting number:
fruits = ["Apple", "Banana", "Orange"]
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
Output:
1 Apple
2 Banana
3 Orange
---
Why use
enumerate()?✓ Cleaner and more readable code
✓ No need to manually manage indexes
✓ Reduces common indexing mistakes
✓ Frequently used in real-world Python projects
---
Challenge:
Without using
range(len()), print the following output using enumerate():Student 1: Ahmed
Student 2: Sara
Student 3: John
using this list:
students = ["Ahmed", "Sara", "John"]
Python coding
💡 Python Tip #2: The enumerate() Function When looping through a list, you often need both the item's index and its value. Instead of writing: fruits = ["Apple", "Banana", "Orange"] for i in range(len(fruits)): print(i, fruits[i]) You can use enumerate():…
🔥 Python Trick #3: Multiple Variable Assignment
Python allows you to assign multiple variables in a single line.
Instead of:
You can write:
---
You can also assign the same value to multiple variables.
Example:
Simplified:
---
Unpacking a Collection
Python can unpack a list or tuple directly into variables.
Example:
Output:
---
Ignoring Values
If you only need some values, use
Example:
Output:
---
Why use multiple assignment?
✓ Cleaner code
✓ Less typing
✓ Easier to read
✓ Commonly used in professional Python code
---
Challenge:
Without creating temporary variables, write Python code that swaps the values of:
so the final output becomes:
Python allows you to assign multiple variables in a single line.
Instead of:
name = "Yehya"
age = 16
country = "Ethiopia"
You can write:
name, age, country = "Yehya", 16, "Ethiopia"
---
You can also assign the same value to multiple variables.
Example:
x = 0
y = 0
z = 0
Simplified:
x = y = z = 0
---
Unpacking a Collection
Python can unpack a list or tuple directly into variables.
Example:
languages = ["Python", "Java", "C++"]
first, second, third = languages
print(first)
print(second)
print(third)
Output:
Python
Java
C++
---
Ignoring Values
If you only need some values, use
_ for the ones you don't care about.Example:
numbers = (10, 20, 30)
first, _, third = numbers
print(first)
print(third)
Output:
10
30
---
Why use multiple assignment?
✓ Cleaner code
✓ Less typing
✓ Easier to read
✓ Commonly used in professional Python code
---
Challenge:
Without creating temporary variables, write Python code that swaps the values of:
a = 15
b = 40
so the final output becomes:
a = 40
b = 15
Python coding
🔥 Python Trick #3: Multiple Variable Assignment Python allows you to assign multiple variables in a single line. Instead of: name = "Yehya" age = 16 country = "Ethiopia" You can write: name, age, country = "Yehya", 16, "Ethiopia" --- You can also assign…
🐍 Python Tip #4: The
The
Example:
Output:
---
Using
You can combine more than two lists.
Example:
Output:
---
Converting
The
To see all paired values, convert it into a list.
Example:
Output:
---
Why use
✓ Iterate over multiple lists at the same time
✓ Write cleaner and shorter code
✓ Avoid manual indexing with
✓ Frequently used in data processing and automation
---
Challenge:
Using
using these lists:
zip() FunctionThe
zip() function combines two or more iterables element by element.Example:
names = ["Ahmed", "Sara", "John"]
scores = [95, 88, 91]
for name, score in zip(names, scores):
print(name, score)
Output:
Ahmed 95
Sara 88
John 91
---
Using
zip() with Three ListsYou can combine more than two lists.
Example:
names = ["Ahmed", "Sara", "John"]
ages = [18, 19, 20]
countries = ["Egypt", "Ethiopia", "Canada"]
for name, age, country in zip(names, ages, countries):
print(name, age, country)
Output:
Ahmed 18 Egypt
Sara 19 Ethiopia
John 20 Canada
---
Converting
zip() to a ListThe
zip() function returns a zip object.To see all paired values, convert it into a list.
Example:
letters = ["A", "B", "C"]
numbers = [1, 2, 3]
result = list(zip(letters, numbers))
print(result)
Output:
[('A', 1), ('B', 2), ('C', 3)]---
Why use
zip()?✓ Iterate over multiple lists at the same time
✓ Write cleaner and shorter code
✓ Avoid manual indexing with
range() ✓ Frequently used in data processing and automation
---
Challenge:
Using
zip(), print the following output:Ali scored 90
Sara scored 85
John scored 95
using these lists:
students = ["Ali", "Sara", "John"]
marks = [90, 85, 95]
Python coding
🐍 Python Tip #4: The zip() Function The zip() function combines two or more iterables element by element. Example: names = ["Ahmed", "Sara", "John"] scores = [95, 88, 91] for name, score in zip(names, scores): print(name, score) Output: Ahmed 95 Sara…
⚡ Python Tip #5: The
Python provides two useful built-in functions for checking multiple conditions:
---
Using
The
Example:
Output:
---
Using
The
Example:
Output:
---
Another Example
Output:
Since every number is greater than 5,
---
Example with
Output:
Only one number (
---
Why use
✓ Makes code shorter and cleaner
✓ Eliminates unnecessary loops
✓ Easy way to evaluate multiple conditions
✓ Commonly used in data validation and filtering
---
Challenge:
Given the list:
1. Check if all numbers are even.
2. Check if any number is greater than 20.
Try solving it before running the code!
any() and all() FunctionsPython provides two useful built-in functions for checking multiple conditions:
any() and all().---
Using
any()The
any() function returns True if at least one value is True.Example:
values = [False, False, True]
print(any(values))
Output:
True
---
Using
all()The
all() function returns True only if every value is True.Example:
values = [True, True, True]
print(all(values))
Output:
True
---
Another Example
numbers = [10, 20, 30, 40]
print(all(num > 5 for num in numbers))
Output:
True
Since every number is greater than 5,
all() returns True.---
Example with
any()numbers = [10, 20, 30, 40]
print(any(num > 35 for num in numbers))
Output:
True
Only one number (
40) is greater than 35, so any() returns True.---
Why use
any() and all()?✓ Makes code shorter and cleaner
✓ Eliminates unnecessary loops
✓ Easy way to evaluate multiple conditions
✓ Commonly used in data validation and filtering
---
Challenge:
Given the list:
numbers = [12, 18, 25, 30]
1. Check if all numbers are even.
2. Check if any number is greater than 20.
Try solving it before running the code!
Python coding
⚡ Python Tip #5: The any() and all() Functions Python provides two useful built-in functions for checking multiple conditions: any() and all(). --- Using any() The any() function returns True if at least one value is True. Example: values = [False, False…
🚀 Python Tip #6: The
Sometimes you don't know how many arguments a function will receive.
Python provides
---
Using
The
Example:
Output:
---
Using
The
Example:
Output:
---
Using Both Together
A function can use both
Example:
Output:
---
Why use
✓ Accept a flexible number of arguments
✓ Build reusable functions
✓ Useful for libraries and frameworks
✓ Commonly used in Flask, Django, and AI libraries
---
Challenge:
Create a function called
Example:
Expected Output:
*args and **kwargs ParametersSometimes you don't know how many arguments a function will receive.
Python provides
*args and **kwargs to handle this flexibly.---
Using
*argsThe
*args parameter allows a function to accept any number of positional arguments.Example:
def add_numbers(*args):
print(sum(args))
add_numbers(5, 10)
add_numbers(1, 2, 3, 4, 5)
Output:
15
15
---
Using
**kwargsThe
**kwargs parameter allows a function to accept any number of keyword arguments.Example:
def student_info(**kwargs):
for key, value in kwargs.items():
print(f"{key}: {value}")
student_info(
name="Ahmed",
age=18,
country="Ethiopia"
)
Output:
name: Ahmed
age: 18
country: Ethiopia
---
Using Both Together
A function can use both
*args and **kwargs.Example:
def display(*args, **kwargs):
print(args)
print(kwargs)
display(
10,
20,
name="Sara",
age=19
)
Output:
(10, 20)
{'name': 'Sara', 'age': 19}
---
Why use
*args and **kwargs?✓ Accept a flexible number of arguments
✓ Build reusable functions
✓ Useful for libraries and frameworks
✓ Commonly used in Flask, Django, and AI libraries
---
Challenge:
Create a function called
multiply() that accepts any number of numbers using *args and returns their product.Example:
multiply(2, 3, 4)
Expected Output:
24
Python coding
🚀 Python Tip #6: The *args and **kwargs Parameters Sometimes you don't know how many arguments a function will receive. Python provides *args and **kwargs to handle this flexibly. --- Using *args The *args parameter allows a function to accept any number…
🐍 Python Tip #7: The
When looping through a list, you sometimes need both the index and the value.
Instead of manually tracking the index, Python provides the
---
Without
Output:
---
With
Output:
---
Starting from a Different Number
You can choose where the counting begins.
Example:
Output:
---
Why use
✓ Cleaner code
✓ No need for a manual counter
✓ Easier to read and maintain
✓ Commonly used in Python projects
---
Challenge:
Using
using this list:
enumerate() FunctionWhen looping through a list, you sometimes need both the index and the value.
Instead of manually tracking the index, Python provides the
enumerate() function.---
Without
enumerate()fruits = ["Apple", "Banana", "Orange"]
index = 0
for fruit in fruits:
print(index, fruit)
index += 1
Output:
0 Apple
1 Banana
2 Orange
---
With
enumerate()fruits = ["Apple", "Banana", "Orange"]
for index, fruit in enumerate(fruits):
print(index, fruit)
Output:
0 Apple
1 Banana
2 Orange
---
Starting from a Different Number
You can choose where the counting begins.
Example:
fruits = ["Apple", "Banana", "Orange"]
for index, fruit in enumerate(fruits, start=1):
print(index, fruit)
Output:
1 Apple
2 Banana
3 Orange
---
Why use
enumerate()?✓ Cleaner code
✓ No need for a manual counter
✓ Easier to read and maintain
✓ Commonly used in Python projects
---
Challenge:
Using
enumerate(), print the following output:Question 1: What is Python?
Question 2: What is a List?
Question 3: What is a Dictionary?
using this list:
questions = [
"What is Python?",
"What is a List?",
"What is a Dictionary?"
]
Python coding
🐍 Python Tip #7: The enumerate() Function When looping through a list, you sometimes need both the index and the value. Instead of manually tracking the index, Python provides the enumerate() function. --- Without enumerate() fruits = ["Apple", "Banana"…
⚡ Python Tip #8: The
The
---
Basic Example
Output:
The original list remains unchanged.
---
Sorting in Descending Order
Use the
Output:
---
Sorting Strings
Output:
---
Difference Between
Output:
---
`list.sort()
numbers = [3, 1, 2]
numbers.sort()
print(numbers)
python
[1, 2, 3]
python
scores = [88, 95, 72, 100, 67]
1. Print the scores in ascending order.
2. Print the scores in descending order.
3. Verify that the original list remains unchanged after using `sorted()`.
sorted() FunctionThe
sorted() function returns a new sorted list without modifying the original one.---
Basic Example
numbers = [5, 2, 8, 1, 9]
result = sorted(numbers)
print(result)
Output:
[1, 2, 5, 8, 9]
The original list remains unchanged.
---
Sorting in Descending Order
Use the
reverse=True parameter.numbers = [5, 2, 8, 1, 9]
result = sorted(numbers, reverse=True)
print(result)
Output:
[9, 8, 5, 2, 1]
---
Sorting Strings
fruits = ["Orange", "Apple", "Banana", "Mango"]
print(sorted(fruits))
Output:
['Apple', 'Banana', 'Mango', 'Orange']
---
Difference Between
sorted() and sort()sorted()numbers = [3, 1, 2]
new_numbers = sorted(numbers)
print(numbers)
print(new_numbers)
Output:
[3, 1, 2]
[1, 2, 3]
---
`list.sort()
``pythonnumbers = [3, 1, 2]
numbers.sort()
print(numbers)
Output:
python
[1, 2, 3]
Unlike `sorted()`, the `sort()` method modifies the original list.
---
Why use `sorted()`?
✓ Keeps the original data unchanged
✓ Easy to sort numbers and strings
✓ Supports ascending and descending order
✓ Commonly used in data processing and reporting
---
Challenge:
Given the list:
python
scores = [88, 95, 72, 100, 67]
`1. Print the scores in ascending order.
2. Print the scores in descending order.
3. Verify that the original list remains unchanged after using `sorted()`.
Python coding
⚡ Python Tip #8: The sorted() Function The sorted() function returns a new sorted list without modifying the original one. --- Basic Example numbers = [5, 2, 8, 1, 9] result = sorted(numbers) print(result) Output: [1, 2, 5, 8, 9] The original list remains…
💡 Python Tip #9: Lambda Functions
A lambda function is a small anonymous function that can have any number of arguments but only one expression.
Lambda functions are useful when you need a simple function for a short period of time.
---
Basic Syntax
---
Example
Instead of writing:
You can write:
Output:
---
Multiple Arguments
Lambda functions can accept multiple arguments.
Example:
Output:
---
Using
You can sort complex data using a custom key.
Example:
Output:
---
Why use Lambda Functions?
✓ Write short functions quickly
✓ Useful with
✓ Makes code more concise
✓ Commonly used in data analysis and automation
---
Challenge:
Using a lambda function, create a function that returns the cube of a number.
Example:
Expected Output:
A lambda function is a small anonymous function that can have any number of arguments but only one expression.
Lambda functions are useful when you need a simple function for a short period of time.
---
Basic Syntax
lambda arguments: expression
---
Example
Instead of writing:
def square(x):
return x ** 2
print(square(5))
You can write:
square = lambda x: x ** 2
print(square(5))
Output:
25
---
Multiple Arguments
Lambda functions can accept multiple arguments.
Example:
multiply = lambda a, b: a * b
print(multiply(6, 4))
Output:
24
---
Using
lambda with sorted()You can sort complex data using a custom key.
Example:
students = [
("Ali", 85),
("Sara", 95),
("John", 78)
]
result = sorted(
students,
key=lambda student: student[1]
)
print(result)
Output:
[('John', 78), ('Ali', 85), ('Sara', 95)]---
Why use Lambda Functions?
✓ Write short functions quickly
✓ Useful with
sorted(), map(), and filter() ✓ Makes code more concise
✓ Commonly used in data analysis and automation
---
Challenge:
Using a lambda function, create a function that returns the cube of a number.
Example:
cube = lambda x: x ** 3
print(cube(4))
Expected Output:
64
Python coding
💡 Python Tip #9: Lambda Functions A lambda function is a small anonymous function that can have any number of arguments but only one expression. Lambda functions are useful when you need a simple function for a short period of time. --- Basic Syntax lambda…
🚀 Python Tip #10: The
Counting how many times items appear in a list is a common task.
Instead of writing loops manually, Python provides the
---
Importing
---
Basic Example
Output:
---
Counting Characters
Output:
---
Finding the Most Common Items
Use the
Example:
Output:
---
Why use
✓ Count items with a single line of code
✓ Find the most common elements quickly
✓ Useful for text analysis and data processing
✓ Frequently used in Data Science and Machine Learning
---
Challenge:
Given the following list:
1. Count how many times each number appears.
2. Print the most common number.
3. Which number appears exactly once?
collections.Counter ClassCounting how many times items appear in a list is a common task.
Instead of writing loops manually, Python provides the
Counter class from the collections module.---
Importing
Counterfrom collections import Counter
---
Basic Example
from collections import Counter
fruits = [
"apple",
"banana",
"apple",
"orange",
"banana",
"apple"
]
count = Counter(fruits)
print(count)
Output:
Counter({
'apple': 3,
'banana': 2,
'orange': 1
})---
Counting Characters
from collections import Counter
text = "programming"
count = Counter(text)
print(count)
Output:
Counter({
'g': 2,
'r': 2,
'm': 2,
'p': 1,
'o': 1,
'a': 1,
'i': 1,
'n': 1
})---
Finding the Most Common Items
Use the
most_common() method.Example:
from collections import Counter
votes = [
"Python",
"Java",
"Python",
"C++",
"Python",
"Java"
]
count = Counter(votes)
print(count.most_common(1))
Output:
[('Python', 3)]---
Why use
Counter?✓ Count items with a single line of code
✓ Find the most common elements quickly
✓ Useful for text analysis and data processing
✓ Frequently used in Data Science and Machine Learning
---
Challenge:
Given the following list:
numbers = [1, 2, 2, 3, 3, 3, 4, 4, 5]
1. Count how many times each number appears.
2. Print the most common number.
3. Which number appears exactly once?
Python coding
🚀 Python Tip #10: The collections.Counter Class Counting how many times items appear in a list is a common task. Instead of writing loops manually, Python provides the Counter class from the collections module. --- Importing Counter from collections import…
🔥 Python Tip #11: The
When working with dictionaries, you may need to access a key that doesn't exist.
Instead of checking if the key exists first, Python provides the
---
Basic Example
Output:
Since `"age"
student = {
"name": "Ahmed"
}
student.setdefault("country", "Ethiopia")
print(student)
python
{
'name': 'Ahmed',
'country': 'Ethiopia'
}
python
if "country" not in student:
student["country"] = "Ethiopia"
python
student.setdefault("country", "Ethiopia")
python
words = ["apple", "banana", "apple"]
counts = {}
for word in words:
counts.setdefault(word, 0)
counts[word] += 1
print(counts)
python
{
'apple': 2,
'banana': 1
}
python
cities = [
"Addis Ababa",
"Adama",
"Addis Ababa",
"Hawassa",
"Adama"
]
Use `setdefault()` to count how many times each city appears.
setdefault() Dictionary MethodWhen working with dictionaries, you may need to access a key that doesn't exist.
Instead of checking if the key exists first, Python provides the
setdefault() method.---
Basic Example
student = {
"name": "Ahmed",
"age": 18
}
print(student.setdefault("age", 20))Output:
18
Since `"age"
already exists, its value remains unchanged.
---
Adding a New Key
If the key does not exist, setdefault() creates it using the default value.
Example:
``pythonstudent = {
"name": "Ahmed"
}
student.setdefault("country", "Ethiopia")
print(student)
Output:
python
{
'name': 'Ahmed',
'country': 'Ethiopia'
}
---
Without `setdefault()`
python
if "country" not in student:
student["country"] = "Ethiopia"
---
With `setdefault()`
python
student.setdefault("country", "Ethiopia")
Both produce the same result, but `setdefault()` is shorter and cleaner.
---
Practical Example
Count words without worrying about missing keys.
python
words = ["apple", "banana", "apple"]
counts = {}
for word in words:
counts.setdefault(word, 0)
counts[word] += 1
print(counts)
Output:
python
{
'apple': 2,
'banana': 1
}
---
Why use `setdefault()`?
✓ Avoids `KeyError`
✓ Reduces repetitive code
✓ Automatically creates missing keys
✓ Useful when counting, grouping, or organizing data
---
Challenge:
Given the list:
python
cities = [
"Addis Ababa",
"Adama",
"Addis Ababa",
"Hawassa",
"Adama"
]
`Use `setdefault()` to count how many times each city appears.
Python coding
🔥 Python Tip #11: The setdefault() Dictionary Method When working with dictionaries, you may need to access a key that doesn't exist. Instead of checking if the key exists first, Python provides the setdefault() method. --- Basic Example student = { …
🐍 Python Tip #12: The
Working with files and folders is a common task in Python.
Instead of using traditional string paths, Python provides the
---
Importing
---
Creating a Path
Output:
---
Checking if a File Exists
Output:
or
```python
False
python
from pathlib import Path
file = Path("report.pdf")
print(file.name)
print(file.stem)
print(file.suffix)
python
report.pdf
report
.pdf
python
from pathlib import Path
folder = Path("Projects")
folder.mkdir(exist_ok=True)
python
path = "Projects/" + "Python/" + "main.py"
python
from pathlib import Path
path = Path("Projects") / "Python" / "main.py"
print(path)
python
Projects/Python/main.py
python
Python_Practice
python
notes.txt
text
File found
text
File not found
based on the result.
pathlib ModuleWorking with files and folders is a common task in Python.
Instead of using traditional string paths, Python provides the
pathlib module, which offers a cleaner and more object-oriented approach.---
Importing
Pathfrom pathlib import Path
---
Creating a Path
from pathlib import Path
file = Path("notes.txt")
print(file)
Output:
notes.txt
---
Checking if a File Exists
from pathlib import Path
file = Path("notes.txt")
print(file.exists())
Output:
True
or
```python
False
depending on whether the file exists.
---
Getting File Information
python
from pathlib import Path
file = Path("report.pdf")
print(file.name)
print(file.stem)
print(file.suffix)
Output:
python
report.pdf
report
---
Creating a Folder
python
from pathlib import Path
folder = Path("Projects")
folder.mkdir(exist_ok=True)
The `exist_ok=True` argument prevents an error if the folder already exists.
---
Joining Paths
Instead of writing:
python
path = "Projects/" + "Python/" + "main.py"
Use:
python
from pathlib import Path
path = Path("Projects") / "Python" / "main.py"
print(path)
Output:
python
Projects/Python/main.py
---
Why use `pathlib`?
✓ Cleaner and easier to read
✓ Works across Windows, Linux, and macOS
✓ Object-oriented design
✓ Recommended for modern Python projects
---
Challenge:
Create a program that:
1. Creates a folder named:
python
Python_Practice
2. Checks whether a file named:
python
notes.txt
exists inside that folder.
3. Prints:
text
File found
or
text
File not found
`based on the result.
🤔1
Python coding
🐍 Python Tip #12: The pathlib Module Working with files and folders is a common task in Python. Instead of using traditional string paths, Python provides the pathlib module, which offers a cleaner and more object-oriented approach. --- Importing Path…
🧪 Python Tip #13: Using
When writing unit tests, you don't always want to call real databases, APIs, or external services.
Instead, you can use
---
Importing
---
Why Use
Imagine you have a function that connects to a database.
In a real application, this function might:
- Take several seconds to execute
- Require an internet connection
- Access a real database
- Return different results each time
During testing, this is slow and unreliable.
---
Without
This would execute the real database logic.
---
With
Output:
---
How It Works
Creates a fake version of the function.
Whenever the function is called, it immediately returns the specified value instead of executing the original code.
---
Why use
✓ Makes tests run much faster
✓ No need for a real database or API
✓ Produces predictable results
✓ Essential for professional unit testing
---
Challenge:
Create a
Then print the returned dictionary.
MagicMock for TestingWhen writing unit tests, you don't always want to call real databases, APIs, or external services.
Instead, you can use
MagicMock from Python's unittest.mock module to simulate their behavior.---
Importing
MagicMockfrom unittest.mock import MagicMock
---
Why Use
MagicMock?Imagine you have a function that connects to a database.
In a real application, this function might:
- Take several seconds to execute
- Require an internet connection
- Access a real database
- Return different results each time
During testing, this is slow and unreliable.
---
Without
MagicMockdef get_user_from_db(user_id):
# Slow database query
pass
user = get_user_from_db(1)
print(user)
This would execute the real database logic.
---
With
MagicMockfrom unittest.mock import MagicMock
def get_user_from_db(user_id):
# Slow database query
pass
get_user_from_db = MagicMock(
return_value={
"id": 1,
"name": "John Doe"
}
)
user = get_user_from_db(1)
print(user)
Output:
{'id': 1, 'name': 'John Doe'}---
How It Works
MagicMock(return_value=...)
Creates a fake version of the function.
Whenever the function is called, it immediately returns the specified value instead of executing the original code.
---
Why use
MagicMock?✓ Makes tests run much faster
✓ No need for a real database or API
✓ Produces predictable results
✓ Essential for professional unit testing
---
Challenge:
Create a
MagicMock that simulates a weather API and returns:{
"city": "Addis Ababa",
"temperature": 22,
"condition": "Sunny"
}Then print the returned dictionary.
Python coding
🐍 Python Tip #12: The pathlib Module Working with files and folders is a common task in Python. Instead of using traditional string paths, Python provides the pathlib module, which offers a cleaner and more object-oriented approach. --- Importing Path…
If there is any questions lemme know in the discussion group
Python coding
🧪 Python Tip #13: Using MagicMock for Testing When writing unit tests, you don't always want to call real databases, APIs, or external services. Instead, you can use MagicMock from Python's unittest.mock module to simulate their behavior. --- Importing…
⚡ Python Tip #14: The Walrus Operator (
Introduced in Python 3.8, the walrus operator allows you to assign a value to a variable as part of an expression.
This can make your code shorter and avoid repeating calculations.
---
Without the Walrus Operator
---
With the Walrus Operator
The program behaves exactly the same but requires fewer lines of code.
---
Another Example
Without the walrus operator:
---
With the walrus operator:
---
When Should You Use It?
The walrus operator is useful when:
- A value is needed more than once
- You want to avoid repeating a function call
- You want cleaner and more efficient code
However, don't overuse it. Sometimes a normal assignment is easier to read.
---
Why use the Walrus Operator?
✓ Reduces repeated calculations
✓ Makes some loops cleaner
✓ Can improve performance in certain situations
✓ Useful in data processing and file handling
---
Challenge:
Using the walrus operator, write a program that repeatedly asks the user to enter a number until they type:
Print each number entered before the program exits.
:=)Introduced in Python 3.8, the walrus operator allows you to assign a value to a variable as part of an expression.
This can make your code shorter and avoid repeating calculations.
---
Without the Walrus Operator
name = input("Enter your name: ")
while name != "exit":
print(f"Hello, {name}!")
name = input("Enter your name: ")---
With the Walrus Operator
while (name := input("Enter your name: ")) != "exit":
print(f"Hello, {name}!")The program behaves exactly the same but requires fewer lines of code.
---
Another Example
Without the walrus operator:
numbers = [5, 8, 12, 20]
length = len(numbers)
if length > 3:
print(f"The list contains {length} items.")
---
With the walrus operator:
numbers = [5, 8, 12, 20]
if (length := len(numbers)) > 3:
print(f"The list contains {length} items.")
---
When Should You Use It?
The walrus operator is useful when:
- A value is needed more than once
- You want to avoid repeating a function call
- You want cleaner and more efficient code
However, don't overuse it. Sometimes a normal assignment is easier to read.
---
Why use the Walrus Operator?
✓ Reduces repeated calculations
✓ Makes some loops cleaner
✓ Can improve performance in certain situations
✓ Useful in data processing and file handling
---
Challenge:
Using the walrus operator, write a program that repeatedly asks the user to enter a number until they type:
quit
Print each number entered before the program exits.
Python coding
⚡ Python Tip #14: The Walrus Operator (:=) Introduced in Python 3.8, the walrus operator allows you to assign a value to a variable as part of an expression. This can make your code shorter and avoid repeating calculations. --- Without the Walrus Operator…
💡 Python Tip #15: The
Many beginners confuse
---
Using
The
Example:
Output:
Both lists contain the same values.
---
Using
The
Example:
Output:
Although the values are equal, they are stored as different objects.
---
Same Object Example
Output:
Both variables point to the same object.
---
Checking for
The recommended way to check for
Correct:
Avoid:
Using `is None
x = [10, 20]
y = x
z = [10, 20]
print(x == z)
print(x is z)
print(x is y)
Try to predict the output before running the code.
is vs == OperatorsMany beginners confuse
is and ==, but they have different purposes.---
Using
==The
== operator checks whether two values are equal.Example:
a = [1, 2, 3]
b = [1, 2, 3]
print(a == b)
Output:
True
Both lists contain the same values.
---
Using
isThe
is operator checks whether two variables refer to the exact same object in memory.Example:
a = [1, 2, 3]
b = [1, 2, 3]
print(a is b)
Output:
False
Although the values are equal, they are stored as different objects.
---
Same Object Example
a = [1, 2, 3]
b = a
print(a is b)
print(a == b)
Output:
True
True
Both variables point to the same object.
---
Checking for
NoneThe recommended way to check for
None is with is.Correct:
name = None
if name is None:
print("No name provided")
Avoid:
if name == None:
print("No name provided")
Using `is None
is the Pythonic approach.
---
Why does this matter?
✓ Prevents subtle bugs
✓ Improves code readability
✓ Follows Python best practices
✓ Commonly used in professional Python projects
---
Challenge:
What will this code print?
``pythonx = [10, 20]
y = x
z = [10, 20]
print(x == z)
print(x is z)
print(x is y)
`Try to predict the output before running the code.
Python coding
💡 Python Tip #15: The is vs == Operators Many beginners confuse is and ==, but they have different purposes. --- Using == The == operator checks whether two values are equal. Example: a = [1, 2, 3] b = [1, 2, 3] print(a == b) Output: True Both lists…
🔥 Python Tip #16: The
When working with files, it's important to close them after you're done.
Python's
---
Without
If an error occurs before
---
With
Once the block ends, Python automatically closes the file.
---
Writing to a File
This creates the file if it doesn't exist, or overwrites it if it does.
---
Appending to a File
Use
---
Why use the
✓ Automatically closes files
✓ Prevents resource leaks
✓ Cleaner and more readable code
✓ Recommended for all file operations
---
Challenge:
Create a program that:
1. Creates a file named:
2. Writes three tasks into the file.
3. Opens the same file and prints all its contents using the
with StatementWhen working with files, it's important to close them after you're done.
Python's
with statement automatically handles this for you.---
Without
withfile = open("notes.txt", "r")
content = file.read()
print(content)
file.close()If an error occurs before
file.close(), the file may remain open.---
With
withwith open("notes.txt", "r") as file:
content = file.read()
print(content)Once the block ends, Python automatically closes the file.
---
Writing to a File
with open("hello.txt", "w") as file:
file.write("Hello, Python!")This creates the file if it doesn't exist, or overwrites it if it does.
---
Appending to a File
Use
"a" mode to add new content without deleting the existing content.with open("hello.txt", "a") as file:
file.write("\nWelcome back!")---
Why use the
with statement?✓ Automatically closes files
✓ Prevents resource leaks
✓ Cleaner and more readable code
✓ Recommended for all file operations
---
Challenge:
Create a program that:
1. Creates a file named:
tasks.txt
2. Writes three tasks into the file.
3. Opens the same file and prints all its contents using the
with statement.
Python coding
🔥 Python Tip #16: The with Statement When working with files, it's important to close them after you're done. Python's with statement automatically handles this for you. --- Without with file = open("notes.txt", "r") content = file.read() print(content)…
🎯 Python Tip #17: The
Introduced in Python 3.10, the
It is similar to the "switch" statement found in many other programming languages.
---
Without
---
With
Output:
---
Matching Strings
---
The Wildcard
The underscore (
Example:
It is equivalent to the
---
Why use
✓ Cleaner than multiple
✓ Easier to read and maintain
✓ Perfect for menus and command handling
✓ Great for pattern matching in modern Python
> Note:
---
Challenge:
Write a program that asks the user to enter one of these commands:
Use `match-case
Invalid command
match-case StatementIntroduced in Python 3.10, the
match-case statement provides a cleaner alternative to long chains of if...elif...else.It is similar to the "switch" statement found in many other programming languages.
---
Without
match-caseday = 3
if day == 1:
print("Monday")
elif day == 2:
print("Tuesday")
elif day == 3:
print("Wednesday")
else:
print("Invalid day")
---
With
match-caseday = 3
match day:
case 1:
print("Monday")
case 2:
print("Tuesday")
case 3:
print("Wednesday")
case _:
print("Invalid day")
Output:
Wednesday
---
Matching Strings
command = "start"
match command:
case "start":
print("Program started")
case "stop":
print("Program stopped")
case "restart":
print("Program restarted")
case _:
print("Unknown command")
---
The Wildcard
_The underscore (
_) acts as the default case.Example:
case _:
print("No match found")
It is equivalent to the
else statement.---
Why use
match-case?✓ Cleaner than multiple
if...elif statements ✓ Easier to read and maintain
✓ Perfect for menus and command handling
✓ Great for pattern matching in modern Python
> Note:
match-case is available only in Python 3.10 and later.---
Challenge:
Write a program that asks the user to enter one of these commands:
add
remove
update
list
Use `match-case
to print the corresponding action. If the command is not recognized, print:
``textInvalid command
`