0% found this document useful (0 votes)
4 views

Basic Python Traing Manual

The document is a basic Python training manual that outlines the steps for setting up a Python environment, including installation of Python and Anaconda, creating virtual environments, and choosing a code editor. It also covers fundamental Python concepts such as variable declaration, data types, operators, and basic arithmetic operations. The manual provides examples and explanations to help beginners start coding in Python effectively.

Uploaded by

Tsegaye Eshetu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
4 views

Basic Python Traing Manual

The document is a basic Python training manual that outlines the steps for setting up a Python environment, including installation of Python and Anaconda, creating virtual environments, and choosing a code editor. It also covers fundamental Python concepts such as variable declaration, data types, operators, and basic arithmetic operations. The manual provides examples and explanations to help beginners start coding in Python effectively.

Uploaded by

Tsegaye Eshetu
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 50

3/15/24, 7:25 AM Basic Python Traing Manual

1. Setting up our python Environment


Setting up our Python environment is one of the first steps in programming with Python.

Here's a general guide on how to set up your Python


environment:

1. Install Python:

Go to the official Python website at python.org.


Download the latest version of Python (Python 3 is recommended) for your operating
system (Windows, macOS, or Linux).
Run the installer and follow the installation instructions. Make sure to check the option that
adds Python to your system's PATH, which allows you to run Python from the command line
easily.

1. Verify Your Installation:

Open a command prompt or terminal.


Type python --version or python -V to check if Python is installed correctly and to see the
version. It should display the Python version you installed.

1. Download Anaconda and install :

Visit the Anaconda website: https://www.anaconda.com/products/distribution.


Download the appropriate version of Anaconda for your operating system (Windows,
macOS, or Linux).
Follow the installation instructions provided on the website for your specific operating
system.
Run the installer that you downloaded.
Follow the installation prompts and accept the default settings.
Once the installation is complete, Anaconda should be installed on your system.

1. Create a Virtual Environment and activate it:

Open a terminal or command prompt on your system.


To create a new virtual environment, use the following command: conda create -name
After creating the virtual environment, you need to activate it.
On Windows, use the following command: conda activate

1. Install Packages into the Virtual Environment:

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 1/50


3/15/24, 7:25 AM Basic Python Traing Manual

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

1. Choose a Code Editor or IDE:

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.

1. Create a Project Folder:

Organize your work by creating a project folder for your Python files. This helps keep your
code and related files structured.

1. Virtual Environments (Recommended):

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.

1. Running Python Code:

To run your Python code, you can execute the Python file from the command line:

Python: Getting Started


In [1]: print("Hello world")

Hello world

In [4]: 5 + 3

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 2/50


3/15/24, 7:25 AM Basic Python Traing Manual
8
Out[4]:

Simple Calculations
In addition to all the more complex things you can do in Python, it is also useful for completing
simple mathematical operations.

Addition and Subtraction

Add numbers together like this:

In [ ]: 2 + 2

In [ ]: 4-3

Notice that you don't need to include = in order to make the operation work.

Subtract numbers like this:

Division

Divide numbers like this:

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

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 3/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [ ]: 11//4

Remember that Python will return an error if you try to divide by 0!

Modulo Division

Perform modulo division like this:

In [ ]: 7%3

Multiplication

Multiply numbers like this:

In [ ]: 6 * 2

Add exponents to numbers like this:

In [ ]: 4**2

Order of Operations
Just like everywhere else, Python works on a specific order of operations. That order is:

Parentheses Exponents Multiplication Addition Subtraction

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)

this is the example


of something
in python training

In [13]: print('Herllo world this is an example')

Herllo world this is an example

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 4/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [17]: x= int(input("Enter first number:"))


y = int(input("Enter the second number:"))
x + y

Enter first number:6


Enter the second number:4
10
Out[17]:

In [22]: print(f"{x} + {y} = {x+y}")

6 + 4 = 10

In [ ]: x =int(input("Enter the first number:"))


y =int(input("Enter the second number:"))
sum1 = x + y
print(f"{x} + {y} = {sum1}")

Variable and datatype


In Python, variables are used to store and manage data. Python is a dynamically typed language, which
means you don't need to declare a variable's data type explicitly; it is determined automatically based on
the value assigned to it. Here's an overview of variables and the common data types in Python:

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)

2. Variable nameing rule


Variable names must start with a letter (a-z, A-Z) or an underscore (_).
They can include letters, numbers, and underscores.
Variable names are case-sensitive, so X and x are treated as different variables.

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)

2.2. Common Data Types in Python


Python supports various data types. Here are some of the most common ones:

1. Numeric Types

int: Integers, e.g., 5, -3, 0.


float: Floating-point numbers, e.g., 3.14, -0.5, 2.0.

1. String

str: A sequence of characters enclosed in single or double quotes, e.g., "Hello, World!" or
'Python'.

1. Boolean

bool: Represents truth values. It can be either True or False.

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

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 6/50


3/15/24, 7:25 AM Basic Python Traing Manual

NoneType: Represents the absence of a value. It is often used as a placeholder or to


indicate that a variable has no value assigned.

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. Bytes and Byte Arrays:

bytes: Represents a sequence of bytes. Bytes are immutable.


bytearray: Represents a mutable sequence of bytes. 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

NoneType: Represents the absence of a value. It is often used as a placeholder or to


indicate that a variable has no value assigned.

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. Bytes and Byte Arrays:

bytes: Represents a sequence of bytes. Bytes are immutable.


bytearray: Represents a mutable sequence of bytes.

2.3. Operators and Expressions


In Python, operators and expressions are essential for performing various operations and
calculations. Operators are symbols that perform operations on variables and values, while
expressions are combinations of variables, values, and operators.

1. Arithmetic Operators:
Arithmetic operators are used for basic mathematical operations.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 7/50


3/15/24, 7:25 AM Basic Python Traing Manual

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.

In [ ]: and # Logical AND


or # Logical OR
not # Logical NOT

Example

In [ ]: is_true = 3>=2
is_false = 1<=9
result = is_true or is_false
print(result)

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 8/50


3/15/24, 7:25 AM Basic Python Traing Manual

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 [ ]: & # Bitwise AND


| # Bitwise OR
^ # Bitwise XOR
~ # Bitwise NOT
<< # Left shift
>> # Right shift

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.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 9/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [49]: name = ["Kedir", "Yassin", "Tamirat"]


"Kedir" in name

True
Out[49]:

In [ ]: in # True if a value is found in the sequence


not in # True if a value is not found in the sequence

Example

In [ ]: fruits = ['apple', 'banana', 'orenge']


is_apple_in_fruits = 'banana' not in fruits
print(is_apple_in_fruits)

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]:

In [ ]: is # True if both variables point to the same object


is not # True if both variables point to different objects

In [55]: names=["Kedir", "Aster", "Kedija", "Yoham", "Yohanis"]

In [59]: for index, name in enumerate(names):


print(f'{index+1} - {name}')

1 - Kedir
2 - Aster
3 - Kedija
4 - Yoham
5 - Yohanis

In [63]: even = sum([x for x in range(1,101) if x%2==0])


print(even, end=" ")

2550

In [66]: ke_name = [name for name in names if name.lower().startswith("ke".lower())]


ke_name

['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}')

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 10/50


3/15/24, 7:25 AM Basic Python Traing Manual
search...YO
1 - Yoham
2 - Yohanis

Example

In [76]:

dict
Out[76]:

In [ ]: names = ["Kedir", "Aster", "Kedija", "Yoham", "Yohanis"]


q = input("search...")
search = [name for name in names if name.lower().startswith(q.lower())]
search

In [ ]: x = [1, 2, 3]
y = x # y references the same object as x
is_same = x is y # True

2.3. Input and Output


Input and output (I/O) are fundamental concepts in programming that allow you to interact
with a program, provide data, and receive results. In Python, you can perform input and output
operations using various functions and methods.

Python Output
In Python, we can simply use the print() function to print output. For example,

In [ ]: print('Python is powerful programming language')

print() function syntax


Syntax : print(value(s), sep= ‘ ‘, end = ‘\n’, file=file, flush=flush)

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

print("Hello, my name is", name, "and I am", age, "years old.")

In [ ]: print("Hello ", end = " ")


print("World!")

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 11/50


3/15/24, 7:25 AM Basic Python Traing Manual

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

print('The value of x is {} and y is {}'.format(x,y))

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().

In [ ]: with open('output.txt', 'w') as file:


file.write("This is written to the file.")

Python Input

Standard Input (stdin):


We can read user input from the keyboard using the input() function.
It reads a line of text entered by the user and returns it as a string.

In [ ]: user_input = input("Enter something: ")

In [ ]: # using input() to take user input


num = input('Enter a number: ')
num2 = int(num)

print('You Entered:', num)

print('Data type of num:', type(num2))

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.

In [ ]: # Reading the entire file


with open('myfile.txt', 'r') as file:
content = file.read()
print(content)

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 12/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [ ]: # Reading line by line


with open('myfile.txt', 'r+') as file:
for line in file:
print(line)

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.

1. if Statement The if statement is used to execute a block of code if a specified condition is


true. If the condition is false, the code block is skipped.

In [ ]: if condition:
# Code to execute if the condition is true

In [ ]: num = 5

if num > 0:
print("The number is positive.")

1. else Statement (Optional):

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

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 13/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [ ]: students = ["Kelemu", "Yassin", "Kedir", "Desta"]


name = input("search....")
result = [student.startswith(name) for student in students]
result

In [ ]: string = "hello, world"


char = "a"

if char in string:
print("The string contains the character", char)
else:
print("The string does not contain the character", char)

1. elif Statement (Optional):

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

1. for loop and,


2. while loop

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 14/50


3/15/24, 7:25 AM Basic Python Traing Manual

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=" ")

python range() function


The Python range() function returns a sequence of numbers, in a given range.
The most common use of it is to iterate sequences on a sequence of numbers using Python
loops.

In [ ]: range(start, stop, step)

If we pass all three arguments,

the first argument is start


the second argument is stop
the third argument is step

In [ ]: # Prints out the numbers 0,1,2,3,4


for x in range(5):
print(x, end=" ")

In [ ]: # Prints out 3,4,5


for x in range(3, 6):
print(x, end=" ")

In [ ]: # Prints out 3,5,7


for x in range(3, 8, 2):
print(x, end=" ")

In [ ]: numbers = range(0, 15, 3)


print(list(numbers)) # [0, 1, 2, 3, 4]

In [ ]: # numbers from 2 to 10 with increment 3 between numbers


numbers = range(2, 10, 3)
print(list(numbers)) # [2, 5, 8]

In [ ]: # numbers from 4 to -1 with increment of -1


numbers = range(4, -1, -1)
print(list(numbers)) # [4, 3, 2, 1, 0]

In [ ]: # numbers from 1 to 4 with increment of 1


# range(0, 5, 1) is equivalent to range(5)

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 15/50


3/15/24, 7:25 AM Basic Python Traing Manual
numbers = range(0, 5, 1)
print(list(numbers)) # [0, 1, 2, 3, 4]

"while" loops
While loops repeat as long as a certain boolean condition is met.

In [ ]: # Prints out 0,1,2,3,4

count = 0
while count < 5:
print(count, end=" ")
count += 1 # This is the same as count = count + 1

Loop Control Statements


Python provides control statements that you can use to modify the behavior of loops:

break: The break statement is used to exit the loop prematurely, before it has finished all
iterations.

In [ ]: # Prints out 0,1,2,3,4

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

In [ ]: # Prints out only odd numbers - 1,3,5,7,9


for x in range(10):
# Check if x is even
if x % 2 == 0:
continue
print(x)

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.

In [ ]: for i in range(1, 6):


print(i)
else:
print("Loop finished without a break.")

Nested Loops: You can nest loops within each other to perform more complex iterations.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 16/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [ ]: for i in range(1, 4):


for j in range(1, 4):
print(i,j, end=" ")
print()

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:

The basic structure of a list comprehension is as follows:

new_list = [expression for item in iterable if condition]

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)

# evens will be [2, 4, 6, 8]

In [ ]: words = ["apple", "banana", "orange"]


uppercase_words = [word.upper() for word in words]
# uppercase_words will be ['APPLE', 'BANANA', 'ORENGE']
print(uppercase_words)

In [ ]: names = ["Yasine", "Yohannes", "Alemu"]


name_length_pairs = [(name, len(name)) for name in names]
# name_length_pairs will be [('Yasine', 6), ('Yohannes', 8), ('Alemu', 5)]

In [ ]: matrix = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]


flattened_matrix = [x for row in matrix for x in row]
# flattened_matrix will be [1, 2, 3, 4, 5, 6, 7, 8, 9]

Quadratic Reciprocity
In [ ]: p_remainder = [x**2 % p for x in range(0, p)]
len(p_remainder) = (p + 1) / 2

map, filter and reduce function in python

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 17/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [27]: numbers = [2,5,8,3]


seq = list(map(lambda num : num**2, numbers))
seq

[4, 25, 64, 9]


Out[27]:

In [29]: even = list(filter(lambda x : x%2==0, numbers))


even

<filter at 0x20fdb3b0250>
Out[29]:

In [32]: from functools import reduce


y = reduce(lambda x, y : x*y, numbers)
y

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}
]

In [46]: salary = reduce(lambda x, y : x + y, list(map(lambda emp: emp['salary'], list(filter(


salary

210000
Out[46]:

In [47]: salary = reduce(lambda x, y : x + y, [employee['salary'] for employee in employees if


salary

210000
Out[47]:

In [ ]: A=[]
B=[]
cartesian_product= [(a,b) for a in A for b in B]

Intersection and Union

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 18/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [ ]: list1 = [1, 2, 3, 4]
list2 = [3, 4, 5, 6]

intersection = [value for value in list1 if value in list2]


union = list1 + [value for value in list2 if value not in list1]

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.

Python Defining a Function


You can define custom functions to provide the required functionality. Here are simple rules to
define a function in Python.

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

In [ ]: def functionname( parameters ):


"function_docstring"
function_suite
return [expression]

Basic Function Syntax:

A Python function typically follows this structure:

def: The def keyword is used to define a function.


function_name: This is the name you give to your function, following Python's naming
rules.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 19/50


3/15/24, 7:25 AM Basic Python Traing Manual

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}!")

greet("Aster") # Output: "Hello, Aster!"

In [ ]: def square(x):
return x * x

result = square(5)
print(result) # Output: 25

In this example:

square is the function name.


(x) is the parameter representing the input value.
The function calculates the square of x and returns the result.

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.

In [ ]: result = square(5) # Calling the square function


print(result) # Output: 25

Function Parameters and Return Values

Function Parameters (Input):

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.

Defining Functions with Parameters:

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 function_name(parameter1, parameter2, ...):


# Function code that uses the parameters

In [ ]: def greet(name):
print(f"Hello, {name}!")

greet("Aster") # "Alice" is passed as the value of the "name" parameter

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 20/50


3/15/24, 7:25 AM Basic Python Traing Manual

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.

Default Parameter Values:

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}!")

greet() # Output: "Hello, Guest!"


greet("Aster") # Output: "Hello, Aster!"

Defining Functions with Return Values:


You specify the return value in the return statement. The function can return any data type,
including numbers, strings, lists, and more.

In [ ]: def add(x, y):


result = x + y
return result

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.

Read a file and calculte the avarege of the element

In [ ]: def get_average():
with open('tempratures.txt', 'r') as file:
data = file.readlines()
values = data[1:]
values = [float(i) for i in values]

average = sum(values) / len(values)


return average
average = get_average()
print(round(average,2))

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

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 21/50


3/15/24, 7:25 AM Basic Python Traing Manual

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

data = [10, 20, 30, 40, 50]


total, average = calculate_stats(data)
print("Total:", total)
print("Average:", average)

Coding Exercise 1
The code in the code area is incomplete.

Your task is to:

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]

The output of your code should be:

9.7

In [ ]: def get_max():
grades = [9.6, 9.2, 9.7]
return max([x for x in grades])

print(get_max())

In [ ]: from statistics import mode, median, stdev

my_list = [2, 1, 2, 8, 3, 10]

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

Scope and Lifetime of Variables

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

1. Enclosing (Nonlocal) Scope: If a variable is defined within an enclosing function (a


function that contains another function), it can be accessed by the inner function. The
variable's lifetime extends from the point of assignment until the function in the enclosing
scope is no longer in use.

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.

In [ ]: z = 30 # z is a variable with global scope

def my_function():
print(z) # z is accessible in the function

Modifying Variables in Different Scopes:

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.

In [ ]: count = 0 # Global variable

def increment_count():
global count # Indicate that 'count' is global
count += 1

increment_count()
print(count) # Output: 1

In [ ]: value = 10 # Global variable

def modify_value():
value = 5 # This is a local variable

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 23/50


3/15/24, 7:25 AM Basic Python Traing Manual
modify_value()
print(value) # Output: 10 (global variable is not modified)

Recursion
Recursive functions are functions that calls itself. It is always made up of 2 portions, the base
case and the recursive case.

The base case is the condition to stop the recursion.


The recursive case is the part where the function calls on itself.

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)

In [ ]: with open('factorial.csv', 'w') as file:


columns = f"number,factorial"
file.write(columns)

with open('factorial.csv', 'a') as file:


n = int(input("Enter the last number:"))
for number in range(1,n+1):
result = factorial(number)
data = f"\n{number},{result}"
file.write(data)
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

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 24/50


3/15/24, 7:25 AM Basic Python Traing Manual

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.

Lists are defined by enclosing a comma-separated sequence of items in square brackets [ ].

In [ ]: my_list = [1, 2, 3, 'apple', 'banana']


help(my_list.pop)

In [ ]: x = (1,2,4)
dir(x)

Accessing Elements:

We can access individual elements in a list using their index.

The index starts at 0 for the first element and increments by 1 for each subsequent element.

In [ ]: colors = ['red', 'blue', 'green']


print(colors[0]) ## red
print(colors[2]) ## green
print(len(colors)) ## 3

Slicing:
You can also access a range of elements using slicing.

Slicing allows you to extract a sublist from the original list.

In [ ]: numbers = [1, 2, 3, 4, 5]
sublist = numbers[1:4] # Extracts elements at index 1, 2, and 3 (result: [2, 3, 4])

In [25]: squares = list(map(lambda x: x**2, range(10)))


squares

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]


Out[25]:

In [ ]: sequares = [x**2 for x in range(10)]


sequares

Modifying Lists:
Lists are mutable, meaning you can change their elements after creation.

We can modify individual elements or add and remove elements.

In [ ]: colors = ['red', 'blue', 'green']


colors[1] = "teal"
localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 25/50
3/15/24, 7:25 AM Basic Python Traing Manual
colors.append('white')
colors.remove('red')
colors

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]

Inserting an lists into lists

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.

In [ ]: squares = [1, 4, 9, 16]


sum = 0
for num in squares:
sum += num
print(sum) ## 30

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.

In [48]: new_list = zip(price_birr, area_m2)


zipped_list = list(new_list)

---------------------------------------------------------------------------
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)

NameError: name 'price_birr' is not defined

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 26/50


3/15/24, 7:25 AM Basic Python Traing Manual

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 [ ]: fruits = ['apple', 'banana', 'orange']


fruits.append('orange') # Add an element to the end
fruits.remove('banana') # Remove an element by value
fruits.sort() # Sort the list in ascending order
index = fruits.index('orange') # Find the index of an element
print(fruits)

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)

In [ ]: fruits = ['orange', 'apple', 'pear', 'banana', 'kiwi', 'apple', 'banana']


fruits.count('apple')# 2
fruits.count('tangerine') # 0
>>> fruits.index('banana')
3
>>> fruits.index('banana', 4) # Find next banana starting at position 4
6
>>> fruits.reverse()
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange']

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 27/50


3/15/24, 7:25 AM Basic Python Traing Manual
>>> fruits.append('grape')
>>> fruits
['banana', 'apple', 'kiwi', 'banana', 'pear', 'apple', 'orange', 'grape']
>>> fruits.sort()
>>> fruits
['apple', 'apple', 'banana', 'banana', 'grape', 'kiwi', 'orange', 'pear']
>>> fruits.pop()
'pear'

Common List Operations:

Finding the length of a list: len(my_list)


Checking if an element is in a list: element in my_list
Concatenating lists: new_list = list1 + list2
Repeating a list: new_list = my_list * n

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:

1. Prompt the user to input an index (e.g., 0, 1, or 2).

2. Print out the item with that index.

However, there is a bug with the program which you should try to fix.

In [ ]: menu = ["pasta", "pizza", "salad"]

user_choice = input("Enter the index of the item: ")

message = f"You chose {menu[user_choice]}."


print(message)

Bug-Fixing Exercise 2
Here is another piece of buggy code: Fix the code, so it prints out the output below:

In [ ]: menu = ["pasta", "pizza", "salad"]

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 28/50


3/15/24, 7:25 AM Basic Python Traing Manual
for i, j in enumerate[menu]:
print(f"{i}.{j}")

checking password strength


In [ ]: password = input("Enter your password:")
result =[]

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.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 29/50


3/15/24, 7:25 AM Basic Python Traing Manual

The parentheses are optional, however, it is a good practice to use them.

A tuple can have any number of items and they may be of different types (integer, float, list,
string, etc.).

In [ ]: my_tuple = (1, 2, 3, 'apple', 'banana')

In [ ]: # Different types of tuples

# Empty tuple
my_tuple = ()
print(my_tuple)

# Tuple having integers


my_tuple = (1, 2, 3)
print(my_tuple)

# tuple with mixed datatypes


my_tuple = (1, "Hello", 3.4)
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.

In [ ]: fruits = ('apple', 'banana', 'orange')


first_fruit = fruits[0] # Access the first element ('apple')
second_fruit = fruits[1] # Access the second element ('banana')

In [ ]: # accessing tuple elements using indexing


letters = ("p", "r", "o", "g", "r", "a", "m", "i", "z")

print(letters[0]) # prints "p"


print(letters[5]) # prints "a"

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

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 30/50


3/15/24, 7:25 AM Basic Python Traing Manual

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).

In [ ]: fruits = ('apple', 'banana', 'orange', 'banana')


count = fruits.count('banana') # Count occurrences of 'banana' (result: 2)
index = fruits.index('orange') # Find the index of 'orange' (result: 2)

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'
}

name = person['name'] # Access the 'name' key (result: 'Yasin')


age = person.get('age') # Using the get method (result: 30)

In [ ]: student= {"name":["Yasin", "Aster","Kedir"],


"age":[34,65,23]}
print(student["name"][1])

Modifying a Dictionary:

Dictionaries are mutable, meaning we can change their values by specifying the key.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 31/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [ ]: person = {
'name': 'Yasin',
'age': 30,
'city': 'Haramaya'
}

person['city'] = 'Maya City' # Modify the 'city' key


person['country'] = 'Ethiopia' # Add a new key-value pair

Removing Elements:

We can remove elements from a dictionary using the pop() method, specifying the key to be
removed.

We can also use the del statement to remove a key-value pair.

In [ ]: person = {
'name': 'Yasin',
'age': 30,
'city': 'Maya City'
}

person.pop('age') # Remove the 'age' key


del person['city'] # Remove the 'city' key-value pair

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'
}

keys = person.keys() # Get a list of keys


values = person.values() # Get a list of values
items = person.items() # Get a list of key-value pairs
has_age = 'age' in person # Check if a key exists (result: True)
print(keys)
print(values)
print(items)
print(has_age)

Excercise
Find number of words in the sentence using python programming language.?

Storing and retrieving configuration settings.


Counting the frequency of items in a list or text.
Creating records with named fields.
Implementing data structures like graphs and hash tables.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 32/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [ ]: # Storing configuration settings


config = {
'username': 'user123',
'password': 'secret',
'server': 'example.com'
}

# Counting frequency of items


text = "this is a sample text with some repeated words. this example is good for a tra
word_count = {}
words = text.split()
print(len(words))
for word in text.split():
if word in word_count:
word_count[word] += 1
else:
word_count[word] = 1

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.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 33/50


3/15/24, 7:25 AM Basic Python Traing Manual

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}

union_set = set1.union(set2) # Union of two sets


intersection_set = set1.intersection(set2) # Intersection of two sets
difference_set = set1.difference(set2) # Set difference (elements in set1 but not in
symmetric_difference_set = set1.symmetric_difference(set2) # Symmetric difference

Excercise Common Use Cases:

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 [ ]: # Removing duplicates from a list


numbers = [1, 2, 2, 3, 4, 4, 5]

In [ ]: unique_numbers = list(set(numbers))

# Checking for common elements


set1 = {1, 2, 3, 4, 5}
set2 = {4, 5, 6, 7, 8}
common_elements = set1.intersection(set2)

File Handling

Reading and Writing Files


A file is a container in computer storage devices used for storing data.

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.

Hence, in Python, a file operation takes place in the following order:

1. Open a file
2. Read or write (perform operation)
3. Close the file

Opening Files in Python

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 34/50


3/15/24, 7:25 AM Basic Python Traing Manual

The open() Python method is the primary file handling function. The basic syntax is:

**file_object = open('file_name', 'mode')**


The open() function takes two elementary parameters for file handling:

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:

In [ ]: file1 = open("file.txt") # equivalent to 'r' or 'rt'


file1 = open("file.txt",'w') # write in text mode

Reading from a File:

We can read the contents of a file using various methods:

1. Using read(): Reads the entire file content into a string.

In [ ]: with open('file.txt', 'r') as file:


file_content = file.read()
print(file_content)

1. Using readline(): Reads one line at a time`

In [ ]: with open('file.txt', 'r') as file:


line = file.readline()
while line:
print(line, end='')
line = file.readline()

1. Using readlines(): Reads all lines into a list.

In [ ]: with open('file.txt', 'r') as file:


lines = file.readlines()
for line in lines:
print(line, end='')

Write to a file
There are two methods of writing to a file in Python, which are:

1. write()
2. writelines()

1. Using write(): Writes a string to the file.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 35/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [ ]: with open('file.txt', 'w') as file:


file.write('Hello, world!')

Using writelines(): Writes a list of strings to the file.

In [ ]: lines = ['Line 1\n', 'Line 2\n', 'Line 3\n']


with open('file.txt', 'w') as file:
file.writelines(lines)

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 [ ]: with open("any.csv", 'r') as file:


file.readlines()
print(file)

In [ ]: x = input("Enter the number")


y = int(x)
print(y)

Python try...except Block


The try...except block is used to handle exceptions in Python. Here's the syntax of try...except
block:

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}")

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 36/50


3/15/24, 7:25 AM Basic Python Traing Manual

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.

Handling Multiple Exceptions:


You can handle different types of exceptions by specifying multiple except blocks for each
exception type.

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}")

In [ ]: # 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")

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.")

Handling Exceptions in file


localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 37/50
3/15/24, 7:25 AM Basic Python Traing Manual

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}")

Using else and finally Blocks:


You can use else and finally blocks in combination with try-except blocks when working with
files.

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.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 38/50


3/15/24, 7:25 AM Basic Python Traing Manual

Classes serve as blueprints for creating objects, and objects are instances of these classes.

Major principles of object-oriented programming system are given below.

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)

In [ ]: fname = input("Your First name:")


lname = input("Your last name:")
age = input("Age:")
person1 = Person(fname,lname, age)
person2 = Person("Aster", "Alemu", 12)
person3 = Person("Hana", "Yohannes", 45)

person3.greet()

Creating Objects (Instances):


An object is a particular instance of a class with unique characteristics and functions. After a
class has been established, you may make objects based on it.

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.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 39/50


3/15/24, 7:25 AM Basic Python Traing Manual

Once we have defined a class, we can create objects (instances) of that class using the class
name followed by parentheses.

Syntax:

In [ ]: # Declare an object of a class


object_name = Class_Name(arguments)

In [ ]: class Student:
fname = "Kedir"
def info(self):
print(f"{self.fname} is a student")
stud1 = Student()
stud1.info()

In [ ]: person = Person("Kelemu", 30)


person.greet()

Attributes:

attributes are variables that hold data associated with an object. They represent the object's
state. There are two types of attributes:

Instance attribute and,


Class attribute

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

person1 = Person("Yasin", 30)


person2 = Person("Sara", 21)
print(person1.name)
print(person2.age)

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

def __init__(self, radius):


self.radius = radius # Instance attribute
def area(self):
return self.pi * self.radius ** 2

circle1 = Circle(2)

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 40/50


3/15/24, 7:25 AM Basic Python Traing Manual
circle2 = Circle(3)
circle3 = Circle(20)
area1 = circle1.area()
area2 = circle2.area()
area3 =circle3.area()
print("The first circle area = ", area1)
print("The second circle area = ", area2)
print("The third circle area = ", area3)

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

name, age, salary = get_data(1)


emp1 = Employee(name, age, salary)
name, age, salary = get_data(2)
emp2 =Employee(name, age, salary)
name, age, salary = get_data(3)
emp3 =Employee(name, age, salary)

emp1.get_info()
emp2.get_info()
emp3.get_info()

OOP Concepts in Python

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.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 41/50


3/15/24, 7:25 AM Basic Python Traing Manual

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 derived-class(base class):


<class-suite>

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")

print(dog.speak()) # Output: "jack says Woof!"


print(cat.speak()) # Output: "tomy says Meow!"

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.

In [ ]: #import abstract base class library


from abc import ABC, abstractmethod

class Shape(ABC):
@abstractmethod
def area(self):
pass

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 42/50


3/15/24, 7:25 AM Basic Python Traing Manual
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

shapes = [Circle(2), Square(4)]

for shape in shapes:


print(f"Area: {shape.area()}")

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 Python, polymorphism is demonstrated through method overriding. Method overriding


occurs when a subclass provides a specific implementation of a method that is already defined
in its superclass. This allows different objects to respond differently to the same method call.

The word "polymorphism" means "many forms", and in programming it refers to


methods/functions/operators with the same name that can be executed on many objects or
classes.

In [ ]: x = "Hello World!"
#For strings len() returns the number of characters:
print(len(x))

mytuple = ("apple", "banana", "cherry")


#For tuples len() returns the number of items in the tuple:
print(len(mytuple))

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

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 43/50


3/15/24, 7:25 AM Basic Python Traing Manual

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

shapes = [Circle(2), Square(4)]

for shape in shapes:


print(f"Area: {shape.area()}")

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!")

car1 = Car("Ford", "Mustang") #Create a Car class


boat1 = Boat("Ibiza", "Touring 20") #Create a Boat class
plane1 = Plane("Boeing", "747") #Create a Plane class

for x in (car1, boat1, plane1):


x.move()

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):

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 44/50


3/15/24, 7:25 AM Basic Python Traing Manual
print("Ethiopia is a developing country.")

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!")

car1 = Car("Ford", "Mustang") #Create a Car object


boat1 = Boat("Ibiza", "Touring 20") #Create a Boat object
plane1 = Plane("Boeing", "747") #Create a Plane object

for x in (car1, boat1, plane1):


print(x.brand)
print(x.model)
x.move()

Encapsulation

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 45/50


3/15/24, 7:25 AM Basic Python Traing Manual

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

def set_name(self, name):


self._name = name

person = Person("Saron", 30)


print(person.get_name()) # Accessing a protected attribute

# This will raise an error because __age is private


# print(person.__age)

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.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 46/50


3/15/24, 7:25 AM Basic Python Traing Manual

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.

Using the re Module:

In Python, regular expressions are commonly used with the re module, which provides functions
and methods for working with regex patterns.

You can start using regular expressions by importing the re module:

In [ ]: import re

Basic Regular Expression Patterns:

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.

Metacharacters: Regular expressions contain special metacharacters like . (matches any


character except a newline), * (matches 0 or more repetitions), + (matches 1 or more
repetitions), ? (matches 0 or 1 repetition), and more.

Using the re.search() Function:

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

text = "Hello, world!"


pattern = r"world"

match = re.search(pattern, text)


print(match)
if match:
print("Match found:", match.group()) # Output: "world"
else:
print("No match found")

In [ ]:

Using the re.findall() Function:

The re.findall() function returns all non-overlapping matches of a pattern in a string as a list of
strings.

In [ ]: import re

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 47/50


3/15/24, 7:25 AM Basic Python Traing Manual
text = "The 5sun is shining, and the ^$ _) @# birds are singing."
pattern = r"\b\S+\b" # Matches words
matches = re.findall(pattern, text)

print("Matches:", matches)
# Output: ['The', 'sun', 'is', 'shining', '-and', 'the', 'birds', 'are', 'singing']

Using Regular Expression Flags:

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:

.: Matches any character except a newline.


*: Matches 0 or more repetitions of the preceding pattern.
+: Matches 1 or more repetitions of the preceding pattern.
?: Matches 0 or 1 repetition of the preceding pattern.
^: Matches the start of a string.
$: Matches the end of a string.
[]: Character class, matches any character inside the brackets.
|: Alternation, matches either the pattern on the left or the pattern on the right.
(): Capturing group, groups parts of the pattern together and captures the matched text.
{}: Specifies the number of repetitions, like {2,4} to match 2 to 4 occurrences.

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.

Here's how to perform pattern matching in Python:

Import the re Module:

1. First, import the re module to access the regular expression functions.

In [ ]: import re

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 48/50


3/15/24, 7:25 AM Basic Python Traing Manual

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 [ ]: pattern = r'\d+' # Matches one or more digits

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.

In [ ]: text = "There are 123 apples and 456 oranges."


match = re.search(pattern, text)

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.

In [ ]: matches = re.findall(pattern, text)


print("Matches:", matches) # Output: ["123", "456"]

1. Extract Matched Groups: Regular expressions can include capturing groups using
parentheses. You can use match.group(index) to access specific capturing groups.

In [ ]: pattern = r'(\d+) (\w+)'


match = re.search(pattern, "There are 123 apples.")

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.

In [ ]: for match in re.finditer(pattern, text):


print("Match:", match.group())

1. Replace Matches: You can use the re.sub() function to replace matches with a specified
string.

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 49/50


3/15/24, 7:25 AM Basic Python Traing Manual

In [ ]: text = "There are 123 apples and 456 oranges."


pattern = r'\s+'
updated_text = re.sub(pattern, ",", text)
print("Updated text:", updated_text) # "There are 999 oranges."

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"]

Common Functions and Methods:


The re module provides several functions and methods for working with regular expressions:

re.search(pattern, string, flags=0): Searches for a pattern in a string. Returns a match


object or None if no match is found.
re.match(pattern, string, flags=0): Matches the pattern at the beginning of the string.
Returns a match object or None if no match is found.
re.findall(pattern, string, flags=0): Finds all occurrences of the pattern in a string and
returns them as a list of strings.
re.finditer(pattern, string, flags=0): Returns an iterator that yields match objects for all
occurrences of the pattern in the string.
re.sub(pattern, replacement, string, count=0, flags=0): Replaces all occurrences of the
pattern in the string with the specified replacement string.
re.compile(pattern, flags=0): Compiles a regular expression pattern into a regular
expression object, which can be used for multiple pattern matching operations.

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")

localhost:8888/nbconvert/html/Basic Python Traing Manual.ipynb?download=false 50/50

You might also like