DigitalSkills&Python_Chapter5
DigitalSkills&Python_Chapter5
Chapter 5
Python Overview and Basic Syntax:
Python Data Structures: Set
Python Functions & Modules
Python Exception Handling
{1, 2, 3, 4, 5, 6}
apple
{'cherry', 'banana'}
Data Structures
Summary
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
20
Pr. Mehdia AJANA
PYTHON Example: function with one parameter:
Definition greet("Ali")
greet("Ahmed") Hello Ali
Hello Ahmed
greet("Iyad") Hello Iyad
21
Pr. Mehdia AJANA
PYTHON Parameters or Arguments?
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)
Functions greet()
# Output: Hello Guest
greet("Ali")
# Output: Hello Ali
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")
Example:
def square(number):
return number ** 2
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)
36
Pr. Mehdia AJANA
PYTHON Lambda Functions in Python
37
Pr. Mehdia AJANA
PYTHON What is Variable Scope?
38
Pr. Mehdia AJANA
PYTHON Local Variables
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():
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
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.
2024-10-21 08:34:07.533548
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
numbers = [1, 2, 3, 4, 5]
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.
import math
Example output:
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:
Python
Exception
Handling
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
first_value = number1 + 8
second_value = number2 - 5
return first_value
Python
Functions some_thing(13, 10)
A. 5
B. 21
C. 18