PPS Unit 3
PPS Unit 3
PPS Unit 3
Solving
def my_function(parameters):
function_block
return expression
⚫ The def keyword, along with the function name is
used to define the function.
#function definition
def hello_world():
print("hello world")
# function calling
hello_world()
return statement
⚫ The return statement is used at the end of the
function and returns the result of the function.
⚫ It terminates the function execution and transfers the
result where the function is called.
⚫ The return statement cannot be used outside of the
function.
return [expression_list]
In the above code, we have defined the function named sum, and it has
a statement c = a+b, which computes the given values, and the result is
returned by the return statement to the caller function.
Example 2 Creating function without
return statement
# Defining function
def sum():
a = 10
b = 20
c = a+b
● Required arguments
● Keyword arguments
● Default arguments
● Variable-length arguments
Required arguments
def add(a,b,*arg):
m=a+b
for value in arg:
m=m+value
return m
OUTPUT : ????
Variable scope and lifetime,
All variables in a program may not be accessible at all
locations in that program. This depends on where you have
declared a variable.
● Global variables
● Local variables
Example
x = lambda a:a+10
print(x)
print("sum = ",x(20))
Output:
<function <lambda> at
0x0000019E285D16A8>
sum = 30
'''this is lambda function'''
x = lambda a, b, c : a + b + c
print(x(5, 6, 2))
output
13
Why Use Lambda Functions?
The power of lambda is better shown when you use them as an
anonymous function inside another function.
Introduction to modules
def area_triagle(x,y):
area=(1/2)*x*y
print("Area of triangle :",area)
def area_circle(r):
print("Area of circle :",3.14*r*r)
x=100
Use a Module
import mymodule
mymodule.area_triagle(10,20)
mymodule.area_circle(6)
Mod1.py
def gfg():
print("Welcome to
GFG")
Mod2.py
Syntax:
import package_name.module_name
Output:
3.141592653589793
720