Basic Python Traing Manual
Basic Python Traing Manual
1. Install Python:
With the virtual environment activated, you can install packages using conda install or pip
install.
For example, to install the pandas package, you can use: conda install pandas or pip install
pandas
You can write Python code in a basic text editor like Notepad (on Windows) or TextEdit (on
macOS). However, using a code editor or an Integrated Development Environment (IDE)
can enhance your development experience.
Some popular code editors and IDEs for Python include Visual Studio Code, PyCharm,
Sublime Text, and Jupyter Notebook (for data science). Download and install your preferred
editor or IDE.
Organize your work by creating a project folder for your Python files. This helps keep your
code and related files structured.
It's good practice to create virtual environments for your Python projects. Virtual
environments allow you to isolate project dependencies and prevent conflicts between
packages.
To create a virtual environment, open your terminal or command prompt and run:
1. Package Management
Python uses package managers like pip to install external libraries and packages. You can
install packages with the following commands:
pip install package_name to install a specific package.
1. Start Coding:
You're now ready to start coding in Python. Open your code editor or IDE, create a new
Python file (usually with a .py extension), and start writing your Python code.
To run your Python code, you can execute the Python file from the command line:
Hello world
In [4]: 5 + 3
Simple Calculations
In addition to all the more complex things you can do in Python, it is also useful for completing
simple mathematical operations.
In [ ]: 2 + 2
In [ ]: 4-3
Notice that you don't need to include = in order to make the operation work.
Division
In [5]: x = 3
y = 5
y % x
2
Out[5]:
In [6]: y // x
1
Out[6]:
In [8]: round(y/x, 2)
1.67
Out[8]:
In [9]: 4*2
8
Out[9]:
In [10]: 4**2
16
Out[10]:
In [ ]:
In [ ]: 11/2
In [ ]: 11//4
Modulo Division
In [ ]: 7%3
Multiplication
In [ ]: 6 * 2
In [ ]: 4**2
Order of Operations
Just like everywhere else, Python works on a specific order of operations. That order is:
If you remember being taught PEMDAS, then this is the same thing! All the operations in Python
work with levels of parentheses, so if you wanted to add two numbers together, and then add
another number to the result, the code would look like this:
In [12]: (((5**3 + 7) * 4) // 16 + 9 - 2)
40
Out[12]:
Printing
In [14]: message= '''this is the example
of something
in python training
'''
print(message)
6 + 4 = 10
1. Variable Declaration
You can create a variable by simply assigning a value to a name.
In [ ]: x= 10
name = "Kelemu D."
In [ ]: x = 3.4
print(type(x))
print('x = ',x)
In [28]: x = True
y = False
not y
True
Out[28]:
3. Variable Assignment
We can assign values of different data types to the same variable.
To assign the value to the variable use assignment operator "="
localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 5/50
3/15/24, 7:25 AM Basic Python Traing Manual
In [ ]: x = 10
cgpa = 6
name = 'Yassin'
In [ ]: x = 12
y= 4
y= x
print('x= ', x, "y=", y)
1. Numeric Types
1. String
str: A sequence of characters enclosed in single or double quotes, e.g., "Hello, World!" or
'Python'.
1. Boolean
1. Lists
list: Ordered, mutable (changeable) sequences of elements. Lists are created using square
brackets, e.g. [1, 2, 3].
1. Tuples
tuple: Ordered, immutable sequences of elements. Tuples are created using parentheses,
e.g., (1, 2, 3).
1. Dictionaries
dict: Unordered collections of key-value pairs. Dictionaries are created using curly braces
and key-value pairs, e.g. {'name': 'John', 'age': 30}.
1. Sets
set: Unordered collections of unique elements. Sets are created using curly braces or the
set() constructor, e.g., {1, 2, 3}.
1. None Type
1. Complex Numbers
complex: Represents complex numbers in the form a + bj, where a and b are real numbers
and j represents the imaginary unit.
1. Dictionaries
dict: Unordered collections of key-value pairs. Dictionaries are created using curly braces
and key-value pairs, e.g. {'name': 'John', 'age': 30}.
1. Sets
set: Unordered collections of unique elements. Sets are created using curly braces or the
set() constructor, e.g., {1, 2, 3}.
1. None Type
1. Complex Numbers
complex: Represents complex numbers in the form a + bj, where a and b are real numbers
and j represents the imaginary unit.
1. Arithmetic Operators:
Arithmetic operators are used for basic mathematical operations.
In [ ]: + # Addition
- # Subtraction
* # Multiplication
/ # Division (float result)
// # Floor Division (integer result)
% # Modulo (remainder)
** # Exponentiation
Example
In [ ]: x = 14
y = 6
addition = x + y
multiplication = x * y
subtraction = x - y
division = x % y
print(division)
2. Comparison Operators:
Comparison operators are used to compare values.
In [ ]: == # Equal to
!= # Not equal to
< # Less than
> # Greater than
<= # Less than or equal to
>= # Greater than or equal to
Example
In [ ]: a = 5
b = 7
is_equal = a != b
is_greater = a > b
is_less = a<b
print(type(is_equal))
3. Logical Operators:
Logical operators are used to combine or negate boolean values.
Example
In [ ]: is_true = 3>=2
is_false = 1<=9
result = is_true or is_false
print(result)
5. Bitwise Operators
Bitwise operators are used for operations at the bit level.
In [39]: x = 4
y = 2
In [40]: bin(x)
'0b100'
Out[40]:
In [41]: x | y
6
Out[41]:
In [42]: x>>y
1
Out[42]:
In [43]: x<<y
16
Out[43]:
In [46]: ~-4
3
Out[46]:
In [ ]: a = 4
b = 3
bin(b)
Example
In [ ]: a = 5 # Binary: 0101
b = 3 # Binary: 0011
result = a & b # Bitwise AND: 0001 (Decimal: 1)
res = a | b # Bitwise OR: 0111(Decimal:7)
xres = a ^ b # XOR operation # Output: 6 (Binary: 0110)
print(xres)
6. Membership Operators:
Membership operators are used to test if a value is present in a sequence.
True
Out[49]:
Example
7. Identity Operators:
Identity operators are used to compare the memory location of two objects.
In [52]: y = 3
x = 5
x is y
False
Out[52]:
1 - Kedir
2 - Aster
3 - Kedija
4 - Yoham
5 - Yohanis
2550
['Kedir', 'Kedija']
Out[66]:
In [69]: q = input("search...")
search_res = [name for name in names if name.lower().startswith(q.lower())]
for index, name in enumerate(search_res):
print(f'{index+1} - {name}')
Example
In [76]:
dict
Out[76]:
In [ ]: x = [1, 2, 3]
y = x # y references the same object as x
is_same = x is y # True
Python Output
In Python, we can simply use the print() function to print output. For example,
Parameters: * **value(s)**: Any value, and as many as you like. Will be converted to a string before
printed * **sep=’separator’** : (Optional) Specify how to separate the bjects, if there is more than
one.Default :’ ‘ * **end=’end’**: (Optional) Specify what to print at the end.Default : ‘\n’ * **file** :
(Optional) An object with a write method. Default :sys.stdout * **flush** : (Optional) A Boolean,
specifying if the output is flushed (True) or buffered (False). Default: False Return Type: It returns output
to the screen.
In [ ]: name = "Yohannes"
age = 25
In [ ]: print('Ethiopian New Year', 2016, 'Passed a month ago!', sep= '. ')
Output formatting
Sometimes we would like to format our output to make it look attractive. This can be done by
using the str.format() method. For example,
In [ ]: x = 5
y = 10
In [ ]: name = "Yassin"
age = 30
print(f"My name is {name} and I am {age} years old.")
Writing to Files:
You can write data to files using the open() function and methods like write().
Python Input
Reading Files:
we can read data from files using the open() function and methods like read(), readline(), or
by iterating through lines with a for loop.
Conditional Statements
Conditional statements in Python (if, elif, else) are used to make decisions and execute different
blocks of code based on specified conditions.
Conditional statements (if, else, and elif) are fundamental programming constructs that allow to
control the flow of our program based on conditions that specify.
In [ ]: if condition:
# Code to execute if the condition is true
In [ ]: num = 5
if num > 0:
print("The number is positive.")
The else statement is used to execute a block of code when none of the preceding conditions
are true.
In [ ]: if condition:
# Code to execute if the condition is true
else:
# Code to execute if the condition is false
In [ ]: num = -5
if num > 0:
print("The number is positive.")
else:
print("The number is negative.")
In the above example, we use an if-else statement to check if num is greater than 0. If it is, the
message "The number is positive." is printed. If it is not (that is, num is negative or zero), the
message "The number is negative." is printed.
Excersice
Checking if a string contains a certain character
if char in string:
print("The string contains the character", char)
else:
print("The string does not contain the character", char)
The elif (short for "else if") statement is used to check an additional condition if the previous if
condition is false. You can have multiple elif blocks. The elif statement allows you to check
multiple conditions in sequence, and execute different code blocks depending on which
condition is true. Here's the basic syntax:
In [ ]: if condition1:
# Code to execute if condition1 is true
elif condition2:
# Code to execute if condition2 is true
In [ ]: if condition1:
# code to execute if condition1 is true
elif condition2:
# code to execute if condition1 is false and condition2 is true
elif condition3:
# code to execute if condition1 and condition2 are false, and condition3 is true
else:
# code to execute if all conditions are false
In [ ]: score = 85
if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
else:
grade = "D"
print(f"Your grade is {grade}")
Loops
The are two types of loop in python
for loop
For loops can iterate over a sequence of numbers using the "range" and "xrange" functions. The
difference between range and xrange is that the range function returns a new list with numbers
of that specified range, whereas xrange returns an iterator, which is more efficient. (Python 3
uses the range function, which acts like xrange). Note that the range function is zero based.
In [ ]: primes = [2, 3, 5, 7]
for prime in primes:
print(prime, end=" ")
"while" loops
While loops repeat as long as a certain boolean condition is met.
count = 0
while count < 5:
print(count, end=" ")
count += 1 # This is the same as count = count + 1
break: The break statement is used to exit the loop prematurely, before it has finished all
iterations.
count = 0
while True:
print(count)
count += 1
if count >= 5:
break
continue: The continue statement is used to skip the current iteration and continue with the
next one
else with Loops: You can use the else block with loops to specify code that should be
executed when the loop completes all iterations without encountering a break.
Nested Loops: You can nest loops within each other to perform more complex iterations.
List Comprehensions
List comprehensions are a concise and expressive way to create lists in Python.
They allow you to generate a new list by applying an expression to each item in an existing
iterable (such as a list, tuple, or range).
List comprehensions are a Pythonic and readable alternative to traditional for-loops when
you want to create a new list based on an existing one.
Basic Syntax:
In [ ]: numbers = [1, 2, 3, 4, 5]
squares = [x**2 for x in numbers]
# squares will be [1, 4, 9, 16, 25]
In [ ]: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]
evens = [x for x in numbers if x % 2 == 0]
for x in numbers:
if(x%2==0):
event.append(x)
Quadratic Reciprocity
In [ ]: p_remainder = [x**2 % p for x in range(0, p)]
len(p_remainder) = (p + 1) / 2
<filter at 0x20fdb3b0250>
Out[29]:
240
Out[32]:
Excercise
1. Create lists of tuples which has student name and cgpa then display student name they
have 2.0 cgpa
1. Assuming we have a list of dictionaries where each dictionary represents an employee with
'name', 'age', and 'salary' attributes. how to calculate total salary of employee they are
above 50 years old? you can use list comprehension to filter employees with age 50 and
above, and then sum their salaries.
In [33]: employees = [
{'name': 'Yohannes', 'age': 45, 'salary': 50000},
{'name': 'Abdul', 'age': 55, 'salary': 60000},
{'name': 'Tamirat', 'age': 50, 'salary': 70000},
{'name': 'Kidist', 'age': 60, 'salary': 80000}
]
210000
Out[46]:
210000
Out[47]:
In [ ]: A=[]
B=[]
cartesian_product= [(a,b) for a in A for b in B]
In [ ]: list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]
Function
In programming, a function is a reusable block of code that executes a certain functionality
when it is called.
A function is a block of organized, reusable code that is used to perform a single, related action.
Functions provide better modularity for your application and a high degree of code reusing.
Function blocks begin with the keyword def followed by the function name and
parentheses ( ( ) ).
Any input parameters or arguments should be placed within these parentheses. You can
also define parameters inside these parentheses.
The first statement of a function can be an optional statement; the documentation string of
the function or docstring.
The code block within every function starts with a colon (:) and is indented.
The statement return [expression] exits a function, optionally passing back an expression to
the caller. A return statement with no arguments is the same as return None.
syntax
parameters: These are optional input values that you can pass to the function. A function
can have zero or more parameters.
return: The return statement is used to specify the value that the function should return to
the caller. If omitted, the function returns None.
In [ ]: def greet(name):
print(f"Hello, {name}!")
In [ ]: def square(x):
return x * x
result = square(5)
print(result) # Output: 25
In this example:
Calling a Function:
To use a function, you call it by its name, passing any required arguments (parameters). The
function's return value can be assigned to a variable or used directly.
Function parameters, also known as arguments, are values that you pass to a function when you
call it. Parameters allow you to provide input to the function so that it can perform a specific
task.
When defining a function, you can specify one or more parameters inside the parentheses.
These parameters act as placeholders for the values that will be passed to the function.
In [ ]: def greet(name):
print(f"Hello, {name}!")
In this example, name is a parameter, and when you call the greet function with the argument
"Alice," the value "Alice" is passed to the name parameter within the function.
You can provide default values for function parameters, making them optional when calling the
function. If an argument is not provided, the default value is used.
In [ ]: def greet(name="Guest"):
print(f"Hello, {name}!")
sum_result = add(3, 4)
print(sum_result) # Output: 7
In this example, the add function takes two parameters, x and y, and returns the sum of these
parameters. The result is stored in the variable sum_result when the function is called.
In [ ]: def get_average():
with open('tempratures.txt', 'r') as file:
data = file.readlines()
values = data[1:]
values = [float(i) for i in values]
In [ ]: round(10/3, 3)
In [ ]: def add(numbers):
res = 0
count = 0
for item in numbers:
res+=item
count= count+1
return res, count
In [ ]: numbers = [2,5,7,8]
sum1, length = add(numbers)
avg = sum1 / length
print(f"sum={sum1}")
print(f"No elements {length}")
print(f"Average: {avg}")
Excersice
Create a function called calculate_stats to perform the sum and average of sequence of number.
In [ ]: def calculate_stats(numbers):
total = sum(numbers)
avg = total / len(numbers)
return total, avg
Coding Exercise 1
The code in the code area is incomplete.
1. complete the get_max function so it calculates and prints out the maximum value of the
grades list.
2. and then call the function and print out the output.
In [ ]: def get_max():
grades = [9.6, 9.2, 9.7]
9.7
In [ ]: def get_max():
grades = [9.6, 9.2, 9.7]
return max([x for x in grades])
print(get_max())
average = stdev(my_list)
print(average)
localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 22/50
3/15/24, 7:25 AM Basic Python Traing Manual
1. Local Scope: Variables defined within a function have local scope, which means they are
only accessible within that function. They have a lifetime limited to the execution of that
function.
In [ ]: def my_function():
x = 10 # x is a variable with local scope
In [ ]: def outer_function():
y = 20 # y is a variable with enclosing scope
def inner_function():
print(y) # y is accessible in the inner function
1. Global Scope: Variables defined at the top level of a Python script or module, outside of
any function, have global scope. They can be accessed from anywhere in the code and have
a lifetime that matches the duration of the program.
def my_function():
print(z) # z is accessible in the function
If you want to modify a global variable from within a function, you can use the global keyword
to indicate that the variable should be treated as a global variable, not a new local variable.
def increment_count():
global count # Indicate that 'count' is global
count += 1
increment_count()
print(count) # Output: 1
def modify_value():
value = 5 # This is a local variable
Recursion
Recursive functions are functions that calls itself. It is always made up of 2 portions, the base
case and the recursive case.
In [ ]: def factorial(n):
if n == 0:
return 1 # Base case: 0! = 1
else:
return n * factorial(n - 1)
n = int(input("Enter the last number:"))
for number in range(1,n+1):
result = factorial(number)
print((number,result)) # Output: 120 (5! = 5 * 4 * 3 * 2 * 1 = 120)
Excersice
Write a recursive function that will sum all numbers from 1 to n. n is the argument of the
function.
In [ ]: def sumSequence(n):
if n == 1:
return 1
else:
return n + sumSequence(n-1)
In [ ]: sum = sumSequence(100)
print(sum)
Collections
List
In Python, a list is a versatile and fundamental data structure used to store collections of items.
Lists are ordered, mutable (changeable), and can contain elements of different data types. Lists
are defined by enclosing a comma-separated sequence of items in square brackets [ ]. Here's an
overview of lists and their operations:
You can create a list by enclosing elements within square brackets. Elements can be of any data
type and can be separated by commas.
In [ ]: x = (1,2,4)
dir(x)
Accessing Elements:
The index starts at 0 for the first element and increments by 1 for each subsequent element.
Slicing:
You can also access a range of elements using slicing.
In [ ]: numbers = [1, 2, 3, 4, 5]
sublist = numbers[1:4] # Extracts elements at index 1, 2, and 3 (result: [2, 3, 4])
Modifying Lists:
Lists are mutable, meaning you can change their elements after creation.
In [ ]: my_list = [1, 2, 3, 7]
elements_to_insert = [4, 5, 6]
position = 3
my_list[3:3] = elements_to_insert
print(my_list) # Output: [1, 2, 3, 4, 5, 6, 7]
In [ ]: my_list = [1, 2, 3, 5]
element_to_insert = 4
position = 3 # Position to insert (0-based index)
my_list.insert(position, element_to_insert)
print(my_list) # Output: [1, 2, 3, 4, 5]
FOR and IN
Python's for and in constructs are extremely useful, and the first use of them we'll see is with
lists. The for construct -- for var in list -- is an easy way to look at each element in a list (or other
collection). Do not add or remove from the list during iteration.
Zipping Items
Finally, it might be useful to combine -- or zip -- two lists together. For example, we might want
to create a new list that pairs the values in our price_birr list with our area_m2 list. To do
that, we use the zip method. The code looks like this:
You might have noticed that the above code involving putting one list (in this case, new_list )
inside another list (in this case, list ). This approach is called a generator, and we'll come
back to what that is and how it works later in the course.
---------------------------------------------------------------------------
NameError Traceback (most recent call last)
Cell In[48], line 1
----> 1 new_list = zip(price_birr, area_m2)
2 zipped_list = list(new_list)
List Methods
Here are some other common list methods.
list.append(elem) -- adds a single element to the end of the list. Common error: does not
return the new list, just modifies the original.
list.insert(index, elem) -- inserts the element at the given index, shifting elements to the
right.
list.extend(list2) adds the elements in list2 to the end of the list. Using + or += on a list is
similar to using extend().
list.index(elem) -- searches for the given element from the start of the list and returns its
index. Throws a ValueError if the element does not appear (use "in" to check without a
ValueError).
list.remove(elem) -- searches for the first instance of the given element and removes it
(throws ValueError if not present)
list.sort() -- sorts the list in place (does not return it). (The sorted() function shown later is
preferred.)
list.reverse() -- reverses the list in place (does not return it)
list.pop(index) -- removes and returns the element at the given index. Returns the rightmost
element if index is omitted (roughly the opposite of append()).
Notice that these are methods on a list object, while len() is a function that takes the list (or
string or whatever) as an argument.
In [ ]: x = [3,1,8,3,10]
print(x)
for item in range(11):
x.append(item)
print(x)
x.sort(reverse=True)
x.remove(10)
x.remove(10)
print(x)
Coding Exercise 1
We have a list of three strings defined in the code area. Extend the code so your program prints
out the following out of that list:
1. 0-Document.txt
2. 1-Report.txt
3. 2-Presentation.txt
Bug-Fixing Exercises
Bug-Fixing Exercise 1
Supposedly, the following program should:
However, there is a bug with the program which you should try to fix.
Bug-Fixing Exercise 2
Here is another piece of buggy code: Fix the code, so it prints out the output below:
if len(password)>=8:
result.append(True)
else:
result.append(False)
digit = False
for i in password:
if i.isdigit():
digit = True
result.append(digit)
uppercase = False
for i in password:
if i.isupper():
uppercase = True
result.append(uppercase)
print(result)
print(all(result))
if all(result):
print('The password is strong')
else:
print('weak password')
Tuples
Tuple is one of 4 built-in data types in Python used to store collections of data, the other 3 are
List, Set, and Dictionary, all with different qualities and usage. A tuple is a collection which is
ordered and unchangeable. Tuples are written with round brackets.
In Python, a tuple is an ordered and immutable collection of elements. Tuples are very similar to
lists in terms of their indexing, nested structures, and their use of the comma as a separator.
However, the key difference is that tuples cannot be modified once they are created, making
them suitable for situations where you want to ensure that the data remains constant. Tuples
are defined by enclosing elements in parentheses (). Here's an overview of tuples and their
operations:
Creating a Tuple:
A tuple is created by placing all the items (elements) inside parentheses (), separated by
commas.
A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).
# Empty tuple
my_tuple = ()
print(my_tuple)
# nested tuple
my_tuple = ("mouse", [8, 4, 6], (1, 2, 3))
print(my_tuple)
`Accessing Elements:
Like a list, each element of a tuple is represented by index numbers (0, 1, ...) where the first
element is at index 0.
We can access individual elements in a tuple using their index, just like you would with a list.
Slicing:
Slicing works the same way in tuples as it does in lists, allowing you to extract a sublist from the
original tuple.
In [ ]: numbers = (1, 2, 3, 4, 5)
subtuple = numbers[1:4] # Extracts elements at index 1, 2, and 3
Tuple Methods:
Tuples have a limited set of methods due to their immutability, but they include methods like
count (to count occurrences of a value) and index (to find the index of a value).
Dictionary
A dictionary is a versatile and built-in data structure that allows you to store data in key-value
pairs. Dictionaries are unordered, mutable, and indexed collections of items, where each item
consists of a key and its associated value. Keys must be unique, and they are used to access the
corresponding values. Dictionaries are defined by enclosing key-value pairs in curly braces { }.
Here's an overview of dictionaries and their operations:
Creating a Dictionary:
We can create a dictionary by enclosing key-value pairs within curly braces. Key-value pairs are
separated by colons, and different pairs are separated by commas.
In [ ]: my_dict = {
'name': 'Yasin',
'age': 30,
'city': 'Harar'
}
my_dict
Accessing Elements:
We can access the values of a dictionary by specifying the key in square brackets or using the
get() method.
In [ ]: person = {
'name': 'Yasin',
'age': 30,
'city': 'Haramaya'
}
Modifying a Dictionary:
Dictionaries are mutable, meaning we can change their values by specifying the key.
In [ ]: person = {
'name': 'Yasin',
'age': 30,
'city': 'Haramaya'
}
Removing Elements:
We can remove elements from a dictionary using the pop() method, specifying the key to be
removed.
In [ ]: person = {
'name': 'Yasin',
'age': 30,
'city': 'Maya City'
}
Dictionary Methods:
Dictionaries have various built-in methods for performing common operations, such as getting
keys, values, and key-value pairs, checking if a key exists, and more.
In [ ]: person = {
'name': 'Yasin',
'age': 30,
'city': 'Maya City'
}
Excercise
Find number of words in the sentence using python programming language.?
In [ ]: word_count
Sets
In Python, a set is an unordered and mutable collection of unique elements. Sets are defined by
enclosing elements within curly braces { }, and the elements are separated by commas. The key
characteristic of sets is that they do not allow duplicate values. Here's an overview of sets and
their operations:
Creating a Set:
You can create a set by enclosing unique elements within curly braces or by using the set()
constructor.
In [ ]: my_set = {1, 2, 3, 4, 5, 5}
another_set = set([3, 4, 2 ,3, 4, 5, 6, 7])
In [ ]: another_set
Accessing Elements:
Since sets are unordered, they do not have indexes like lists or tuples. You typically access set
elements using set operations like checking for membership.
In [ ]: my_set = {1, 2, 3, 4, 5}
is_present = 3 in my_set # Check if an element is present (result: True)
In [ ]: my_set
Modifying a Set:
Sets are mutable, which means you can add or remove elements.
In [ ]: my_set = {1, 2, 3, 4, 5}
my_set.add(6) # Add a new element to the set
my_set.remove(3) # Remove an element by value
Set Operations:
Sets support various set operations like union, intersection, difference, and symmetric
difference.
In [ ]: set1 = {1, 2, 3}
set2 = {3, 4, 5}
Sets are used when you need to work with collections of unique items or perform set-based
operations, such as finding common elements between two collections, removing duplicates
from a list, or checking for membership in a set.
In [ ]: unique_numbers = list(set(numbers))
File Handling
When we want to read from or write to a file, we need to open it first. When we are done, it
needs to be closed so that the resources that are tied with the file are freed.
1. Open a file
2. Read or write (perform operation)
3. Close the file
The open() Python method is the primary file handling function. The basic syntax is:
1. The file_name includes the file extension and assumes the file is in the current working
directory. If the file location is elsewhere, provide the absolute or relative path.
2. The mode is an optional parameter that defines the file opening method. The table below
outlines the different possible options:
Write to a file
There are two methods of writing to a file in Python, which are:
1. write()
2. writelines()
Exception Handling
Even if a statement or expression is syntactically correct, it may cause an error when an attempt
is made to execute it.
Errors detected during execution are called exceptions and are not unconditionally fatal: you will
soon learn how to handle them in Python programs. Most exceptions are not handled by
programs, however, and result in error messages as shown here:
In [ ]: try:
# code that may cause exception
except:
# code to run when exception occurs
Here, we have placed the code that might generate an exception inside the try block. Every try
block is followed by an except block.
When an exception occurs, it is caught by the except block. The except block cannot be used
without the try block.
In [ ]: res = 10/0
In [ ]: try:
# Code that might raise an exception
result = 10 / 0 # This will raise a ZeroDivisionError
except ZeroDivisionError as e:
# Code to handle the exception
print(f"Any number does not divided by 0 {e}")
In the example, we are trying to divide a number by 0. Here, this code generates an exception.
To handle the exception, we have put the code, result = numerator/denominator inside the try
block. Now when an exception occurs, the rest of the code inside the try block is skipped.
The except block catches the exception and statements inside the except block are executed.
In [ ]: try:
# Code that might raise an exception
print("Befor the exception was happen")
x = 4
y =6
add = x + y
print("sum=", add)
result = 10 / 0
print("Hello")
except ZeroDivisionError:
print("You can't divide by zero!")
except ArithmeticError:
print("An arithmetic error occurred.")
except Exception as e:
print(f"An exception occurred: {e}")
Using finally:
The finally block is used to specify code that will always be executed, whether an exception is
raised or not.
In [ ]: try:
# Code that might raise an exception
value = int("42")
except ValueError:
print("Invalid value")
finally:
print("Finally block is executed, no matter what.")
When working with files in Python, it's important to handle exceptions to ensure that your code
behaves gracefully in various situations, such as when a file doesn't exist, there's a permission
issue, or the file operation encounters errors. Here's how you can handle exceptions when
dealing with file operations:
In [ ]: try:
with open('file.txt', 'r') as file:
content = file.read()
except FileNotFoundError:
print("The file doesn't exist.")
except PermissionError:
print("Permission denied.")
except Exception as e:
print(f"An exception occurred: {e}")
In [ ]: try:
with open('filfde.txt', 'r') as file:
content = file.read()
if len(content) == 0:
raise ValueError("The file is empty.")
except FileNotFoundError:
print("The file doesn't exist.")
except PermissionError:
print("Permission denied.")
except ValueError as e:
print(f"Value error: {e}")
except Exception as e:
print(f"An exception occurred: {e}")
The else block contains code that should be executed if no exceptions occur during file
operations.
In [ ]: try:
except FileNotFoundError:
print("The file doesn't exist.")
except Exception as e:
print(f"An exception occurred: {e}")
else:
print("File reading successful.")
In [ ]:
Class in Python
classes and objects are fundamental concepts that allow you to model and represent real-world
entities and their behaviors.
Classes serve as blueprints for creating objects, and objects are instances of these classes.
Class
Object
Method
Inheritance
Polymorphism
Data Abstraction
Encapsulation
Defining a Class:
A class is a template or a blueprint for creating objects. It defines the structure and behavior of
objects. To define a class, use the class keyword followed by the class name and a colon.
In [ ]: class MyClass:
pass
# Class attributes and methods go here
In [ ]: def myfun():
pass
In [ ]: class Person:
def __init__(self, fname, lname, age):
# This is the constructor method that is called when creating a new Person obj
# It takes two parameters, name and age, and initializes them as attributes of
self.fname = fname
self.age = age
self.lname = lname
def greet(self):
# This is a method of the Person class that prints a greeting message
message = f"Hello {self.fname} {self.lname}. Well come to our session"
print(message)
person3.greet()
By using the class constructor, you may create an object of a class in Python. The object's
attributes are initialised in the constructor, which is a special procedure with the name init.
Once we have defined a class, we can create objects (instances) of that class using the class
name followed by parentheses.
Syntax:
In [ ]: class Student:
fname = "Kedir"
def info(self):
print(f"{self.fname} is a student")
stud1 = Student()
stud1.info()
Attributes:
attributes are variables that hold data associated with an object. They represent the object's
state. There are two types of attributes:
1. Instance Attributes: These attributes are specific to each instance of the class. You can
define them inside the class's methods.
In [ ]: class Person:
def __init__(self, name, age):
self.name = name # Instance attribute
self.age = age # Instance attribute
1. Class Attributes: These attributes are shared by all instances of the class. They are defined
within the class but outside any method.
In [ ]: class Circle:
pi = 3.14 # Class attribute
circle1 = Circle(2)
Excercise
Create Employee class which has name, age and salary attribute and create 3 objects then
display thier information.
In [ ]: class Employee:
# count = 0
def __init__(self, name, age, salary):
self.name = name
self.age = age
self.salary = salary
def get_info(self):
info = f"My name is {self.name}, I am {self.age} years old. and my salary is {
print(info)
In [ ]: def get_data(empno):
# empno = count + 1
print(f"Enter all requiered Information for Employee {empno}")
name = input("Name:")
age = input("Age:")
salary = input("Salary:")
return name, age, salary
emp1.get_info()
emp2.get_info()
emp3.get_info()
Inheritance
Inheritance is the process of creating a new class by deriving properties and behaviors from an
existing class.
In inheritance, the child class acquires the properties and can access all the data members and
functions defined in the parent class. A child class can also provide its specific implementation
to the functions of the parent class.
The existing class is called the superclass or parent class, and the new class is called the subclass
or child class.
The subclass inherits attributes and methods from the superclass. This allows you to create
specialized classes that share common characteristics.
Syntax
In [ ]: class Animal:
def __init__(self, name):
self.name = name
def speak(self):
pass
class Dog(Animal):
def speak(self):
return f"{self.name} says Woof!"
class Cat(Animal):
def speak(self):
return f"{self.name} says Meow!"
dog = Dog("jack")
cat = Cat("tomy")
In the example above, the Dog and Cat classes are subclasses of the Animal class. They inherit
the name attribute and define their own speak methods.
Abstraction
Abstraction is used to hide the internal functionality of the function from the users. The users
only interact with the basic implementation of the function, but inner working is hidden. User is
familiar with that "what function does" but they don't know "how it does."
In Python, an abstraction is used to hide the irrelevant data/class in order to reduce the
complexity. It also enhances the application efficiency. Next, we will learn how we can achieve
abstraction using the Python program.
class Shape(ABC):
@abstractmethod
def area(self):
pass
def area(self):
return 3.14 * self.radius**2
class Square(Shape):
def __init__(self, side_length):
self.side_length = side_length
def area(self):
return self.side_length**2
Polymorphism
Polymorphism is the ability to use objects of different classes through a common interface. It
allows you to write code that can work with objects without knowing their specific class.
Polymorphism is achieved through method overriding and interfaces.
In [ ]: x = "Hello World!"
#For strings len() returns the number of characters:
print(len(x))
thisdict = {
"brand": "Ford",
"model": "Mustang",
"year": 1964
}
#For dictionaries len() returns the number of key/value pairs in the dictionary:
print(len(thisdict))
In [ ]: class Shape:
def area(self):
pass
class Circle(Shape):
def __init__(self, radius):
self.radius = radius
def area(self):
return 3.14 * self.radius**2
class Square(Shape):
def __init__(self, side_length):
self.side_length = side_length
def area(self):
return self.side_length**2
In [ ]: class Car:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Drive!")
class Boat:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Sail!")
class Plane:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Fly!")
In [ ]: class Ethiopia():
def capital(self):
print("Addis Ababa is the capital of Ethiopia.")
def language(self):
print("Amharic is the most widely spoken language of Ethiopia.")
def type(self):
class USA():
def capital(self):
print("Washington, D.C. is the capital of USA.")
def language(self):
print("English is the primary language of USA.")
def type(self):
print("USA is a developed country.")
def func(obj):
obj.capital()
obj.language()
obj.type()
obj_eth = Ethiopia()
obj_usa = USA()
func(obj_eth)
func(obj_usa)
Excercise
Create a class called Vehicle and make Car, Boat, Plane child classes of Vehicle:
In [ ]: class Vehicle:
def __init__(self, brand, model):
self.brand = brand
self.model = model
def move(self):
print("Move!")
class Car(Vehicle):
pass
class Boat(Vehicle):
def move(self):
print("Sail!")
class Plane(Vehicle):
def move(self):
print("Fly!")
Encapsulation
Encapsulation is the concept of bundling the data (attributes) and methods (functions) that
operate on the data into a single unit known as a class.
The primary goal of encapsulation is to hide the internal details of a class while providing a well-
defined interface for interacting with the class.
This allows you to control access to the data and protect it from unauthorized or unintended
modifications.
In Python, encapsulation can be achieved using access modifiers. These access modifiers control
the visibility of class members (attributes and methods):
1. Public: Members are accessible from anywhere. In Python, by default, all members are
public.
2. Protected: Members are indicated with a single underscore prefix (e.g., _attribute). These
members are intended to be protected and should not be accessed directly outside the
class, although it's not enforced by the language.
3. Private: Members are indicated with a double underscore prefix (e.g., __attribute). These
members are meant to be private and should not be accessed directly outside the class.
Python enforces name mangling for private members to make them less accessible.
In [ ]: class Person:
def __init__(self, name, age):
self._name = name # Protected attribute
self.__age = age # Private attribute
def get_name(self):
return self._name
Excercise
Create student class and implementation encapsulation method to hide all attributes like id,
name, age, and cgpa
Regular Expression
A Python regular expression is a sequence of metacharacters that define a search pattern. We
use these patterns in a string-searching algorithm to "find" or "find and replace" on strings.
Regular expressions, often abbreviated as "regex" or "regexp," are a powerful tool for pattern
matching and text manipulation. They provide a way to search, extract, and manipulate strings
based on specific patterns.
In Python, regular expressions are commonly used with the re module, which provides functions
and methods for working with regex patterns.
In [ ]: import re
Literal Characters: To search for a literal character in a string, you can use the character
itself. For example, the pattern "abc" matches the substring "abc" in a string.
Character Classes: You can use character classes to match a set of characters. For example,
[aeiou] matches any vowel.
The re.search() function is used to search for a pattern within a string. It returns a match object if
a match is found, or None if no match is found.
In [ ]: import re
In [ ]:
The re.findall() function returns all non-overlapping matches of a pattern in a string as a list of
strings.
In [ ]: import re
print("Matches:", matches)
# Output: ['The', 'sun', 'is', 'shining', '-and', 'the', 'birds', 'are', 'singing']
Regular expressions can be case-sensitive or case-insensitive, and you can control this using
flags. For example, to perform a case-insensitive search, you can use the re.IGNORECASE flag.
In [ ]: import re
text = "The quick brown FOx jumps over the lazy dog."
pattern = r"fox"
matches = re.findall(pattern, text, re.IGNORECASE)
print("Matches:", matches)
# Output: ['fox']
Common Metacharacters:
Pattern Matching
Pattern matching using regular expressions is a powerful technique for finding and extracting
specific patterns within text. You can use Python's re module to perform pattern matching and
extract information from text data.
In [ ]: import re
1. Define a Regular Expression Pattern: Create a regular expression pattern that defines the
pattern you want to match. Use metacharacters and character classes to specify the pattern
you're looking for.
In [ ]: import re
text = "there are 10 apples and 23 Mango"
pattern = r'[a-zA-Z]+'
print(re.findall(pattern, text))
1. Search for Matches: Use the re.search() function to search for the pattern within a string. It
returns a match object or None if no match is found.
if match:
print("Match found:", match.group()) # Output: "123"
else:
print("No match found")
1. Find All Matches: To find all occurrences of the pattern within the text, use the re.findall()
function. It returns a list of matching substrings.
1. Extract Matched Groups: Regular expressions can include capturing groups using
parentheses. You can use match.group(index) to access specific capturing groups.
if match:
print("Number:", match.group(1)) # Output: "123"
print("Fruit:", match.group(2)) # Output: "apples"
1. Iterate Over Matches: You can use the re.finditer() function to find all matches and iterate
over them using a loop.
1. Replace Matches: You can use the re.sub() function to replace matches with a specified
string.
1. Regular Expression Flags: You can use flags like re.IGNORECASE to make the pattern
matching case-insensitive.
In [ ]: pattern = r'apple'
text = "I like Apple, apple, and APPLE."
matches = re.findall(pattern, text, re.IGNORECASE)
print("Matches:", matches) # Output: ["Apple", "apple", "APPLE"]
In [ ]: import re
text = "$hell12o thi23s is sentence"
pattern = "[a-zA-Z]"
text1 = re.sub(pattern, "", text)
print(re.match(pattern, text))
print(text1)
In [ ]: import re
text = "The quick brown fox jumps over the lazy dog."
pattern = r"fox"
match = re.search(pattern, text)
if match:
print("Match found:", match.group()) # Output: "fox"
else:
print("No match found")