Python Notes
Python Notes
(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.
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.
# 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():
message = 'nonlocal'
print("inner:", message)
inner()
print("outer:", message)
outer()
Eg:
def myfunction():
pass
Output
Case-1:
Hi, I am Prince
My age is 20
Case-2:
Hi, I am 20
My age is Prince
To make an argument positional-only, use the forward slash (/) symbol. All the arguments before this
symbol will be treated as positional-only.
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.
def Fun1(RN,Name,City):
print("My Name is " + Name)
Eg:
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:
x = lambda a : a + 10
print(x(5))
# List of numbers
numbers = [1, 2, 3, 4, 5]
# Applying map()
result = map(square, numbers)
Output:
csharp
CopyEdit
[1, 4, 9, 16, 25]
print(list(result))
Output:
csharp
CopyEdit
[4, 8, 12, 16, 20]
python
CopyEdit
# Two lists
a = [1, 2, 3]
b = [4, 5, 6]
print(list(result))
Output:
csharp
CopyEdit
[5, 7, 9]
print(list(result))
Output:
css
CopyEdit
['HELLO', 'WORLD', 'PYTHON']
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)
# 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.
numbers = [3, 7, 2, 9, 5]
print(result)
Output:
CopyEdit
9
numbers = [2, 3, 4, 5]
print(result)
Output:
bash
CopyEdit
120 # (2*3*4*5)
print(result)
Output:
arduino
CopyEdit
"Python is awesome"
Purpose Applies function to each element Applies function cumulatively to reduce elements
Function Type Works with single or multiple arguments Works with two arguments at a time
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.).
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
# my_module.py
def greet(name):
return f"Hello, {name}!"
pi = 3.14159
# main.py
import my_module
Importing a Modu
le
1. import module_name
2. from module_name import function_name
3. from module_name import *
Example:
Creating math_operations.py
# math_operations.py
def add(a, b):
return a + b
Python provides several built-in modules, such as math, random, datetime, etc.
import math
Example:
def outer():
x = "Outer"
def inner():
x = "Inner"
print("Inner Scope:", x)
inner()
print("Outer Scope:", x)
outer()
Output:
Steps:
Structure:
mypackage/
__init__.py
module1.py
# module1.py
def add(a, b):
return a + b
# main.py
from mypackage import module1
print(module1.add(3, 4)) # Output: 7
Importing a Package
Example:
import os
print(os.getcwd()) # Output: Current working directory
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.