0% found this document useful (0 votes)
2 views28 pages

W3T2 - Functions

This document provides an overview of functions in Python, explaining their purpose, structure, and benefits such as reusability, modularity, and abstraction. It also distinguishes between global and local variables, detailing their scope, lifetime, and modification rules. Additionally, it includes activities to practice implementing functions and emphasizes the advantages of using functions for code organization and maintainability.

Uploaded by

polalar213
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views28 pages

W3T2 - Functions

This document provides an overview of functions in Python, explaining their purpose, structure, and benefits such as reusability, modularity, and abstraction. It also distinguishes between global and local variables, detailing their scope, lifetime, and modification rules. Additionally, it includes activities to practice implementing functions and emphasizes the advantages of using functions for code organization and maintainability.

Uploaded by

polalar213
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 28

Functions

Learning Goals

By the end of this lesson you will be able to:


o Understand what a function is and how it is used
o Use functions
What is a Function

 A function in Python is a reusable block of code that performs a specific


task.
 Functions help organize code into manageable, modular pieces, which can
be called (or invoked) from other parts of your program when needed.
Functions allow you to avoid repeating code and make your programs more
modular and easier to understand.

Example
Code:
Basic Structure of a Function

 def: This keyword is used to define a function.


 function_name: The name you give to your function. It should be descriptive
of what the function does.
 parameters: (Optional) Values you can pass into the function to customize
its behavior. Parameters are enclosed in parentheses and separated by
commas if there are multiple.
 return: (Optional) A statement that exits the function and optionally sends a
value back to the caller.
How to call a Function

Sample Function: Call Function: Output:


Functions with Parameters

Sample Function: Call Function: Output:


Function with Return Value

Sample Function: Call Function: Output:


Function with Default Parameters

Sample Function: Call Function: Output:

This function has a default parameter value. If no argument is


passed when the function is called, it uses the default value.
Function with Multiple Parameters

Sample Function:
Output:
Summary of Functions

 Reusability: Functions allow you to reuse code, which makes programs shorter and more readable.

 Modularity: Functions help break down complex problems into smaller, more manageable pieces.

 Abstraction: When you use a function, you don't need to know how it works internally—just what it
does and how to use it.

 Parameters: Functions can take parameters (input values) that allow you to pass data into them.

 Return Values: Functions can return values that can be used in other parts of your program.
Global Variable

Global Variable:
A global variable is a variable that is defined outside of any function and is accessible
throughout the entire program, including inside functions (unless shadowed by a local
variable with the same name). The scope of a global variable is the entire module or
script.

Characteristics of Global Variables:

• Scope: Global variables are accessible from any part of the program, including inside
functions (if not shadowed).
• Lifetime: Global variables exist for the duration of the program's execution. They are
created when the program starts and destroyed when the program ends.
• Modification: To modify a global variable inside a function, you must explicitly declare
it as global using the global keyword.
Global Variable Example

Code Example Code Output

•The first print statement inside the function prints global_var's value, which is 20.
•The second print statement outside the function also prints the same value of global_var,
which remains 20.
•This illustrates that the global variable global_var is accessible both inside and outside the
function, and its value remains consistent across both contexts since no modifications are made
to it.
Local Variable

Local Variables:
 A local variable is a variable that is defined inside a function and is only accessible
within that function. It cannot be accessed from outside the function in which it is
declared. The scope of a local variable is limited to the function block where it is
defined.

Characteristics of Local Variables:


 Scope: Local variables are only accessible within the function where they are defined.
 Lifetime: Local variables exist only during the execution of the function. Once the
function terminates, the local variables are destroyed.
 Shadowing: If a local variable has the same name as a global variable, the local
variable will "shadow" or override the global variable within that function's scope.
Local Variable Example

Code Example Code Output

•This code snippet illustrates how a variable defined within a function is local to that function,
meaning it can only be accessed or modified inside that function.
•Local variables are useful for temporary storage of data that only needs to be used within a
specific function.
Summary of Differences

Aspect Local Variable Global Variable


Definition Inside a function Outside all functions

Scope Only within the function Throughout the entire program

Accessible from any part of the


Accessibility Not accessible outside the function
program
Exists for the duration of the
Lifetime Exists only during the function call
program
Can be modified freely within the Requires global keyword to modify
Modification
function inside a function
ACTTIVITY - Global & Local
Code Example
global_var = 50 # Global variable 1. Open Thonny
2. Write the code on the left – without
comments
def my_function(): 3. Run the code
local_var = 10 # Local variable 4. Modify the variable values and test
global_var = 20 # This creates a new local the output
variable with the same name
print("Inside function, local_var:", local_var)
Code Output
print("Inside function, global_var:", global_var)

my_function()
print("Outside function, global_var:",
global_var) # This prints the original global
variable
Activity – Modify to include
functions

 Modify this program


to include
FUNCTIONS that
outputs the area of
a circle based on
the given radius

•The program takes the radius as input and calculates the area
using the formula πr².
•The area is then printed.
Answer - Modify to include
functions

•The calculation of the area is


moved to a function
calculate_area(radius).

•The main code takes user input,


calls the function to calculate the
area, and then prints the result.

•This makes the program more


modular and reusable.
Activity 2 – Modify to include
functions

 Modify this program to


include FUNCTIONS that
finds the largest of three
numbers provided by the
user.
Answer 2 - Modify to include
functions

 The logic to find the largest


number is moved to a
function find_largest(num1,
num2, num3).

 The main code collects user


input, calls the function,
and prints the result.

 This makes the logic


reusable, and the code is
more organized.
Code - With vs Without Functions

 Without Functions: The code directly handles input, processing, and


output in a linear sequence. This can make the code harder to
maintain and less reusable.

 With Functions: The code is broken into modular parts, where each
function handles a specific task. This improves readability,
maintainability, and reusability. Functions allow the same logic to be
reused in different parts of the program or even in different programs.
RECALL QUESTIONS
What scope of variable do
we use INSIDE a function?
What is a function?
Why do we use Functions?
What algorithm construct
aligns with a Function?
What is the Key Word in
python to declare a
function?
Extra Resources

Functions:
 https://www.w3schools.com/python/python_functions.asp

You might also like