Python coding
Basic_Python_Intro_Notes.pdf
Introduction to Programming with Python
---
What is Python?
Python is a popular programming language created by Guido van Rossum in 1991.
It is known for:
- Simplicity
- Readability
- Flexibility
- Powerful libraries
Python is beginner-friendly while still being powerful enough for AI, web development, and automation.
---
What is Python Used For?
- Web Development
- Software Development
- Data Science & Mathematics
- Automation & System Scripting
Python works on multiple platforms:
- Windows
- Linux
- Mac
- Raspberry Pi
---
Important Concept: Indentation
Unlike many programming languages that use
Example:
Proper indentation is required in Python.
---
Your First Python Program
This prints text to the screen.
---
Reading User Input
Use the
---
Variables in Python
Variables are containers used to store data.
Python automatically detects the data type.
---
Casting
Casting is used to force a variable into a specific data type.
---
Variable Naming Rules
- Must start with a letter or underscore
- Cannot start with a number
- Can contain letters, numbers, and underscores
- Case-sensitive (
- Cannot use Python keywords like:
- if
- while
- print
---
Naming Conventions
Camel Case:
Pascal Case:
Snake Case (Recommended in Python):
---
Built-in Data Types
Python includes several built-in data types:
- Text →
- Numeric →
- Sequence →
- Mapping →
- Boolean →
Check a variable type using
Output:
---
Comments in Python
Comments make code easier to understand.
Single-line comment:
Multi-line comment:
---
What is Python?
Python is a popular programming language created by Guido van Rossum in 1991.
It is known for:
- Simplicity
- Readability
- Flexibility
- Powerful libraries
Python is beginner-friendly while still being powerful enough for AI, web development, and automation.
---
What is Python Used For?
- Web Development
- Software Development
- Data Science & Mathematics
- Automation & System Scripting
Python works on multiple platforms:
- Windows
- Linux
- Mac
- Raspberry Pi
---
Important Concept: Indentation
Unlike many programming languages that use
{ }, Python uses indentation (spaces) to define code blocks.Example:
if 5 > 2:
print("Five is greater than two")
Proper indentation is required in Python.
---
Your First Python Program
print("Hello World")This prints text to the screen.
---
Reading User Input
Use the
input() function to get data from users.name = input("Please enter your name: ")
print(f"Hi {name}, nice to meet you!")---
Variables in Python
Variables are containers used to store data.
x = 5
y = "John"
Python automatically detects the data type.
---
Casting
Casting is used to force a variable into a specific data type.
str(3) # '3'
int(3.8) # 3
float(3) # 3.0
---
Variable Naming Rules
- Must start with a letter or underscore
_- Cannot start with a number
- Can contain letters, numbers, and underscores
- Case-sensitive (
age, Age, and AGE are different)- Cannot use Python keywords like:
- if
- while
---
Naming Conventions
Camel Case:
myVariableName
Pascal Case:
MyVariableName
Snake Case (Recommended in Python):
my_variable_name
---
Built-in Data Types
Python includes several built-in data types:
- Text →
str- Numeric →
int, float, complex- Sequence →
list, tuple, range- Mapping →
dict- Boolean →
boolCheck a variable type using
type():print(type(5))
Output:
<class 'int'>
---
Comments in Python
Comments make code easier to understand.
Single-line comment:
# This is a comment
Multi-line comment:
"""
This is a multi-line comment
"""
Python coding
Basic_Python_Control_Structures.pdf
Control Structures and Loops in Python
---
Conditional Statements
Conditional statements allow programs to make decisions based on conditions.
They help control the flow of a program by executing different code depending on whether a condition is True or False.
---
Comparison Operators
| Operator | Meaning |
|----------|----------|
| == | Equal to |
| != | Not equal to |
| < | Less than |
| <= | Less than or equal to |
| > | Greater than |
| >= | Greater than or equal to |
---
If, Elif, and Else
-
-
-
Example:
---
Logical Operators
Logical operators combine multiple conditions.
---
AND Operator
Returns True only if both conditions are True.
---
OR Operator
Returns True if at least one condition is True.
---
NOT Operator
Reverses the result.
---
Loops in Python
Loops repeat code multiple times while a condition is met.
Python mainly uses:
- while loop
- for loop
---
The While Loop
Executes repeatedly while the condition remains True.
Important:
Always update the loop variable to avoid infinite loops.
---
Break Statement
Stops the loop immediately.
---
Continue Statement
Skips the current iteration and continues with the next one.
---
Else with Loops
The
---
The For Loop
A
- Lists
- Tuples
- Strings
Example:
---
Practice Exercises
1. Write a program to check whether a number is positive, negative, or zero.
2. Print all even numbers from 1 to 20 using a loop.
3. Create a loop that stops when the number 5 is reached.
4. Loop through a string and print each character separately.
---
Conditional Statements
Conditional statements allow programs to make decisions based on conditions.
They help control the flow of a program by executing different code depending on whether a condition is True or False.
---
Comparison Operators
| Operator | Meaning |
|----------|----------|
| == | Equal to |
| != | Not equal to |
| < | Less than |
| <= | Less than or equal to |
| > | Greater than |
| >= | Greater than or equal to |
---
If, Elif, and Else
-
if → checks the first condition -
elif → checks another condition if previous ones are False -
else → runs if none of the conditions are True Example:
a = 200
b = 33
if b > a:
print("b is greater than a")
elif a == b:
print("a and b are equal")
else:
print("a is greater than b")
---
Logical Operators
Logical operators combine multiple conditions.
---
AND Operator
Returns True only if both conditions are True.
a = 200
b = 33
c = 500
if a > b and c > a:
print("Both conditions are satisfied")
---
OR Operator
Returns True if at least one condition is True.
if a > b or a > c:
print("At least one condition is True")
---
NOT Operator
Reverses the result.
a = 33
b = 200
if not a > b:
print("a is NOT greater than b")
---
Loops in Python
Loops repeat code multiple times while a condition is met.
Python mainly uses:
- while loop
- for loop
---
The While Loop
Executes repeatedly while the condition remains True.
i = 1
while i < 6:
print(i)
i += 1
Important:
Always update the loop variable to avoid infinite loops.
---
Break Statement
Stops the loop immediately.
i = 1
while i < 6:
print(i)
if i == 3:
break
i += 1
---
Continue Statement
Skips the current iteration and continues with the next one.
i = 0
while i < 6:
i += 1
if i == 3:
continue
print(i)
---
Else with Loops
The
else block runs once when the loop condition becomes False.i = 1
while i < 6:
print(i)
i += 1
else:
print("Loop finished")
---
The For Loop
A
for loop is used to iterate through sequences such as:- Lists
- Tuples
- Strings
Example:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
---
Practice Exercises
1. Write a program to check whether a number is positive, negative, or zero.
2. Print all even numbers from 1 to 20 using a loop.
3. Create a loop that stops when the number 5 is reached.
4. Loop through a string and print each character separately.
Python coding
Basic_Python_Functions_Recursion.pdf
Functions and Recursion in Python
---
Working with Functions
A function is a reusable block of code that runs only when it is called.
Functions help:
- Organize code
- Avoid repetition
- Make programs easier to manage
---
Default Parameter Values
A function can use a default value if no argument is provided.
Output:
---
Passing Sequences as Arguments
Functions can receive lists, tuples, dictionaries, and other data types.
---
Return Values
Use the
Output:
---
Recursion
Recursion is when a function calls itself.
It is useful for:
- Mathematical problems
- Repeated calculations
- Breaking problems into smaller parts
---
Important Note
Recursive functions must have a stopping condition (base case).
Without it, the function may run forever and crash the program.
---
Recursion Example
This function adds numbers from 6 down to 0.
---
Lambda Functions
A lambda function is a small anonymous function.
Syntax:
Example:
Output:
---
Why Use Lambda Functions?
Useful for:
- Short operations
- One-line functions
- Functional programming techniques
---
Practice Exercises
1. Create a Fibonacci sequence program.
The sequence starts with:
0, 1, 1, 2, 3, 5, 8...
Each number equals the sum of the previous two numbers.
---
2. Write a function that accepts a positive integer and calculates the sum of all numbers down to 0.
Example:
---
Working with Functions
A function is a reusable block of code that runs only when it is called.
Functions help:
- Organize code
- Avoid repetition
- Make programs easier to manage
---
Default Parameter Values
A function can use a default value if no argument is provided.
def my_function(country="Norway"):
print("I am from " + country)
my_function("Sweden")
my_function()
Output:
I am from Sweden
I am from Norway
---
Passing Sequences as Arguments
Functions can receive lists, tuples, dictionaries, and other data types.
def my_list_function(food):
for x in food:
print(x)
fruits = ["apple", "banana", "cherry"]
my_list_function(fruits)
---
Return Values
Use the
return statement to send data back from a function.def multiply_by_five(x):
return 5 * x
result = multiply_by_five(3)
print(result)
Output:
15
---
Recursion
Recursion is when a function calls itself.
It is useful for:
- Mathematical problems
- Repeated calculations
- Breaking problems into smaller parts
---
Important Note
Recursive functions must have a stopping condition (base case).
Without it, the function may run forever and crash the program.
---
Recursion Example
def tri_recursion(k):
if k > 0:
result = k + tri_recursion(k - 1)
return result
else:
return 0
print(tri_recursion(6))
This function adds numbers from 6 down to 0.
---
Lambda Functions
A lambda function is a small anonymous function.
Syntax:
lambda arguments : expression
Example:
x = lambda a, b: a * b
print(x(5, 6))
Output:
30
---
Why Use Lambda Functions?
Useful for:
- Short operations
- One-line functions
- Functional programming techniques
---
Practice Exercises
1. Create a Fibonacci sequence program.
The sequence starts with:
0, 1, 1, 2, 3, 5, 8...
Each number equals the sum of the previous two numbers.
---
2. Write a function that accepts a positive integer and calculates the sum of all numbers down to 0.
Example:
Input: 5
Output: 15
❤1
Python coding
Basic_Python_Data_Structures_Lists.pdf
Data Structures: Lists in Python
---
Introduction to Lists
Lists are used to store multiple items in a single variable.
They are one of the main built-in collection data types in Python.
---
Key Characteristics of Lists
- Ordered → Items keep their position
- Changeable → Items can be modified
- Allow Duplicates → Same value can appear multiple times
---
Creating a List
---
Accessing List Items
Lists use indexes.
Output:
---
List Indexing
- Positive indexes start from the beginning
- Negative indexes start from the end
---
Negative Indexing
Output:
---
Range of Indexes
The start index is included, but the end index is excluded.
Output:
---
Changing List Items
Use the index number to modify an item.
---
List Length
Use
---
Essential List Methods
---
append()
Adds an item to the end.
---
insert()
Adds an item at a specific position.
---
remove()
Removes a specific item.
---
pop()
Removes the last item.
---
Membership Test
Use
---
Practice Exercises
1. Create a list of 5 favorite movies and print the third item.
2. Replace the second item in a list with a new value.
3. Add two new items to a list using:
- append()
- insert()
4. Check if
---
Introduction to Lists
Lists are used to store multiple items in a single variable.
They are one of the main built-in collection data types in Python.
---
Key Characteristics of Lists
- Ordered → Items keep their position
- Changeable → Items can be modified
- Allow Duplicates → Same value can appear multiple times
---
Creating a List
thislist = ["apple", "banana", "cherry"]
print(thislist)
---
Accessing List Items
Lists use indexes.
thislist = ["apple", "banana", "cherry"]
print(thislist[0])
print(thislist[1])
Output:
apple
banana
---
List Indexing
"apple" "banana" "cherry"
0 1 2
-3 -2 -1
- Positive indexes start from the beginning
- Negative indexes start from the end
---
Negative Indexing
thislist = ["apple", "banana", "cherry"]
print(thislist[-1])
Output:
cherry
---
Range of Indexes
The start index is included, but the end index is excluded.
thislist = ["apple", "banana", "cherry", "orange", "kiwi"]
print(thislist[2:4])
Output:
['cherry', 'orange']
---
Changing List Items
Use the index number to modify an item.
thislist = ["apple", "banana", "cherry"]
thislist[1] = "blackcurrant"
print(thislist)
---
List Length
Use
len() to count items.print(len(thislist))
---
Essential List Methods
---
append()
Adds an item to the end.
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits)
---
insert()
Adds an item at a specific position.
fruits.insert(1, "cherry")
print(fruits)
---
remove()
Removes a specific item.
fruits.remove("banana")
print(fruits)---
pop()
Removes the last item.
fruits.pop()
print(fruits)
---
Membership Test
Use
in to check if an item exists.if "apple" in fruits:
print("Yes, it is in the list!")
---
Practice Exercises
1. Create a list of 5 favorite movies and print the third item.
2. Replace the second item in a list with a new value.
3. Add two new items to a list using:
- append()
- insert()
4. Check if
"banana" exists in a list.
Python coding
Basic_Python_Advanced_Lists.pdf
Advanced List Operations in Python
---
Adding List Items
Python provides multiple ways to add items to a list.
---
append()
Adds an item to the end of the list.
Output:
---
insert()
Adds an item at a specific index.
---
extend()
Adds elements from another iterable.
---
Removing List Items
Python provides different methods for removing items.
---
remove()
Removes the first matching value.
---
pop()
Removes an item by index.
Without an index,
---
del Keyword
Delete a specific item:
Delete the entire list:
---
clear()
Removes all items but keeps the list object.
---
List Comprehension
A shorter and cleaner way to create lists.
Traditional way:
List comprehension way:
---
Sorting Lists
Sort alphabetically:
Reverse sorting:
---
Important Note
Sorting is case-sensitive.
Capital letters come before lowercase letters.
---
Copying Lists
Wrong way:
This only creates a reference.
---
Correct Ways to Copy
Using
Using `list()
another_copy = list(fruits)
python
list1 = ["a", "b"]
list2 = [1, 2]
list3 = list1 + list2
print(list3)
python
for x in list2:
list1.append(x)
print(list1)
---
Practice Exercises
1. Use list comprehension to convert all items in a list to uppercase.
2. Sort a list based on how close numbers are to 50.
3. Reverse a list using `.reverse()`.
---
Adding List Items
Python provides multiple ways to add items to a list.
---
append()
Adds an item to the end of the list.
fruits = ["apple", "banana"]
fruits.append("orange")
print(fruits)
Output:
['apple', 'banana', 'orange']
---
insert()
Adds an item at a specific index.
fruits = ["apple", "banana"]
fruits.insert(1, "cherry")
print(fruits)
---
extend()
Adds elements from another iterable.
fruits = ["apple", "banana"]
tropical = ["mango", "pineapple"]
fruits.extend(tropical)
print(fruits)
---
Removing List Items
Python provides different methods for removing items.
---
remove()
Removes the first matching value.
fruits = ["apple", "banana", "banana"]
fruits.remove("banana")
print(fruits)
---
pop()
Removes an item by index.
fruits = ["apple", "banana", "cherry"]
fruits.pop(1)
print(fruits)
Without an index,
pop() removes the last item.---
del Keyword
Delete a specific item:
fruits = ["apple", "banana", "cherry"]
del fruits[0]
print(fruits)
Delete the entire list:
del fruits
---
clear()
Removes all items but keeps the list object.
fruits = ["apple", "banana", "cherry"]
fruits.clear()
print(fruits)
---
List Comprehension
A shorter and cleaner way to create lists.
Traditional way:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = []
for x in fruits:
if "a" in x:
newlist.append(x)
print(newlist)
List comprehension way:
fruits = ["apple", "banana", "cherry", "kiwi", "mango"]
newlist = [x for x in fruits if "a" in x]
print(newlist)
---
Sorting Lists
Sort alphabetically:
fruits = ["orange", "mango", "kiwi", "banana"]
fruits.sort()
print(fruits)
Reverse sorting:
fruits.sort(reverse=True)
print(fruits)
---
Important Note
Sorting is case-sensitive.
Capital letters come before lowercase letters.
---
Copying Lists
Wrong way:
list2 = list1
This only creates a reference.
---
Correct Ways to Copy
Using
.copy():new_copy = fruits.copy()
Using `list()
:
``pythonanother_copy = list(fruits)
---
Joining Two Lists
Using `+` operator:
python
list1 = ["a", "b"]
list2 = [1, 2]
list3 = list1 + list2
print(list3)
Using a loop:
python
for x in list2:
list1.append(x)
print(list1)
`---
Practice Exercises
1. Use list comprehension to convert all items in a list to uppercase.
2. Sort a list based on how close numbers are to 50.
3. Reverse a list using `.reverse()`.
Python coding
Basic_Python_Tuples.pdf
Basic Python Course
Data Structures: Tuples
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Introduction to Tuples
Tuples are used to store multiple items in a single variable.
They are one of the 4 built-in collection data types in Python.
---
Characteristics of Tuples
- Ordered → Items keep their position
- Unchangeable (Immutable) → Items cannot be modified after creation
- Allow Duplicates → Multiple items can have the same value
---
Creating a Tuple
---
One-Item Tuple Trick
To create a tuple with only one item, you must include a comma.
Correct:
Wrong:
Without the comma, Python treats it as a string.
---
2. Updating Tuples (The Workaround)
Tuples are immutable, meaning they cannot be changed directly.
However, there is a common workaround:
1. Convert tuple to list
2. Modify the list
3. Convert back to tuple
Example:
---
3. Unpacking Tuples
Packing means storing values into a tuple.
Unpacking means extracting tuple values into variables.
Output:
---
Using the Asterisk (*)
If variables are fewer than values, use
Output:
---
4. Join and Multiply Tuples
Join Tuples
Use
---
Multiply Tuples
Use
Output:
---
5. Why Use Tuples?
You may ask:
Why use tuples if lists already exist?
Here are two important reasons:
---
Performance
Tuples are slightly faster than lists because they are immutable.
---
Data Safety
Tuples protect data from accidental modification.
Useful for:
- Coordinates
- Days of the week
- Months of the year
- Fixed configuration data
---
Practice Exercises
1. Reverse this tuple:
2. Check if
3. Use
Data Structures: Tuples
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Introduction to Tuples
Tuples are used to store multiple items in a single variable.
They are one of the 4 built-in collection data types in Python.
---
Characteristics of Tuples
- Ordered → Items keep their position
- Unchangeable (Immutable) → Items cannot be modified after creation
- Allow Duplicates → Multiple items can have the same value
---
Creating a Tuple
thistuple = ("apple", "banana", "cherry")
print(thistuple)---
One-Item Tuple Trick
To create a tuple with only one item, you must include a comma.
Correct:
thistuple = ("apple",)Wrong:
thistuple = ("apple")Without the comma, Python treats it as a string.
---
2. Updating Tuples (The Workaround)
Tuples are immutable, meaning they cannot be changed directly.
However, there is a common workaround:
1. Convert tuple to list
2. Modify the list
3. Convert back to tuple
Example:
x = ("apple", "banana", "cherry")
y = list(x) # Convert to list
y[1] = "kiwi" # Modify the list
x = tuple(y) # Convert back to tuple
print(x)---
3. Unpacking Tuples
Packing means storing values into a tuple.
Unpacking means extracting tuple values into variables.
fruits = ("apple", "banana", "cherry")
(green, yellow, red) = fruits
print(green)Output:
apple
---
Using the Asterisk (*)
If variables are fewer than values, use
* to collect the remaining values.fruits = ("apple", "banana", "cherry", "orange")
(green, yellow, *others) = fruits
print(others)Output:
['cherry', 'orange']
---
4. Join and Multiply Tuples
Join Tuples
Use
+ to combine tuples.tuple1 = ("a", "b")
tuple2 = (1, 2)
tuple3 = tuple1 + tuple2
print(tuple3)---
Multiply Tuples
Use
* to repeat tuple content.fruits = ("apple", "banana")
print(fruits * 2)Output:
('apple', 'banana', 'apple', 'banana')---
5. Why Use Tuples?
You may ask:
Why use tuples if lists already exist?
Here are two important reasons:
---
Performance
Tuples are slightly faster than lists because they are immutable.
---
Data Safety
Tuples protect data from accidental modification.
Useful for:
- Coordinates
- Days of the week
- Months of the year
- Fixed configuration data
---
Practice Exercises
1. Reverse this tuple:
mytuple = ("apple", "banana", "cherry")2. Check if
"banana" exists inside the tuple using in.3. Use
.count() to count how many times a value appears in a tuple.
Python coding
Basic_Python_Sets.pdf
Basic Python Course
Data Structures: Sets
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Understanding Sets
Sets are used to store multiple items in a single variable.
They are written using curly brackets
---
Characteristics of Sets
- Unordered → Items do not have a fixed order
- Unchangeable → Items themselves cannot be modified directly
- Unindexed → No index numbers like lists
- No Duplicates → Duplicate values are automatically removed
---
Example
Output:
Notice:
---
2. Modifying a Set
Adding One Item
Use
---
Adding Multiple Items
Use
---
Removing Items
Using
Important:
---
Using
Difference:
---
3. Set Operations (Logic)
Sets are powerful because they support mathematical operations.
---
Union (Combine All Items)
Method:
Operator:
Example:
---
Intersection (Common Items Only)
Method:
Operator:
---
Difference (Items in Set1 but NOT in Set2)
Method:
Operator:
---
Symmetric Difference
Keeps items that exist in either set, but NOT both.
Method:
Operator:
---
Boolean Note
In Python sets:
So these are treated as duplicate values.
Example:
Output:
---
4. Why Use Sets?
Removing Duplicates Instantly
Sets are perfect for cleaning repeated data.
Example:
Output:
---
Practice Exercises
1. Disjoint Check
Write a program to check if two sets have no common items without using built-in functions.
---
2. Unique Counter
Given a list of student names, count the number of unique names.
---
3. Symmetric Difference
Use the
Data Structures: Sets
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Understanding Sets
Sets are used to store multiple items in a single variable.
They are written using curly brackets
{}.---
Characteristics of Sets
- Unordered → Items do not have a fixed order
- Unchangeable → Items themselves cannot be modified directly
- Unindexed → No index numbers like lists
- No Duplicates → Duplicate values are automatically removed
---
Example
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)Output:
{'apple', 'banana', 'cherry'}Notice:
"apple" appears only once.---
2. Modifying a Set
Adding One Item
Use
.add():thisset = {"apple", "banana", "cherry"}
thisset.add("orange")
print(thisset)---
Adding Multiple Items
Use
.update():thisset.update(["mango", "kiwi"])
print(thisset)
---
Removing Items
Using
remove():thisset.remove("banana")Important:
remove() raises an error if the item does not exist.---
Using
discard()thisset.discard("banana")Difference:
discard() does NOT raise an error if the item is missing.---
3. Set Operations (Logic)
Sets are powerful because they support mathematical operations.
---
Union (Combine All Items)
Method:
set1.union(set2)
Operator:
set1 | set2
Example:
set1 = {"a", "b"}
set2 = {1, 2}
print(set1 | set2)---
Intersection (Common Items Only)
Method:
set1.intersection(set2)
Operator:
set1 & set2
---
Difference (Items in Set1 but NOT in Set2)
Method:
set1.difference(set2)
Operator:
set1 - set2
---
Symmetric Difference
Keeps items that exist in either set, but NOT both.
Method:
set1.symmetric_difference(set2)
Operator:
set1 ^ set2
---
Boolean Note
In Python sets:
True == 1
False == 0
So these are treated as duplicate values.
Example:
myset = {True, 1, False, 0}
print(myset)Output:
{False, True}---
4. Why Use Sets?
Removing Duplicates Instantly
Sets are perfect for cleaning repeated data.
Example:
names = ["Ali", "Sara", "Ali", "Hana", "Sara"]
unique_names = set(names)
print(unique_names)
Output:
{'Ali', 'Sara', 'Hana'}---
Practice Exercises
1. Disjoint Check
Write a program to check if two sets have no common items without using built-in functions.
---
2. Unique Counter
Given a list of student names, count the number of unique names.
---
3. Symmetric Difference
Use the
^ operator to find items that exist in either Set A or Set B, but not both.
Python coding
Basic_Python_Sets.pdf
Basic Python Course
Data Structures: Sets
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Understanding Sets
A Set is a collection used to store multiple unique items in a single variable.
Sets are written using curly brackets
Example:
---
Characteristics of Sets
- Unordered → Items do not keep a fixed order
- Unindexed → No index numbers
- No Duplicates → Repeated values are automatically removed
- Mutable → You can add or remove items
---
Duplicate Values are Ignored
Output:
Even though
---
2. Modifying a Set
Adding One Item
Use
---
Adding Multiple Items
Use
---
Removing Items
Using
Important:
If the item does not exist, Python raises an error.
---
Using
Difference:
---
3. Set Operations (Logic)
Sets support mathematical operations.
These operations are extremely useful in programming and data analysis.
---
Union
Combines all unique values from both sets.
Method:
Operator:
Example:
---
Intersection
Returns only common values.
Method:
Operator:
Example:
Output:
---
Difference
Returns values in the first set but not in the second set.
Method:
Operator:
---
Symmetric Difference
Returns values that are NOT shared between both sets.
Method:
Operator:
---
Boolean Note
In Python sets:
So Python treats them as duplicate values.
Example:
Output:
---
4. Why Use Sets?
Removing duplicates instantly.
Example:
Output:
---
Real-World Uses of Sets
- Removing duplicate usernames
- Finding common interests between users
- Comparing datasets
- Membership testing
---
Practice Exercises
1. Disjoint Check
Write a program to check if two sets have zero common items without using built-in functions.
---
2. Unique Counter
Given a list of student names, count how many unique names exist.
---
3. Symmetric Difference
Use the
Data Structures: Sets
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Understanding Sets
A Set is a collection used to store multiple unique items in a single variable.
Sets are written using curly brackets
{}.Example:
thisset = {"apple", "banana", "cherry"}
print(thisset)---
Characteristics of Sets
- Unordered → Items do not keep a fixed order
- Unindexed → No index numbers
- No Duplicates → Repeated values are automatically removed
- Mutable → You can add or remove items
---
Duplicate Values are Ignored
thisset = {"apple", "banana", "cherry", "apple"}
print(thisset)Output:
{'apple', 'banana', 'cherry'}Even though
"apple" appears twice, it is stored only once.---
2. Modifying a Set
Adding One Item
Use
.add():thisset = {"apple", "banana"}
thisset.add("orange")
print(thisset)---
Adding Multiple Items
Use
.update():thisset.update(["mango", "kiwi"])
print(thisset)
---
Removing Items
Using
remove():thisset.remove("banana")Important:
If the item does not exist, Python raises an error.
---
Using
discard()thisset.discard("banana")Difference:
discard() does not raise an error if the item is missing.---
3. Set Operations (Logic)
Sets support mathematical operations.
These operations are extremely useful in programming and data analysis.
---
Union
Combines all unique values from both sets.
Method:
set1.union(set2)
Operator:
set1 | set2
Example:
set1 = {"a", "b"}
set2 = {1, 2}
print(set1 | set2)---
Intersection
Returns only common values.
Method:
set1.intersection(set2)
Operator:
set1 & set2
Example:
set1 = {"apple", "banana"}
set2 = {"banana", "orange"}
print(set1 & set2)Output:
{'banana'}---
Difference
Returns values in the first set but not in the second set.
Method:
set1.difference(set2)
Operator:
set1 - set2
---
Symmetric Difference
Returns values that are NOT shared between both sets.
Method:
set1.symmetric_difference(set2)
Operator:
set1 ^ set2
---
Boolean Note
In Python sets:
True == 1
False == 0
So Python treats them as duplicate values.
Example:
myset = {True, 1, False, 0}
print(myset)Output:
{False, True}---
4. Why Use Sets?
Removing duplicates instantly.
Example:
names = ["Ali", "Sara", "Ali", "Hana", "Sara"]
unique_names = set(names)
print(unique_names)
Output:
{'Ali', 'Sara', 'Hana'}---
Real-World Uses of Sets
- Removing duplicate usernames
- Finding common interests between users
- Comparing datasets
- Membership testing
---
Practice Exercises
1. Disjoint Check
Write a program to check if two sets have zero common items without using built-in functions.
---
2. Unique Counter
Given a list of student names, count how many unique names exist.
---
3. Symmetric Difference
Use the
^ operator to find items that exist in either Set A or Set B, but not both.
Python coding
Basic_Python_Dictionaries.pdf
Basic Python Course
Data Structures: Dictionaries
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Understanding Dictionaries
Dictionaries are used to store data in key:value pairs.
Think of a real dictionary:
- Word → Key
- Meaning → Value
Example:
Output:
---
Characteristics of Dictionaries
- Ordered → Python keeps the insertion order
- Changeable → Items can be updated or removed
- No Duplicate Keys → Duplicate keys overwrite old values
Example:
Output:
---
2. Managing Data
Accessing Items
Using square brackets:
Using `.get()
print(thisdict.get("year"))
python
thisdict["year"] = 2020
python
thisdict["color"] = "red"
python
print(thisdict)
python
for x in thisdict:
print(x)
python
for x in thisdict.values():
print(x)
python
for x, y in thisdict.items():
print(x, y)
python
myfamily = {
"child1": {
"name": "Emil",
"year": 2004
},
"child2": {
"name": "Tobias",
"year": 2007
}
}
python
print(myfamily["child2"]["name"])
python
Tobias
python
x = thisdict.keys()
thisdict["color"] = "white"
print(x)
python
thisdict.pop("model")
python
thisdict.clear()
python
thisdict.update({"color": "blue"})
python
if "model" in thisdict:
print("Yes, model exists")
Data Structures: Dictionaries
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Understanding Dictionaries
Dictionaries are used to store data in key:value pairs.
Think of a real dictionary:
- Word → Key
- Meaning → Value
Example:
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
print(thisdict["brand"])Output:
Ford
---
Characteristics of Dictionaries
- Ordered → Python keeps the insertion order
- Changeable → Items can be updated or removed
- No Duplicate Keys → Duplicate keys overwrite old values
Example:
thisdict = {
"brand": "Ford",
"brand": "BMW"
}
print(thisdict)Output:
{'brand': 'BMW'}---
2. Managing Data
Accessing Items
Using square brackets:
print(thisdict["model"])
Using `.get()
:
``pythonprint(thisdict.get("year"))
Difference:
`.get()` avoids errors if the key does not exist.
---
Changing and Adding Items
Update an existing value:
python
thisdict["year"] = 2020
Add a new key:value pair:
python
thisdict["color"] = "red"
Example:
python
print(thisdict)
---
3. Looping Through Dictionaries
Loop Through Keys
python
for x in thisdict:
print(x)
---
Loop Through Values
python
for x in thisdict.values():
print(x)
---
Loop Through Both Keys and Values
python
for x, y in thisdict.items():
print(x, y)
---
4. Nested Dictionaries
A dictionary can contain other dictionaries.
This is useful for:
- User profiles
- Databases
- Structured data
Example:
python
myfamily = {
"child1": {
"name": "Emil",
"year": 2004
},
"child2": {
"name": "Tobias",
"year": 2007
}
}
Access nested data:
python
print(myfamily["child2"]["name"])
Output:
python
Tobias
---
5. View Objects (Added Value)
The `.keys()` and `.values()` methods return dynamic view objects.
This means if the dictionary changes, the views update automatically.
Example:
python
x = thisdict.keys()
thisdict["color"] = "white"
print(x)
---
Dictionary Methods Summary
---
.pop(key)
Removes a specific item.
python
thisdict.pop("model")
---
.clear()
Removes all items.
python
thisdict.clear()
---
.update()
Updates the dictionary with another dictionary.
python
thisdict.update({"color": "blue"})
---
Real-World Uses of Dictionaries
- User account information
- Product databases
- API responses
- Student records
- Configuration settings
---
Practice Exercises
1. Inventory Update
Create a dictionary of store items and prices. Increase the price of one item by 10%.
---
2. Nested Access
From the `myfamily` dictionary, print only the name of `"child2"`.
---
3. Key Checker
Check if `"model"` exists inside `thisdict`.
Example:
python
if "model" in thisdict:
print("Yes, model exists")
`
Python coding
Basic_Python_NumPy_Libraries.pdf
Basic Python Course
Introduction to NumPy
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. What is NumPy?
NumPy stands for Numerical Python.
It is a powerful Python library used for:
- Numerical Computing
- Arrays and Matrices
- Scientific Calculations
- Data Analysis
- Artificial Intelligence and Machine Learning
NumPy is one of the most important libraries in the Python ecosystem.
---
Why NumPy is Important
Speed:
NumPy arrays are much faster than normal Python lists.
Memory Efficiency:
Arrays use less memory compared to standard Python lists.
Advanced Mathematics:
Supports matrix operations, statistics, linear algebra, and more.
Foundation of AI:
Libraries like Pandas, TensorFlow, and Scikit-learn rely heavily on NumPy.
---
2. Importing NumPy
Before using NumPy, it must be imported.
`np` is simply a shorter alias for NumPy.
---
3. Creating Arrays
Arrays are the core structure of NumPy.
Output:
---
4. Array Dimensions
NumPy supports multiple dimensions.
| Dimension | Description |
|-----------|-------------|
| 0-D | Single value |
| 1-D | Simple array |
| 2-D | Matrix/Table |
| 3-D | Collection of matrices |
---
2-D Array Example
---
Checking Dimensions
Use
Output:
---
5. Array Shape
The
Output:
Meaning:
- 2 rows
- 3 columns
---
6. Slicing Arrays
Slicing works similarly to Python lists.
Example:
Explanation:
- Row index → 0
- Column indexes → 1 to 2
Output:
---
7. Reshaping Arrays
Reshaping changes the structure without changing the data.
Output:
---
8. Searching Arrays
Use
Output:
Meaning:
The value
---
9. Vectorized Operations
NumPy can perform operations on entire arrays without loops.
Output:
Every element increases by 1 instantly.
---
10. Why NumPy is Powerful
Without NumPy:
With NumPy:
Cleaner, faster, and more efficient.
---
Real-World Uses of NumPy
- Artificial Intelligence
- Machine Learning
- Data Science
- Image Processing
- Scientific Research
- Game Development
---
Practice Exercises
1. Create a 5-D array using
2. Find indexes of all even numbers:
3. Convert a 1-D array with 8 elements into a 2x4 matrix using
Introduction to NumPy
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. What is NumPy?
NumPy stands for Numerical Python.
It is a powerful Python library used for:
- Numerical Computing
- Arrays and Matrices
- Scientific Calculations
- Data Analysis
- Artificial Intelligence and Machine Learning
NumPy is one of the most important libraries in the Python ecosystem.
---
Why NumPy is Important
Speed:
NumPy arrays are much faster than normal Python lists.
Memory Efficiency:
Arrays use less memory compared to standard Python lists.
Advanced Mathematics:
Supports matrix operations, statistics, linear algebra, and more.
Foundation of AI:
Libraries like Pandas, TensorFlow, and Scikit-learn rely heavily on NumPy.
---
2. Importing NumPy
Before using NumPy, it must be imported.
import numpy as np
`np` is simply a shorter alias for NumPy.
---
3. Creating Arrays
Arrays are the core structure of NumPy.
import numpy as np
arr = np.array([1, 2, 3, 4, 5])
print(arr)
Output:
[1 2 3 4 5]
---
4. Array Dimensions
NumPy supports multiple dimensions.
| Dimension | Description |
|-----------|-------------|
| 0-D | Single value |
| 1-D | Simple array |
| 2-D | Matrix/Table |
| 3-D | Collection of matrices |
---
2-D Array Example
arr2 = np.array([
[1, 2, 3],
[4, 5, 6]
])
print(arr2)
---
Checking Dimensions
Use
.ndim:print(arr2.ndim)
Output:
2
---
5. Array Shape
The
.shape attribute returns the size of each dimension.print(arr2.shape)
Output:
(2, 3)
Meaning:
- 2 rows
- 3 columns
---
6. Slicing Arrays
Slicing works similarly to Python lists.
Example:
print(arr2[0, 1:3])
Explanation:
- Row index → 0
- Column indexes → 1 to 2
Output:
[2 3]
---
7. Reshaping Arrays
Reshaping changes the structure without changing the data.
arr = np.array([1, 2, 3, 4, 5, 6, 7, 8])
newarr = arr.reshape(2, 4)
print(newarr)
Output:
[[1 2 3 4]
[5 6 7 8]]
---
8. Searching Arrays
Use
np.where() to find indexes.arr = np.array([1, 2, 3, 4, 5, 6])
x = np.where(arr == 4)
print(x)
Output:
(array([3]),)
Meaning:
The value
4 exists at index 3.---
9. Vectorized Operations
NumPy can perform operations on entire arrays without loops.
arr = np.array([1, 2, 3])
arr = arr + 1
print(arr)
Output:
[2 3 4]
Every element increases by 1 instantly.
---
10. Why NumPy is Powerful
Without NumPy:
numbers = [1, 2, 3]
new_numbers = []
for x in numbers:
new_numbers.append(x + 1)
print(new_numbers)
With NumPy:
arr = np.array([1, 2, 3])
print(arr + 1)
Cleaner, faster, and more efficient.
---
Real-World Uses of NumPy
- Artificial Intelligence
- Machine Learning
- Data Science
- Image Processing
- Scientific Research
- Game Development
---
Practice Exercises
1. Create a 5-D array using
ndmin.2. Find indexes of all even numbers:
arr = np.array([1, 2, 3, 4, 5, 6])
3. Convert a 1-D array with 8 elements into a 2x4 matrix using
.reshape().
Python coding
Basic_Python_NumPy_Part2.pdf
Basic Python Course
NumPy Part 2: Randomness & Math Functions
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Random Numbers in NumPy
In programming, random numbers are usually pseudo-random numbers.
This means:
- They are generated using algorithms
- They appear random
- But they are not truly random like natural randomness
NumPy provides powerful tools for generating random data.
Import random module:
---
Random Integers
Use
Output example:
This generates a random integer from:
- 0 → 99
---
Random Floats
Use
Example output:
---
Random Choice
Use
Possible output:
---
2. NumPy Arithmetic (Universal Functions)
NumPy uses Universal Functions (
These operations are:
- Faster than loops
- Cleaner to write
- Optimized internally
---
Example Arrays
---
Addition
Output:
---
Subtraction
---
Multiplication
---
Division
---
3. Rounding Decimal Numbers
NumPy provides multiple functions for handling decimals.
---
trunc() / fix()
Removes decimal values toward zero.
Output:
---
around()
Rounds to the nearest decimal place.
Output:
---
floor()
Rounds downward.
Output:
---
ceil()
Rounds upward.
Output:
---
4. Trigonometry and Logarithms
NumPy can perform advanced mathematics easily.
---
Sine Function
Output:
---
Logarithm Base 2
Output:
Explanation:
- log₂(1) = 0
- log₂(2) = 1
- log₂(4) = 2
- log₂(8) = 3
---
5. Data Distribution
In Machine Learning and AI, we often need data that follows a distribution.
One of the most common is the Normal Distribution (Bell Curve).
---
Normal Distribution Example
This generates:
- Random numbers
- Following a Gaussian distribution
- Inside a 2x3 matrix
---
Why Distributions Matter
Distributions are heavily used in:
- Artificial Intelligence
- Machine Learning
- Statistics
- Simulations
- Data Science
---
Practice Exercises
1. Random Choice
Create an array of 5 names and use
---
2. Ceiling & Floor
Create this array:
Print:
- Floor values
- Ceiling values
---
3. Random Matrix
Generate a 3x5 matrix of random integers between 0 and 50.
NumPy Part 2: Randomness & Math Functions
By Yehya Oumer
(Certificate from Mizan Institute of Technology)
Issued: 2026
---
1. Random Numbers in NumPy
In programming, random numbers are usually pseudo-random numbers.
This means:
- They are generated using algorithms
- They appear random
- But they are not truly random like natural randomness
NumPy provides powerful tools for generating random data.
Import random module:
from numpy import random
---
Random Integers
Use
randint() to generate random integers.from numpy import random
x = random.randint(100)
print(x)
Output example:
57
This generates a random integer from:
- 0 → 99
---
Random Floats
Use
rand() to generate random decimal values between 0 and 1.y = random.rand(5)
print(y)
Example output:
[0.24 0.81 0.55 0.91 0.13]
---
Random Choice
Use
choice() to randomly select values from an array.arr = [3, 5, 7, 9]
x = random.choice(arr)
print(x)
Possible output:
7
---
2. NumPy Arithmetic (Universal Functions)
NumPy uses Universal Functions (
ufuncs) to perform fast mathematical operations on arrays.These operations are:
- Faster than loops
- Cleaner to write
- Optimized internally
---
Example Arrays
import numpy as np
arr1 = np.array([10, 20, 30])
arr2 = np.array([3, 5, 7])
---
Addition
add_arr = np.add(arr1, arr2)
print(add_arr)
Output:
[13 25 37]
---
Subtraction
sub_arr = np.subtract(arr1, arr2)
print(sub_arr)
---
Multiplication
mult_arr = np.multiply(arr1, arr2)
print(mult_arr)
---
Division
div_arr = np.divide(arr1, arr2)
print(div_arr)
---
3. Rounding Decimal Numbers
NumPy provides multiple functions for handling decimals.
---
trunc() / fix()
Removes decimal values toward zero.
arr = np.trunc([-3.7, 3.7])
print(arr)
Output:
[-3. 3.]
---
around()
Rounds to the nearest decimal place.
arr = np.around(3.1666, 2)
print(arr)
Output:
3.17
---
floor()
Rounds downward.
arr = np.floor([3.7])
print(arr)
Output:
[3.]
---
ceil()
Rounds upward.
arr = np.ceil([3.2])
print(arr)
Output:
[4.]
---
4. Trigonometry and Logarithms
NumPy can perform advanced mathematics easily.
---
Sine Function
import numpy as np
val = np.sin(np.pi / 2)
print(val)
Output:
1.0
---
Logarithm Base 2
arr = np.array([1, 2, 4, 8])
print(np.log2(arr))
Output:
[0. 1. 2. 3.]
Explanation:
- log₂(1) = 0
- log₂(2) = 1
- log₂(4) = 2
- log₂(8) = 3
---
5. Data Distribution
In Machine Learning and AI, we often need data that follows a distribution.
One of the most common is the Normal Distribution (Bell Curve).
---
Normal Distribution Example
from numpy import random
x = random.normal(size=(2, 3))
print(x)
This generates:
- Random numbers
- Following a Gaussian distribution
- Inside a 2x3 matrix
---
Why Distributions Matter
Distributions are heavily used in:
- Artificial Intelligence
- Machine Learning
- Statistics
- Simulations
- Data Science
---
Practice Exercises
1. Random Choice
Create an array of 5 names and use
random.choice() to select a winner.---
2. Ceiling & Floor
Create this array:
arr = np.array([1.2, 2.8, 3.5])
Print:
- Floor values
- Ceiling values
---
3. Random Matrix
Generate a 3x5 matrix of random integers between 0 and 50.