Info4 Chap5
Info4 Chap5
Functions
2024/2025
C.SAYAH
Python functions
What’s a function?
• A function is a block of reusable code that performs a specific task.
I created a simple function named greet() that prints Hello, Welcome to the
section L2 ST C!.
2
Creating a function in Python
3
Calling a function
• Creating a function doesn’t mean you are executing the code inside it. To do so you
have to call it using its name followed by parentheses.
4
Calling a function
• Code before the function call runs normally. When a function is called, the program
jumps into the function and executes its code.
• After the function finishes, the program continues with the next statement after
the function call.
5
Functions with parameters
6
Default values of parameters
• In Python, default values allow you to define parameters with a pre-set values. If a
function is called without providing a value for those parameters, the default
values are used.
• To set a default value, use the symbol = followed by the value placed immediately
after the parameter’s name in the function definition.
7
The return statement
8
Scope of variables
❖ A scope in Python refers to the region where a variable is defined and can be accessed.
There is two types of scope : global and local.
• Local scope
Variables declared inside a
function, accessible only
within that function.
• Global scope
Variables declared outside
any function, and can be
accessed inside or outside
the function.
9
Exercise : check even or odd
• Create a function called is_even that takes a single integer as parameter and
returns True if the number is even and False if it’s odd.
• If the user enters a negative number, return “invalid input”.
➢ Example of usage :
10
Exercise : check even or odd
Solution
11
Modules in Python
❖ A module in Python is simply a .py file that contains functions, variables and classes that
can be reused in other programs.
12
Modules in Python
❖ Renaming a module
You can rename a module using the keyword as followed by the alias. Aliases are useful to
shorten long module names.
13
Packages in Python
• A package is a collection of modules organized in a
directory. For Python to recognize a directory as a
package, it must contain a special file __init__.py.
• The __init__.py file can be empty or contain necessary
setup required for the package.
• The __init__.py file is always executed when you import a
package.
• Inside the folder, create Python files (.py extension) for each module.
• Create a file main.py outside the package folder, and import the package
so you can use its modules.
15
Thank you!
Do you have questions?