0% found this document useful (0 votes)
10 views39 pages

4 Functions

The document provides a comprehensive overview of functions in Python, detailing their definition, benefits, and key concepts such as parameters and arguments. It explains various types of parameters, including positional, keyword, default, and variable-length parameters, along with rules for defining them. Additionally, it covers local and global variables, the return statement, and exception handling mechanisms in Python.

Uploaded by

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

4 Functions

The document provides a comprehensive overview of functions in Python, detailing their definition, benefits, and key concepts such as parameters and arguments. It explains various types of parameters, including positional, keyword, default, and variable-length parameters, along with rules for defining them. Additionally, it covers local and global variables, the return statement, and exception handling mechanisms in Python.

Uploaded by

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

Functions in Python

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.

•def: This keyword is used to define a new function.


•function_name: The name you assign to the function.
•parameters: These are variables declared within the
parentheses. They receive values when the function is
called.
•return: The value the function returns to the caller
(optional). If no return statement is provided, the
function returns None.
Types of Parameters
•Positional Parameters: Parameters that are assigned values based on the position of the
arguments in the function call.
•Keyword Parameters: Parameters that are assigned values by explicitly naming them in the
function call.
•Default Parameters: Parameters that have a default value if no argument is provided during the
function call.
•Variable-Length Parameters (*args and **kwargs):
• *args: Allows you to pass a variable number of non-keyword arguments.
• **kwargs: Allows you to pass a variable number of keyword arguments.
1. Function with Positional Parameters
When you define a function with parameters, those parameters are expected to receive values
when the function is called.

•In the example above, a and b are positional parameters.


•The arguments 5 and 3 are passed to a and b in the same order.
2. FUNCTION WITH KEYWORD ARGUMENTS 3. FUNCTION WITH DEFAULT PARAMETERS

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.

By using keyword arguments, y is assigned the


value 3 and x the value 10. In this case, name has a default value of
"World". If no argument is provided, the default
value is used.
4. FUNCTION WITH VARIABLE-LENGTH 5. FUNCTION WITH VARIABLE-LENGTH
ARGUMENTS (*args) KEYWORD ARGUMENTS (**kwargs)

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.

In this case, the function accepts any number of


Here, the multiply() function can accept any keyword arguments and processes them as
number of arguments, and they are treated as a key-value pairs
tuple inside the function.
6. Combining Positional, Keyword, and
Default Parameters
•You can combine different
types of parameters in a
function, but be mindful of
the order:
•Positional parameters
•*args
•Keyword parameters with
default values
•**kwargs
Rules for Defining Parameters in
Functions
Order of parameters:
◦ Regular positional parameters come first.
◦ *args for variable-length positional arguments.
◦ Keyword parameters with default values come next.
◦ **kwargs for variable-length keyword arguments comes last.
Positional vs. keyword arguments: When calling a function, positional arguments must be listed before
keyword arguments.
Home Work
1. Write a Python function that calculates the volume of a rectangular box. The function should accept three positional
arguments: length, width, and height.
2. Create a function that generates a greeting message. It should take two arguments: name and greeting, where greeting
has a default value of "Hello".
3. Write a function to calculate the power of a number. The function should accept two arguments: base and exponent
with a default value of 2.
4. Write a Python function that takes a variable number of arguments and returns their sum.
5. Create a function that accepts a dictionary of employee details using **kwargs and prints the name and designation of
the employee.
6. Write a function to calculate the final price of an item after applying a discount. The function should take:
◦ A positional argument price
◦ A keyword argument discount with a default value of 10%

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:

◦ *items is a list of items in an order.


◦ **details contains additional information like customer_name and address.
◦ Print the items and details.

13. Create a function describe_pet(pet_name, /, *, pet_type="Dog") that describes a pet.


◦ Call the function to ensure that pet_name can only be passed as a positional argument, and pet_type can only be passed as a
keyword argument.

14. Write a function calculate_total(a, b, c) and:


◦ Pass the arguments using a tuple values = (10, 20, 30).
◦ Pass arguments using a dictionary data = {'a': 5, 'b': 15, 'c': 25}.
Local Variables
Definition: Variables declared inside a function are local to that function.
Scope: Only accessible within the function where they are defined.
Lifetime: Exist only during the function's execution. Once the function ends, the variable is
destroyed.
Global Variables
Definition: Variables declared outside of all functions and classes are global.
Scope: Accessible throughout the program, including inside functions (if not redefined there).
Lifetime: Exists throughout the program’s execution.
Using Global Variables Inside Functions
If you need to modify a global variable inside a function, you must declare it as global within the
function. Otherwise, Python will treat it as a new local variable.

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

Python allows functions to return multiple


values as a tuple.
RETURNING A VALUE AND TERMINATING
RETURNING NONE
EXECUTION

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

In this case, the function doesn't explicitly return


EXAMPLE 3: CHECKING FOR NONE anything, so None is returned by default. A

By using None, Python provides a simple, clear


way to represent the absence of a value.
Exception Handling
Exception handling in Python is a mechanism to handle runtime errors, ensuring the program
doesn't crash unexpectedly. Instead, Python allows the program to "catch" these exceptions and
take corrective actions.
Key Concepts
1) try block: Contains the code that might raise an exception.
2) except block: Used to handle the exception.
3) else block: Executes if no exception occurs.
4) finally block: Executes no matter what (used for cleanup actions).
Example
How It Works
User Input:
◦ The try block collects input and performs division.

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

Case 3: Invalid Input

You might also like