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

Python Notes

This document covers the concepts of functions, modules, and packages in Python. It explains how to define and use user-defined functions, the differences between local, global, and nonlocal variables, and the use of lambda functions. Additionally, it discusses creating and importing modules and packages, along with built-in modules and package management using PIP.

Uploaded by

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

Python Notes

This document covers the concepts of functions, modules, and packages in Python. It explains how to define and use user-defined functions, the differences between local, global, and nonlocal variables, and the use of lambda functions. Additionally, it discusses creating and importing modules and packages, along with built-in modules and package management using PIP.

Uploaded by

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

Unit - III Functions, Modules and Packages in Python

(CO-
Develop packages to solve given problem using python.)

TLO 3.1 Write relevant user defined functions for the given problem.
TLO 3.2 Write relevant user defined module for the given problem.
TLO 3.3 Write packages for the given problem.

3.1 Functions: Defining function, Calling function, Function arguments, Return statement, Scope of
Variable, Lambda functions
Defining function.
A function is a block of code that performs a specific task. The function is runs when it is called.
In Python a function is defined using the def keyword:
Eg:
def function_name():
print("Hello from a function")

Calling a Function
To call a function, use the function name followed by parenthesis:
Eg:
def my_function():
print("Hello from a function")

my_function()
Function Arguments
-Information can be passed into functions as arguments.
-Arguments are specified after the function name, inside the parentheses. You can add as many
arguments as you want, just separate them with a comma.

Eg: def function1(name):


print(“My name is ”+fname)

function1("Ram")
function1("Seema")
function1("Kajal")

Parameters or Arguments?

The terms parameter and argument can be used for the same thing: information that are passed into a
function.

-A parameter is the variable listed inside the parentheses in the function definition.

-An argument is the value that is sent to the function when it is called.
Return statement
To let a function return a value, use the return statement:

Eg:
def function1(x):
return 5 * x

print(function1(3))
print(function2(5))

Scope of Variable
The location where we can find a variable and also access it if required is called
the scope of a variable.

Python Local variable


Local variables are those that are initialized within a function and are unique to that
function. It cannot be accessed outside of the function.
Eg:
def f():
# local variable
s = "Local variable"
print(s)
f()

Python Global variables


Global variables are the ones that are defined and declared outside any function and are
not specified to any function. They can be used by any part of the program.
def f():
print(s)

# Global scope
s = "Global variable"
f()

Nonlocal Variables
In Python, the nonlocal keyword is used within nested functions to indicate that a variable is
not local to the inner function, but rather belongs to an enclosing function’s scope.

# outside function
def outer():
message = 'local'
# nested function
def inner():

# declare nonlocal variable


nonlocal message

message = 'nonlocal'
print("inner:", message)

inner()
print("outer:", message)

outer()

The pass Statement


function definitions cannot be empty, but if you for some reason have a function definition with no content, put
in the pass statement to avoid getting an error.

Eg:
def myfunction():
pass

Function positional/required argument:


The list of variables declared in the parentheses at the time of defining a function are the formal
arguments. And, these arguments are also known as positional arguments. A function may be
defined with any number of formal arguments.

While calling a function −

 All the arguments are required.


 The number of actual arguments must be equal to the number of formal arguments.
 They Pick up values in the order of definition.
 The type of arguments must match.
 Names of formal and actual arguments need not be same.
def nameAge(name, age):
print("Hi, I am", name)
print("My age is ", age)
# You will get correct output because argument is given in order
print("Case-1:")
nameAge("Prince", 20)
# You will get incorrect output because argument is not in order
print("\nCase-2:")
nameAge(20, "Prince")

Output

Case-1:
Hi, I am Prince
My age is 20
Case-2:
Hi, I am 20
My age is Prince

Positional Only Arguments


It is possible in Python to define a function in which one or more arguments can not accept their value
with keywords. Such arguments are called positional-only arguments.

To make an argument positional-only, use the forward slash (/) symbol. All the arguments before this
symbol will be treated as positional-only.

def intr(a, b, /):


val = a+b
return val
print(intr(8, 4))

If we try to use the arguments as keywords, Python raises errors as shown in the below example.
def intr(a, b, /):
val = a+b
return val
print(intr(a=8, b=4))

Keyword Arguments
You can also send arguments with the key = value syntax.

This way the order of the arguments does not matter.

def Fun1(RN,Name,City):
print("My Name is " + Name)

Fun1(Name=”Zeal”, City=”Pune”, RN=1)


You can use the variables in formal argument list as keywords to pass value.
Use of keyword arguments is optional. But, you can force the function to
accept arguments by keyword only. You should put an astreisk (*) before the
keyword-only arguments list.

def intr(a,*, b):


val = a+b
return val

interest = intr(1000, rate=10)


print(interest)

Default Parameter Value


The following example shows how to use a default parameter value.
If we call the function without argument, it uses the default value

Eg:

def fun1(country = "Norway"):


print("I am from " + country)

fun1 ("Sweden")
fun1 ("India")
fun1 ()
fun1("Brazil")

Python Lambda
A lambda function is a small anonymous function.
A lambda function can take any number of arguments, but can only have one expression.

Syntax:
lambda arguments : expression

eg:

Add 10 to argument a, and return the result:

x = lambda a : a + 10
print(x(5))

Python map() Function


The map() function in Python is used to apply a function to all the elements of an iterable (such as a list,
tuple, etc.) and returns a map object (an iterator).
Syntax:
python
CopyEdit
map(function, iterable)

 function: A function that will be applied to each element of the iterable.


 iterable: A sequence (list, tuple, etc.) whose elements will be passed through the function.

How map() Works?

1. The function is applied to each element of the iterable.


2. The result is returned as an iterator.
3. We can convert the result into a list or tuple using list() or tuple().

Example 1: Using map() with a Normal Function


python
CopyEdit
# Function to calculate square
def square(num):
return num * num

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Applying map()
result = map(square, numbers)

# Convert map object to list


print(list(result))

Output:

csharp
CopyEdit
[1, 4, 9, 16, 25]

✅ Here, square() function is applied to each number in the list.

Example 2: Using map() with lambda Function


python
CopyEdit
numbers = [2, 4, 6, 8, 10]

# Using lambda function inside map()


result = map(lambda x: x * 2, numbers)

print(list(result))
Output:

csharp
CopyEdit
[4, 8, 12, 16, 20]

✅ Here, lambda x: x * 2 is applied to each element of numbers.

Example 3: Using map() with Multiple Iterables

python
CopyEdit
# Two lists
a = [1, 2, 3]
b = [4, 5, 6]

# Adding corresponding elements


result = map(lambda x, y: x + y, a, b)

print(list(result))

Output:

csharp
CopyEdit
[5, 7, 9]

✅ Here, lambda x, y: x + y is applied to both lists simultaneously.

Example 4: Using map() with str.upper()


python
CopyEdit
words = ["hello", "world", "python"]

# Convert each word to uppercase


result = map(str.upper, words)

print(list(result))

Output:

css
CopyEdit
['HELLO', 'WORLD', 'PYTHON']

✅ Here, str.upper is applied to each word to convert it to uppercase.

Key Points to Remember


 map() does not modify the original iterable.

 It returns a map object (iterator), so it needs to be converted using list() or tuple().
 It is faster than using a for loop for applying functions.

Python reduce() Function

The reduce() function in Python is used to apply a function cumulatively to the elements of an iterable,
reducing it to a single value.

📌 Unlike map(), which applies a function to each element individually, reduce() combines elements step
by step.

Syntax:
python
CopyEdit
from functools import reduce
reduce(function, iterable)

 function: A function that takes two arguments and performs an operation.


 iterable: A sequence (list, tuple, etc.) whose elements will be reduced.

✅ reduce() is available in the functools module, so we need to import it before using.

Example 1: Using reduce() to Sum a List


python
CopyEdit
from functools import reduce

# Function to add two numbers


def add(x, y):
return x + y

# List of numbers
numbers = [1, 2, 3, 4, 5]

# Applying reduce()
result = reduce(add, numbers)

print(result)

Output:

CopyEdit
15
✅ Here, reduce() adds numbers step by step: (((1+2)+3)+4)+5 = 15.

Example 2: Using reduce() to Find the Maximum Number


python
CopyEdit

from functools import reduce

# Function to find the maximum


def maximum(x, y):
return x if x > y else y

numbers = [3, 7, 2, 9, 5]

result = reduce(maximum, numbers)

print(result)

Output:

CopyEdit
9

✅ Here, reduce() finds the largest number step by step.

Example 3: Using reduce() with lambda


python
CopyEdit
from functools import reduce

numbers = [2, 3, 4, 5]

# Multiplying all elements


result = reduce(lambda x, y: x * y, numbers)

print(result)

Output:

bash
CopyEdit
120 # (2*3*4*5)

✅ Here, reduce() multiplies all elements step by step.

Example 4: Concatenating Strings Using reduce()


python
CopyEdit
from functools import reduce

words = ["Python", "is", "awesome"]

result = reduce(lambda x, y: x + " " + y, words)

print(result)

Output:

arduino
CopyEdit
"Python is awesome"

✅ Here, reduce() joins all words into a single sentence.

Difference Between map() and reduce()


Feature map() reduce()

Purpose Applies function to each element Applies function cumulatively to reduce elements

Result Returns a new iterable (map object) Returns a single result

Function Type Works with single or multiple arguments Works with two arguments at a time

Usage Transforming elements Aggregating elements

Example map(lambda x: x*2, [1, 2, 3]) → [2, 4, 6] reduce(lambda x, y: x + y, [1, 2, 3]) → 6

Conclusion
 Use map() when you want to apply a function to each element and get a transformed iterable.
 Use reduce() when you want to aggregate elements into a single value (sum, product, max, etc.).

MODULES AND PACKAGES IN PYTHON

3.2 Modules

A module in Python is a file containing Python code (functions, classes, or variables) that
can be imported and reused in other programs. It helps in modularizing code and improving
reusability.
Creating a User-Defined Module

To create a module, simply create a .py file with functions or variables.

Example: Creating my_module.py

# my_module.py
def greet(name):
return f"Hello, {name}!"

pi = 3.14159

Using the module in another Python script:

# main.py
import my_module

print(my_module.greet("Alice")) # Output: Hello, Alice!


print(my_module.pi) # Output: 3.14159

Importing a Modu

le

Modules can be imported using:

1. import module_name
2. from module_name import function_name
3. from module_name import *

Example:

from my_module import greet


print(greet("Bob")) # Output: Hello, Bob!

Example 2: Creating a Math Operations Module

Creating math_operations.py

# math_operations.py
def add(a, b):
return a + b

def subtract(a, b):


return a - b

def multiply(a, b):


return a * b

Using math_operations.py in another script:


# main.py
import math_operations

print(math_operations.add(10, 5)) # Output: 15


print(math_operations.subtract(10, 5)) # Output: 5
print(math_operations.multiply(10, 5)) # Output: 50

Using Python Built-in Modules

Python provides several built-in modules, such as math, random, datetime, etc.

Example: Using math module

import math

print(math.sqrt(25)) # Output: 5.0


print(math.factorial(5)) # Output: 120

Namespace and Scoping

 Namespace is the mapping of variable names to objects in memory.


 Scope defines the accessibility of variables (Local, Enclosing, Global, Built-in).

Example:

def outer():
x = "Outer"
def inner():
x = "Inner"
print("Inner Scope:", x)
inner()
print("Outer Scope:", x)

outer()

Output:

Inner Scope: Inner


Outer Scope: Outer

3.3 Python Packages


A package is a collection of Python modules. It is a directory containing an __init__.py
file and multiple modules.

Creating a User-Defined Package

Steps:

1. Create a directory (e.g., mypackage).


2. Inside the directory, create an __init__.py file.
3. Add module files (e.g., module1.py).

Structure:

mypackage/
__init__.py
module1.py

Example: Creating module1.py

# module1.py
def add(a, b):
return a + b

Using the package:

# main.py
from mypackage import module1
print(module1.add(3, 4)) # Output: 7

Importing a Package

Packages are imported using import package_name.module_name or from package_name


import module_name.

Example:

from mypackage.module1 import add


print(add(5, 6)) # Output: 11

Using Python Built-in Packages

Python has built-in packages like os, sys, json, etc.

Example: Using os package

import os
print(os.getcwd()) # Output: Current working directory

Installing Packages Using PIP

PIP (Python Package Installer) is used to install external packages.


Command to install a package:

pip install numpy

Example: Using numpy

import numpy as np
arr = np.array([1, 2, 3, 4])
print(arr) # Output: [1 2 3 4]

By using modules and packages, Python code becomes more structured, reusable, and
maintainable.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy