4 Functions
4 Functions
BY ARPITA CHOWDHURY
What is Function?
A function is a block of organized, reusable code that performs a specific task. Functions help
break programs into smaller, manageable, and reusable parts, making code easier to
understand, test, and maintain. Most programming languages, including Python, support
functions.
Benefits of Using Functions
Code Reusability: Once a function is defined, it can be reused in multiple places in a program
without rewriting the code.
Modularity: Breaking the code into functions makes it more organized and modular. Each
function performs a single task, making it easier to debug, test, and maintain.
Abstraction: Functions allow you to encapsulate complex logic and use it without worrying
about the internal details.
Scalability: Functions make it easier to extend the code. You can add more functionality or
modify existing functions without affecting the entire program.
What is a Parameter?
A parameter is a variable used in a function definition to represent the input that the function
expects. When a function is called, arguments (the actual values) are passed to these
parameters, allowing the function to perform operations with those values.
In simple terms, parameters are placeholders in the function definition, while arguments are the
actual values passed during the function call.
Key Concepts:
1. Parameters vs Arguments
2. Types of Parameters
Parameters vs Arguments
•Parameter: A variable defined in the function signature that specifies the type of input the
function will receive.
•Argument: The actual value you pass to the function when calling it. This value gets assigned to
the corresponding parameter.
def Statements with Parameters
In Python, a function is defined using the def keyword followed by the function name and
parentheses. You can pass information to the function through parameters, which act as
placeholders for the values (called arguments) that are provided when the function is called.
Parameters allow you to make functions more flexible and reusable.
When calling a function, you can pass You can assign a default value to a parameter.
arguments by explicitly specifying the If the argument is omitted when the function
parameter name, allowing you to change the is called, the default value is used.
order of arguments.
The *args parameter allows a function to accept The **kwargs parameter allows you to pass any
any number of positional arguments. These number of keyword arguments (key-value pairs) to
arguments are passed as a tuple. a function. These arguments are passed as a
dictionary.
7. Write a Python function that prints the details of a student. The function should accept:
◦ A tuple of courses using *args
◦ Additional details (like name and roll_number) using **kwargs
Home Work
8. Write a function that attempts to modify both a list and a string passed as arguments.
9. Create a function where:
• The first argument must be positional-only.
• The second argument must be keyword-only.
10. Write a function order_item(item, quantity=1, price=10.0) that calculates the total price.
11. Create a function sum_all(*numbers) that returns the sum of all numbers passed to it.
12. Write a function process_order(*items, **details) where:
Key Points
•Local variables are preferred over global variables for better modularity and to avoid unintended
side effects.
•Use global variables sparingly to maintain clean and predictable code.
using the global statement
The global statement in Python is used to declare a variable as global inside a function. This
allows the function to access and modify the variable that exists outside its local scope in the
global namespace.
How global Works
•Without the global statement, a variable assigned within a function is treated as local to that
function.
•By using global, the function refers to the variable in the global scope, enabling modification of
its value.
Key Points
The global statement must be used before any modification or assignment to the global variable
inside the function.
Without global, an attempt to assign a value to a global variable inside a function will create a
new local variable instead.
Example: Accessing a Global Variable
Without the global statement, accessing a global variable inside a function works fine if no
assignment is made:
Example: Modifying a Global Variable
To modify the global variable inside a function, use global:
What Happens Without global?
If global is not used and you try to assign a value to a global variable, Python treats it as a new
local variable:
Multiple Variables with global
You can declare multiple global variables at once:
Resolution of names
In Python, name resolution within functions follows the LEGB rule, which defines the order in
which Python searches for a variable or name. LEGB stands for Local, Enclosing, Global, Built-in.
Here's how Python resolves variable names when they are used inside a function:
LOCAL (L) ENCLOSING (E)
Definition: The innermost scope, which refers Definition: The scope of any enclosing
to names defined inside the function (local functions (for nested functions). This is the
variables). scope of the function one level above the
current function.
Priority: Python first looks for the variable in
the local scope of the function where the Priority: Python searches here if the variable is
name is referenced. not found in the local scope.
GLOBAL (G) BUILT-IN (B)
Definition: The module-level scope, which refers to Definition: The outermost scope, which includes names
variables defined at the top level of the script or program. predefined by Python, such as len, print, int, etc.
Priority: Python searches the global scope if the variable is Priority: If the variable is not found in any of the above
not found in local or enclosing scopes. scopes, Python looks in the built-in scope.
Modification: To modify a global variable inside a function,
use the global keyword.
Illustration of the LEGB Rule
Here’s a comprehensive example:
Shadowing
A variable in a lower scope (Local or Enclosing) can shadow variables in higher scopes (Global or
Built-in). Once shadowed, the higher-scope variable is inaccessible in that function.
To restore the built-in functionality, you can delete the shadowing variable using del len.
Home Work
Simple Scope Check Write a program to demonstrate the difference between a global and a local
variable.
◦ Define a global variable x = 10.Create a function that sets a local variable x = 20 and prints it.
◦ Outside the function, print the global variable.
◦ What do you observe?
Using global Keyword Write a program that uses the global keyword to modify a global variable inside a
function.
◦ Define a global variable count = 0.
◦ Create a function increment() that uses global to increase the value of count by 1.
◦ Call increment() three times and print the value of count after each call.
Shadowing Global Variables Create a program where a local variable inside a function shadows a global
variable with the same name.
◦ Define a global variable message = "Hello, World!".
◦ Inside a function, define a local variable message = "Hello, Python!" and print it.
◦ Print the global variable outside the function.
Home Work
Passing Parameters vs. Global Variables Write a program that compares using global variables
and passing parameters to a function.
◦ Define a global variable number = 5.
◦ Create a function multiply_global() that multiplies number by 2 using the global variable.
◦ Create another function multiply_local(n) that takes a parameter n and multiplies it by 2.
◦ Call both functions and compare the results.
Nested Functions and nonlocal Keyword Write a program that demonstrates the use of the
nonlocal keyword.
◦ Define a function outer() that initializes a variable x = 0.
◦ Inside outer(), define a nested function inner() that uses the nonlocal keyword to modify x.
◦ Call inner() multiple times within outer() and print the value of x each time.
the return statement
Terminates the function: Once a return statement is encountered, the function stops executing
further instructions.
Returns a value: The value (or values) specified after the return keyword are sent back to the
caller.
Returns None by default: If a function does not explicitly include a return statement, it returns
None by default.
RETURNING A SINGLE VALUE RETURNING MULTIPLE VALUES
If no return statement is provided or return is The function stops executing as soon as it hits
used without a value, the function returns a return statement.
None.
None
In Python, None is a special constant that represents the absence of a value or a null value. It is
an object of its own data type, NoneType, and is often used to signify that a variable or object
has no value assigned.
Key Characteristics:
• None is not equivalent to False, 0, or an empty string ("").
• It is a singleton object, meaning there is only one instance of None in a Python program.
• It is immutable, like all Python singleton constants.
Common Use Cases:
1. Default Parameters in Functions: Used to indicate that no argument is provided.
2. Return Value: Used as a default return value for functions that do not explicitly return a
value.
3. Checking for Empty Values: Used as a placeholder for optional or uninitialized variables.
Example 1: Default Value in a Function
EXAMPLE 3: FUNCTION WITHOUT EXPLICIT
EXAMPLE 2: VARIABLE INITIALIZATION
RETURN
Error Handling:
• If the denominator is 0, the ZeroDivisionError block executes.
• If non-integer values are provided, the ValueError block handles the error.
Success Case:
◦ If no exception occurs, the else block prints the result.
Cleanup:
◦ The finally block runs regardless of whether an exception occurred or not.
Sample Output
Case 1: No Errors Case 2: Division by Zero