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

DigitalSkills&Python_Chapter5

The document provides an overview of Python programming, focusing on data structures, particularly sets, and their operations, as well as functions and their definitions. It explains the characteristics of sets, including their unordered nature, uniqueness of elements, and methods for adding, removing, and performing operations on sets. Additionally, it covers the structure and usage of functions in Python, including parameters, arguments, and different ways to define and call functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
1 views

DigitalSkills&Python_Chapter5

The document provides an overview of Python programming, focusing on data structures, particularly sets, and their operations, as well as functions and their definitions. It explains the characteristics of sets, including their unordered nature, uniqueness of elements, and methods for adding, removing, and performing operations on sets. Additionally, it covers the structure and usage of functions in Python, including parameters, arguments, and different ways to define and call functions.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 76

Digital Skills and Python Programming

Chapter 5
Python Overview and Basic Syntax:
Python Data Structures: Set
Python Functions & Modules
Python Exception Handling

Pr. Mehdia AJANA


Email: [email protected]
Definition & Syntax
PYTHON • Sets are also used to store multiple items in a
single variable.
First steps • A set is an unordered collection of unique
elements.
• Sets are written with curly brackets { }
Example:
Create and print a set:
>>> thisset = {"apple", "banana", "cherry"}
Data Structures >>> print(thisset)
Set {'cherry', 'banana', 'apple'}
• Set items are unordered, unchangeable, and do
not allow duplicate values.
Unordered:
• The items in a set do not have a defined order.
• Set items can appear in a different order every
time you use them
• Set items cannot be referred to by index or key
Pr. Mehdia AJANA 2
Definition & Syntax
PYTHON Unchangeable:
First steps Once a set is created, you cannot change its items,
but you can remove items and add new items

Duplicates Not Allowed:


Sets cannot have two items with the same value.
Duplicate values will be ignored
Data Structures >>> thisset = {"apple", "banana", "cherry",
Set "apple"}
>>> print(thisset)
{'banana', 'cherry', 'apple'}

Set items can be of any data type:


set1 = {"apple", "banana", "cherry"}
set2 = {1, 5, 7, 9, 3}

Pr. Mehdia AJANA 3


Definition & Syntax
PYTHON A set can contain different data types
First steps set1 = {"abc", 34, True, 40, "male"}

True and 1 is considered the same value


False and 0 is considered the same value
Example:
Data Structures >>> set1={"hello", False, 1, "Hi", True, 0}
>>> set1
Set
{False, 1, 'Hi', 'hello'}

Pr. Mehdia AJANA 4


Access Set Items
PYTHON You cannot access items in a set by referring to an index
or a key.
First steps But you can loop through the set items using a for loop, or
ask if a specified value is present in a set, by using the in
keyword.
Example:
Loop through the set, and print the values:
>>> thisset = {"apple", "banana", "cherry"}
>>> for x in thisset:
Data Structures
print(x)
Set banana
cherry
apple
Check if "banana" is present in the set:
>>> print("banana" in thisset)
True
Check if "banana" is NOT present in the set
>>> print("banana" not in thisset)
False
Pr. Mehdia AJANA 5
Add Set Items
PYTHON Once a set is created, you cannot change its items, but
First steps you can add new items.
To add one item to a set use the add() method.
Example:
Loop through the set, and print the values:
>>> thisset = {"apple", "banana", "cherry"}
>>> thisset.add("orange")
Data Structures >>> print(thisset)
{'orange', 'banana', 'apple', 'cherry'}
Set
To add items from another set into the current set, use
the update() method
>>> thisset = {"apple", "banana", "cherry"}
>>> tropical = {"pineapple", "mango", "papaya"}
>>> thisset.update(tropical)
>>> print(thisset)
{'apple', 'mango', 'cherry', 'pineapple', 'banana', 'papaya'}

Pr. Mehdia AJANA 6


Add Set Items
PYTHON • The update() method can also be used to add
First steps elements from another iterable (data
collection data type) like a list, or a tuple to
the set.
• The set is automatically updated with unique
elements.
Example:
Data Structures
my_set = {1, 2, 3}
Set
my_set.update([4, 5]) # adding a list
my_set.update((4,6)) # adding a tuple
print(my_set)

{1, 2, 3, 4, 5, 6}

Pr. Mehdia AJANA 7


Remove Set Items
PYTHON To remove an item in a set, use the remove(), or
First steps the discard() method.
Example:
>>> thisset = {"apple", "banana", "cherry"}
>>> thisset.remove("banana")
#we can also use thisset.discard("banana")
Data Structures >>> print(thisset)
Set
{'cherry', 'apple'}

• If the item to remove does not exist:


• remove() will raise an error
• discard() will NOT raise an error

Pr. Mehdia AJANA 8


Remove Set Items
PYTHON You can also use the pop() method to remove
First steps an item, but this method will remove a random
item since sets are unordered, so you cannot be
sure what item gets removed.
The return value of the pop() method is the
removed item:
>>> thisset = {"apple", "banana", "cherry"}
Data Structures
>>>x = thisset.pop()
Set
>>>print(x)
>>>print(thisset)

apple
{'cherry', 'banana'}

Pr. Mehdia AJANA 9


Remove Set Items
PYTHON
First steps The clear() method empties the set:
>>> thisset = {"apple", "banana", "cherry"}
>>> thisset.clear()
>>> print(thisset)

Data Structures set()


Set
The del keyword will delete the set completely:
>>> thisset = {"apple", "banana", "cherry"}
>>> del thisset
>>>print(thisset) #this will raise an error
because the set no longer exists

Pr. Mehdia AJANA 10


Set Operations:
PYTHON
Sets Union
First steps We can use the union() method that returns a
new set with all items from other sets
>>> set1 = {"a", "b", "c"}
>>> set2 = {1, 2, 3}
>>> set3 = {"John", "Elena"}
Data Structures >>> myset = set1.union(set2, set3)
Set >>> print(myset )
{1, 2, 3, 'Elena', 'b', 'c', 'a', 'John'}

We can use the | operator (the pipe symbol)


instead of the union() method, and we will get
the same result
>>> myset = set1 |set2 | set3
Pr. Mehdia AJANA 11
Sets Union
PYTHON The union() method allows you to join a set with
First steps other data types, like lists or tuples. The result
will be a set.
Example: Join a set with a tuple
>>> x = {"a", "b", "c"} # Set
>>> y = (1, 2, 3) #Tuple
Data Structures >>> z = x.union(y)
Set >>> print(z)

{3, 1, 2, 'a', 'b', 'c'}

Pr. Mehdia AJANA 12


Sets Intersection:
PYTHON Returns elements that are present in both sets.
First steps Syntax: set1 & set2 or set1.intersection(set2)
Example:
set1 = {1, 2, 3}
set2 = {3, 4, 5}
intersection_set = set1 & set2 # Result: {3}
Data Structures Sets Difference:
Set Returns elements that are in the first set but not
in the second.
Syntax: set1 - set2 or set1.difference(set2)
Example:
difference_set = set1 - set2
# Result: {1, 2}

Pr. Mehdia AJANA 13


Sets Symmetric Difference:
PYTHON symmetric_difference() method returns
First steps elements that are in either of the sets, but not
in both.
Syntax: set1 ^ set2 or
set1.symmetric_difference(set2)
Example:
Data Structures set1 = {1, 2, 3}
set2 = {3, 4, 5}
Set
print(set1.symmetric_difference(set2))
# {1, 2, 4, 5}
print(set1.difference(set2))
# {1, 2}

For more detailed examples and explanations of Set


operations, you can refer to :
https://www.geeksforgeeks.org/sets-in-python/
Pr. Mehdia AJANA 14
Summary of Set Methods
PYTHON Method Operator Description

First steps add()


clear()
Adds an element to the set
Removes all the elements from the set

copy() Returns a copy of the set


Returns a set containing the difference
difference() - between two or more sets

discard() Remove the specified item


Data Structures Returns a set, that is the intersection of two
intersection() & other sets

pop() Removes an element from the set


Set remove() Removes the specified element

symmetric_dif Returns a set with the symmetric differences of


ference() ^ two sets

union() | Returns a set containing the union of sets


Updates a set by adding items from another set
update() |= (or any other iterable)
For more examples about Set methods you can check the
following link: https://www.geeksforgeeks.org/python-set-
methods/
Pr. Mehdia AJANA 15
Summary of Data Structures
PYTHON • Lists and tuples are for ordered collections, but lists
First steps are mutable, and tuples are not.
• Dictionaries store key-value pairs, ideal for mapping
data.
• Sets store unique values and are great for eliminating
duplicates and performing multiple set operations.

Data Structures
Summary

Pr. Mehdia AJANA 16


PYTHON What is a Function?
First steps A function is a block of organized, reusable
code that performs a specific task.

Why Use Functions?

Functions Reusability: Write once, use multiple times.

Definition Organization: Break down complex problems


into smaller pieces.

Readability: Makes code easier to read and


maintain.

17
Pr. Mehdia AJANA
Function Structure
PYTHON In Python a function is defined using the def
First steps keyword.
def function_name(parameters):
""" This is a docstring.It explains
what the function does.
"""
Functions # Block of code
return value
Definition def: Keyword to define a function.
function_name: The name of the function.
parameters: Optional, input values the function can
accept.
Docstring: Optional description of what the
function does.
return: The output that the function gives back.
18
Pr. Mehdia AJANA
Creating and Calling a Function
PYTHON
You can pass data, known as
First steps parameters/arguments, into a function.
You can add as many parameters as you want,
just separate them with a comma (,).
A function can return data as a result.
Functions Python allows the creation of:
• A function without parameters and without a
Definition return value.
• A function without parameters but with a
return value(s).
• A function with parameter(s) and without a
return value.
• A function with parameter(s) and with a return
value(s).
19
Pr. Mehdia AJANA
PYTHON Example: Simple Function

First steps def greet():


""" This function prints
a greeting message.
"""
Functions print("Hello, welcome to Python!")

Definition To call the function, we use the function


name followed by parenthesis:
greet()

# Output: Hello, welcome to Python!

20
Pr. Mehdia AJANA
PYTHON Example: function with one parameter:

First steps Parameters are specified after the function


name, inside the parentheses. You can add as
many parameters as you want, just separate
them with a comma (,).
def greet(fname):
Functions print("Hello "+fname)

Definition greet("Ali")
greet("Ahmed") Hello Ali
Hello Ahmed
greet("Iyad") Hello Iyad

21
Pr. Mehdia AJANA
PYTHON Parameters or Arguments?

First steps From a function's perspective:


• A parameter is the variable listed inside the
parentheses in the function definition.
• An argument is the value that is sent to the
function when it is called.
• Arguments are often shortened to args in
Functions Python documentations.

Python offers a wide range of built-in functions


(e.g. len(), append(), clear()…) and allows a
programmer to create their own to meet the goals
of the program being developed and to organize it
better.

22
Pr. Mehdia AJANA
Number of Arguments
PYTHON
By default, a function must be called with the
First steps correct number of arguments.
If your function expects 2 arguments, you have to
call the function with 2 arguments, not more, and
not less.
Example:
This function expects 2 arguments, and gets 2
arguments:
def full_name(fname, lname):
Functions print(fname + " " + lname)

full_name("Ali", "Alaoui")
Ali Alaoui
If you try to call the function with 1 or 3 arguments,
you will get an error:
full_name("Ali")
TypeError: full_name() missing 1 required
positional argument: 'lname'
23
Pr. Mehdia AJANA
Positional Arguments
PYTHON
The arguments passed to the function are assigned
First steps to the parameters based on their position in the
function call.
So, the order of the arguments in the function call
is important.
Example:
def greet_user(name, age):
Functions print(f"Hello, {name}! You are {age} years
old.")
greet_user("Ali", 25)

# Output: Hello, Ali! You are 25 years old.

In the function call, "Ali" is assigned to the name


parameter and 25 is assigned to the age parameter.
Pr. Mehdia AJANA 24
Keyword Arguments
PYTHON
You can also specify the argument name in the
First steps function call by sending arguments with the key =
value syntax.
This makes it clear what each argument represents,
and the order of the arguments does not matter.
Example:
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
Functions
my_function(child1 = "Ali", child2 = "Ahmed",
child3 = "Iyad")

The youngest child is Iyad

Keyword Arguments are often shortened to kwargs


in Python documentations.
25
Pr. Mehdia AJANA
Default Parameters
PYTHON
You can use a default parameter value.
First steps
If we call the function without argument, it
uses the default value:
def greet(fname="Guest"):
print("Hello " + fname)

Functions greet()
# Output: Hello Guest

greet("Ali")
# Output: Hello Ali

If no argument is provided during the function


call, the default value Guest is used.
26
Pr. Mehdia AJANA
Passing a List as an Argument
PYTHON
You can send any data types of argument to a
First steps
function (string, number, list, dictionary etc.),
and it will be treated as the same data type
inside the function.
E.g. if you send a List as an argument, it will still
Functions be a List when it reaches the function:
def my_function(food):
for x in food:
print(x)

fruits = ["apple", "banana", "cherry"]


my_function(fruits)
apple
banana
cherry
27
Pr. Mehdia AJANA
Variable-Length Arguments in Python
PYTHON
Python allows functions to accept a variable
First steps number of arguments.
This is useful when the number of inputs is not
known in advance.
There are two main ways to use variable
Functions arguments in Python:
*args allows you to pass a variable number of
positional arguments to a function.
Inside the function, args is a tuple:
def greet(*args):
for name in args:
Hello Ali
print(f"Hello, {name}!") Hello Ahmed
greet("Ali", “Ahmed", “Iyad") Hello Iyad

Pr. Mehdia AJANA 28


PYTHON Variable-Length Arguments in Python

First steps **kwargs allows you to pass a variable


number of keyword arguments (name-value
pairs).
Inside the function, kwargs is a dictionary:
def display_info(**kwargs):
for key, value in kwargs.items():
Functions print(f"{key}:{value}")
display_info(name="Ali",age=30,
profession="Engineer")
name: Ali
age: 30
profession: Engineer

29
Pr. Mehdia AJANA
PYTHON Combining *args and **kwargs
You can use both *args and **kwargs together
First steps in the same function to handle both positional
and keyword arguments.
def person_details(*args, **kwargs):
print("Positional Arguments:", args)
print("Keyword Arguments:", kwargs)
Functions
person_details("Ali", "Alaoui",30,
profession="Engineer", city="Tangier")

Positional Arguments: ('Ali', 'Alaoui', 30)


Keyword Arguments: {'profession': 'Engineer', 'city':
'Tangier'}

Pr. Mehdia AJANA 30


Return Values
PYTHON
To let a function return a value, use the return
First steps statement:

Example:
def square(number):
return number ** 2

Functions print(square(4)) # Output: 16


print(square(2)) # Output: 4
print(square(3)) # Output: 9

The function square takes a number as input


and returns its square.

31
Pr. Mehdia AJANA
Return Multiple Values
PYTHON
A function can return multiple values as a tuple.
First steps The get_coordinates() function returns two values:
x and y, packaged as a tuple.
The tuple is then unpacked into x_coord and
y_coord for easy access.
def get_coordinates():
Functions x = 10
y = 20
return x, y
x_coord, y_coord = get_coordinates()
print(x_coord, y_coord) # Output: 10 20
print(get_coordinates()) #Output: (10,20)

32
Pr. Mehdia AJANA
PYTHON Return Multiple Values
The function calculate_operations performs three
First steps calculations and returns all three results as a tuple,
which can be unpacked into individual variables:
def calculate_operations(a, b):
addition = a + b
subtraction = a - b
Functions multiplication = a * b
return addition, subtraction, multiplication
add, sub, mul = calculate_operations(10, 5)
print(f"Addition: {add}, Subtraction: {sub},
Multiplication: {mul}")
# Output: Addition: 15, Subtraction: 5,
Multiplication: 50
33
Pr. Mehdia AJANA
PYTHON Function Calling Another Function
In Python, a function can call another function
First steps within its definition. This allows functions to
interact and break down complex tasks into
smaller, manageable parts:
def multiply_by_two(x):
return x * 2
Functions
def add_and_multiply(a, b):
sum_value = a + b
return multiply_by_two(sum_value)
result = add_and_multiply(3, 4)
print(result) # Output: 14
34
Pr. Mehdia AJANA
Recursion
PYTHON Python also accepts function recursion, which
First steps means a defined function can call itself.
You should be very careful with recursion as you
can write a function which never terminates uses
excess amounts of memory or processor power
Example:
def countdown(n):
Functions
if n == 0:
5
print("Done!")
4
else:
3
print(n)
2
countdown(n - 1)
1
Done!
countdown(5)

Pr. Mehdia AJANA 35


PYTHON Lambda Functions in Python

First steps • Lambda functions are small, anonymous


functions in Python.
• They are defined using the lambda keyword.
• A lambda function can have any number of
arguments, but only one expression.
Functions The syntax for a lambda function is:
lambda arguments: expression

They are typically used for short, simple


functions that are only needed temporarily.

36
Pr. Mehdia AJANA
PYTHON Lambda Functions in Python

First steps Example: Lambda Function with Two


Arguments
# A lambda function that adds two numbers
add = lambda x, y: x + y
# Calling the lambda function
Functions result = add(5, 10)
print(result) # Output: 15
In this example:
lambda x, y: x + y creates a function that takes
two arguments x and y and returns their sum.

37
Pr. Mehdia AJANA
PYTHON What is Variable Scope?

First steps Definition: The scope of a variable


determines where in the code it is accessible.

Functions • Local Variables: Defined inside a function


Global and only accessible within that function.
and
• Global Variables: Defined outside all
Local Variables
functions and accessible throughout the
entire program.

38
Pr. Mehdia AJANA
PYTHON Local Variables

First steps • Defined inside a function.


• Only accessible within that function.
• Created when the function is called and
destroyed when the function ends.
Functions
Global Example:
and def display():
Local Variables y = 5 # Local variable
print(y)

display() # Output: 5
print(y) # Error: y is not defined

39
Pr. Mehdia AJANA
Global Variables
PYTHON
• Defined outside of any function.
First steps
• It can be accessed both inside and outside
functions.
• Useful for sharing data across different
Functions functions.
Global Example:
and
Local Variables x = 10 # Global variable

def display():

print(x) # Access global variable

display() # Output: 10

print(x) #Output: 10
40
Pr. Mehdia AJANA
Naming Variables
PYTHON
• If you use the same variable name inside and
First steps outside of a function, Python will treat them as
two separate variables
• One available in the global scope (outside the
function) and one available in the local scope
Functions (inside the function)
Example: The function will print the local x, and
Global then the code will print the global x:
and x = 300
Local Variables def myfunction():
x = 200
print(x)
myfunction()
print(x)

200
300
41
Pr. Mehdia AJANA
Using The global Keyword
PYTHON
• Python does not allow modifying a global
First steps variable inside a function.
• To change the value of a global variable inside a
function, refer to the variable by using the
global keyword.
Functions
Example:
Global
and x = 10 # Global variable
Local Variables def modify_global():
global x
x = 20 # Modify global variable
modify_global()
print(x) # Output: 20
Pr. Mehdia AJANA 42
The nonlocal Keyword:
PYTHON
• The nonlocal keyword is used to work with
First steps variables inside nested functions.
• The nonlocal keyword makes the variable
belong to the outer function.
Example: If you use the nonlocal keyword, the
Functions variable will belong to the outer function:
Global def myfunc1():
x = "Jane"
and
Local Variables def myfunc2():
nonlocal x
x = "hello"

myfunc2()
return x

print(myfunc1())
hello
Pr. Mehdia AJANA 43
PYTHON Local vs Global vs Nonlocal

First steps • Local: Variables defined within a function.

• Global: Variables defined outside all


functions, accessible everywhere.
Functions
Global • Nonlocal: Used in nested functions. Variables
and defined in an outer function, modified by an
Local Variables inner function.

Pr. Mehdia AJANA 44


PYTHON What is a Module?

First steps Definition: A module is a file that contains


Python code (set of functions, variables,
classes) that can be reused in other
programs/applications.
Modules help in organizing code logically and
make it easier to maintain and reuse.
Python Modules
Definition Types of Modules:
• User-defined Modules: Created by the user
to organize and reuse code.
• Built-in Modules: Pre-installed modules
provided by Python, offering a wide range
of functionality.

Pr. Mehdia AJANA 45


User-defined Modules
PYTHON 1. Create a module:
First steps You can create your own module by writing
Python code and saving it as a .py file.
Save this code in a file named mymodule.py:
# File: my_module.py
def greet(name):
Python Modules print("Hello, " + name)
Definition 2. Use a Module
Now we can import and use the module we
just created in another file, by using the import
statement and calling the greet function:
# Main script file: main.py
import mymodule
mymodule.greet("Ali") # Hello Ali

Pr. Mehdia AJANA 46


Variables in Module
PYTHON
The module can contain functions, as already
First steps described, but also variables of all types (strings,
lists, tuples, dictionaries, objects etc. ):

Example:
person1 = {
Python Modules "name": “Ali",
Variables in a "age": 36,
"country": “Morocco"
Module }
This code can be saved as a module mymodule.py
and then be used as:
import mymodule
a = mymodule.person1["age"]
print(a)
36
Pr. Mehdia AJANA 47
Naming a Module
PYTHON
You can name the module file whatever you
First steps like, but it must have the file extension .py
Re-naming a Module:
You can create an alias when you import a
Python Modules module, by using the as keyword:
Naming a Example:
Module Create an alias for mymodule called mx:

import mymodule as mx

a = mx.person1["age"]
print(a)
36
48
Pr. Mehdia AJANA
Import from Module
PYTHON
You can combine multiple functions and
First steps variables in a single module.
Example:
The module named mymodule has one
function and one dictionary:
def greeting(name):
Python Modules
print("Hello, " + name)
Import from a
Module person1 = {
"name": "Ali",
"age": 36,
"country": "Morocco"
}

49
Pr. Mehdia AJANA
Import from Module
PYTHON
First steps You can choose to import only parts from a
module, by using the from keyword.
from mymodule import person1
print (person1["age"])
Python Modules When importing using the from keyword, do
Import from a not use the module name when referring to
elements in the module. Example:
Module
person1["age"], not
mymodule.person1["age"]
We can use from mymodule import * to
import all elements of a module

50
Pr. Mehdia AJANA
Built-in Modules in Python
PYTHON
Python provides many built-in modules that are
First steps ready to use, which you can import whenever
you like.

Commonly Used Built-in Modules:


Python Modules • math: Provides mathematical functions.
Built-in
Modules • datetime: For working with dates and times.

• random: For generating random numbers.

• os: For interacting with the operating


system.

Pr. Mehdia AJANA 51


Using Built-in Modules
PYTHON The math Module:
First steps Python math module extends the list of
mathematical functions.
To use it, you must import the math module, then
you can start using methods and constants of the
module :
Python Modules import math
Built-in x = math.sqrt(64) 8.0
Modules y = math.pi 3.141592653589793
print(x)
print(y)

You can check a comprehensive list of functions


provided by the math module here:
https://docs.python.org/3/library/math.html
Pr. Mehdia AJANA 52
PYTHON Using Built-in Modules
The datetime Module:
First steps A date in Python is not a data type of its own, but
we can import a module named datetime to work
with dates as date objects.
Example:
Import the datetime module and display the
current date:
Python Modules import datetime as dt
Built-in # Get the current date and time
Modules now = dt.datetime.now()
print(now)

2024-10-21 08:34:07.533548

The output date contains year, month, day, hour,


minute, second, and microsecond.

Pr. Mehdia AJANA 53


Using Built-in Modules
PYTHON The datetime Module:
First steps Return the year of the current date:
import datetime
now = datetime.datetime.now()
print(now.year)

2024
Python Modules
Built-in To create a date, we can use the datetime() class
Modules (constructor) which requires three parameters to
create a date: year, month, day:
import datetime
date1 = datetime.datetime(2024, 10, 21)
print(date1)

2024-10-21 00:00:00

Pr. Mehdia AJANA 54


Using Built-in Modules
PYTHON The datetime Module:
First steps The datetime object has a method for formatting
date objects called strftime():
The method takes one parameter, format, to
specify the format of the returned string:
To display the name of the month:
Python Modules import datetime
date1 = datetime.datetime(2024, 10, 21)
Built-in
print(date1.strftime("%B")) #Display the month
Modules name
print(date1.strftime("%A")) #Display the weekday
October
Monday
You can check a comprehensive list of objects and
functions provided by the datetime module, and also a
reference of all the legal format codes here:
https://docs.python.org/3/library/datetime.html
Pr. Mehdia AJANA 55
Using Built-in Modules:
PYTHON The random Module:
Random numbers are crucial in various scenarios,
First steps such as generating test data, simulating events…
The Python Random module offers several
functions to generate random numbers with
different characteristics:
import random
Python Modules #generate a random float between 0.0 (inclusive)
and 1.0 (exclusive)
Built-in
random_number1 = random.random()
Modules print(random_number1)
0.549570292983532

#generate random integers between 1 and 10


(both inclusive)
random_number2 = random.randint(1, 10)
print(random_number2)
8 Pr. Mehdia AJANA 56
Using Built-in Modules
PYTHON
The random Module:
First steps #randomly select an element from a list
import random as rd

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

Python Modules random_number_list = rd.choice(numbers)


Built-in print(random_number_list)
Modules
2

You can check other methods of the random


module here:
https://docs.python.org/3/library/random.html

Pr. Mehdia AJANA 57


Using Built-in Modules
PYTHON
The os Module:
First steps Python has a built-in os module with methods for
interacting with the operating system:
e.g. creating files and directories, management of
files and directories, input, output, environment
variables, process management…
Python Modules Example:
Built-in The os.remove(path) method removes (deletes) a
Modules file at the given path:
import os
os.remove("example.txt")
# Deletes the file 'example.txt'

58
Pr. Mehdia AJANA
Using Built-in Modules
PYTHON The os Module:
First steps The os.rmdir(path) method removes an empty
directory at the given path:

import os
os.rmdir("my_folder")
# Deletes the directory 'my_folder' (only if it's
Python Modules empty)
Built-in
We will use the above methods when we cover file
Modules handling in Python.

The os module has a large set of methods and


constants that you can explore here:
https://www.geeksforgeeks.org/os-module-python-
examples/

Pr. Mehdia AJANA 59


The dir() Function
PYTHON You can use the dir() function to list all functions,
First steps classes, and variables in an imported module:
Example:

import math

Python Modules print(dir(math))


Built-in # This will print a list of all functions,
Modules constants, etc. in the math module.

Example output:

['acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh',


'ceil', 'cos', 'cosh', 'fabs', 'factorial', 'floor',
'sqrt', 'pi' …. ]

Pr. Mehdia AJANA 60


Getting Documentation of Functions in a
PYTHON Module
First steps You can display the documentation of a module
and its specific functions using the help() function:
Example:
import math
# Get complete documentation for the entire
Python Modules math module
Built-in help(math)
Modules # Get documentation for a specific function,
e.g., 'sqrt‘
help(math.sqrt)

#Example output: Help on built-in function sqrt in


module math:
sqrt(x, /)
Return the square root of x.
Pr. Mehdia AJANA 61
What is Exception Handling?
PYTHON
When an error occurs, or exception as we call it,
First steps Python will normally stop and generate an error
message.

Definition: Exception handling is a mechanism to


respond to the occurrence of exceptions (errors)
in a program, allowing it to continue running or to
Python fail gracefully (using a personalized message for
Exception e.g.).
Handling Purpose:

• Prevents program crashes.

• Provides informative error messages.

• Enables cleanup actions before terminating a


program.

Pr. Mehdia AJANA 62


Common Exceptions in Python
PYTHON • ZeroDivisionError: Raised when dividing by
First steps zero. E.g. result = 10 / 0

• ValueError: Raised when a function receives an


argument of an inappropriate value: e.g. value
= int("abc")

• TypeError: Raised when an operation is applied


Python
to an object of inappropriate type. E.g.: result =
Exception "5" + 5
Handling
• IndexError: Raised when trying to access an
index that is out of range. E.g.: my_list[5]:
Index out of range if the list contains 2
elements

• FileNotFoundError: Raised when a file or


directory is requested but cannot be found.

Pr. Mehdia AJANA 63


Basic Exception Handling Syntax
PYTHON
Exceptions can be handled in Python using the try-
First steps except block:
try:
print(x)
except:
print("An exception occurred")
Python An exception occurred
Exception • The try block contains code that might raise an
Handling exception: x is not defined
• The except block defines how to handle the
exception: since the try block raises an error, the
except block will be executed.

Without the try block, the program will crash and


raise an error:
NameError: name 'x' is not defined

Pr. Mehdia AJANA 64


Multiple Exception Handling
PYTHON You can handle multiple exceptions using
First steps multiple except blocks.
Example: The program checks for two potential
exceptions: ValueError for invalid input and
ZeroDivisionError for division by zero:
try:
Python value = int(input("Enter a number: "))
Exception result = 10 / value
Handling print(f"The result is: {result}")
except ValueError:
print("Error: Please enter a valid
number.")
except ZeroDivisionError:
print("Error: Division by zero!")

Pr. Mehdia AJANA 65


Using else
PYTHON
You can use the else keyword to define a block
First steps of code to be executed if no errors were
raised:
Example:
Here, the try block does not generate any
error:
Python try:
Exception print("Hello")
Handling except:
print("Something went wrong")
else:
print("Nothing went wrong")
Hello
Nothing went wrong

66
Pr. Mehdia AJANA
Using finally
PYTHON The finally block always runs, regardless of whether
First steps an exception occurred or not.
Example:
try:
print(x)
except:
print("Something went wrong")
Python else:
Exception print("Nothing went wrong")
Handling finally:
print("The 'try except' is finished")
Something went wrong
The 'try except' is finished
The else block executes when no exceptions are
raised, while the finally block always runs: useful
for cleanup actions (e.g., closing a file if an error
occurred when reading from this file). 67
Raise an Exception
PYTHON As a Python developer you can choose to
First steps throw/raise an exception if a condition occurs and
then handled using a try-except block.
To raise an exception, use the raise keyword.
Example: Raise an error if the input age is negative:
age=int(input("Enter your age: "))
Python if age < 0:
Exception raise Exception("Age cannot be negative!")
else:
Handling
print(f"Your age is {age}.")
# For input: age=-5
Traceback (most recent call last): File
"<input>", line 3, in <module> Exception: Age
cannot be negative!
You can use the exception name after raise for
example: NameError, TypeError,
ZeroDivisionError… Pr. Mehdia AJANA 68
Raising ZeroDivisionError Exception
PYTHON In Python, you can raise a ZeroDivisionError when
First steps an attempt is made to divide by zero:

def divide(a, b):


if b == 0:
raise ZeroDivisionError("Division by zero is
Python not allowed!")
Exception # raise ZeroDivisionError
Handling return a / b
# Test
try:
result = divide(10, 0)
except ZeroDivisionError as e: #print the
exception message
print(f"An error occurred: {e}")
# Output: Division by zero is not allowed! 69
Raising Multiple Exceptions
PYTHON
Example function:
First steps

Python
Exception
Handling

Pr. Mehdia AJANA 70


Raising Multiple Exceptions
PYTHON Testing the Function with try and except:
First steps

Python
Exception
Handling

Result of 10 / 2 = 5.0
ZeroDivisionError: Division by zero is not allowed.
TypeError: The second argument must be a number.
TypeError: The first argument must be a number.
PYTHON Summary of Exception Handling
• Use try and except to handle exceptions
First steps gracefully.
• Handle multiple exceptions with separate
except blocks.
• Use else and finally for additional control flow:
• else block executes when no exceptions are
Python raised
Exception • finally block always runs, regardless of
Handling whether an exception occurred or not
• Raise is used to throw an exception manually to
handle specific cases in a more controlled
manner. The Exception should be handled after
using try-except.
You can check the documentation of Python built-in
exceptions here:
https://docs.python.org/3/library/exceptions.html
Pr. Mehdia AJANA 72
Exercise:
PYTHON
What will the following program print?:
First steps
def some_thing(number1, number2):

first_value = number1 + 8

second_value = number2 - 5

return first_value
Python
Functions some_thing(13, 10)

A. 5

B. 21

C. 18

D. None of the above.

Pr. Mehdia AJANA 73


Solution:
PYTHON
What will the following program print?:
First steps
def some_thing(number1, number2):

first_value = number1 + 8

second_value = number2 - 5

return first_value
Python
Functions some_thing(13, 10)

A. 5

B. 21

C. 18

D. None of the above: Although the function is


called, nothing is actually printed!
Pr. Mehdia AJANA 74
Exercise:
PYTHON
What will the following program print?:
First steps def some_thing(number1, number2):
first_value = number1 + 8
second_value = number2 - 5
temp_value = other_thing(second_value)
return temp_value
Python def other_thing(another_value):
Functions return (another_value + 5) * 3
some_thing(13, 10)
print(second_value)
A. 30
B. An error will occur.
C. 5
D. None of the above.
Pr. Mehdia AJANA 75
Solution:
PYTHON
What will the following program print?:
First steps def some_thing(number1, number2):
first_value = number1 + 8
second_value = number2 - 5
temp_value = other_thing(second_value)
return temp_value
Python def other_thing(another_value):
Functions return (another_value + 5) * 3
some_thing(13, 10)
print(second_value)

B. An error will occur: second_value is a local


variable defined inside the some_thing
function
Pr. Mehdia AJANA 76

You might also like