Download as pdf or txt
Download as pdf or txt
You are on page 1of 19

Working with Functions

Intro, Understanding & Defining Functions


Parameters, Returning, Scope

Lectures by Harsh Sharma @ Apni Kaksha


Function ki pehchaan

Functions ( )
In large programs, we try to avoid a single large list of instructions.
It’s broken down into smaller units known as Functions.

A Function is a named unit of a group of program statements. This unit can


be invoked.

A Function is a subprogram/mini-program.
What is a Function?
When we know some things are repetitive or very similar.
To avoid writing same code again and again, we write it once and give it a
name.

This name is the function name, and whenever we call this name the code in
it will run.
Types of Functions
1. User Defined Functions : Designed by Programmers, like we will make.

2. Built-in Functions : Functions already present in python.


(pre-defined) e.g. input( ), len( ), int( ), etc.

3. Functions defined in : These are also predefined but in modules.


Modules To use them we have to import the corresponding
module/library.
e.g. factorial( ), sqrt( ), plot( ), etc.
Minimizing Repetitions
def greeting( ):
print(“Mere pyaare desh vaasiyon...”)
print(“....”)
print(“Mitrrooonnn!!!”)
Will run the three 3 statements.
#code_minimized.
greeting( )
When we have Similar Codes
def announcement(a) :
print(‘Hello Passengers, this train will go to Delhi’) print(‘Hello Passengers, this train will go to’ ,a)
print(‘Hello Passengers, this train will go to Lucknow’)
print(‘Hello Passengers, this train will go to Mumbai) announcement(‘Delhi’)
print(‘Hello Passengers, this train will go to Chandigarh’) announcement(‘Lucknow’)
print(‘Hello Passengers, this train will go to Mars’) announcement(‘Mumbai’)
announcement(‘Chandigarh’)
announcement(‘Mars’)
Elements 0f a Function Definition
Function Header
Keyword for
defining

def sum(x, y) :
print(x+y) parameters/arguments

Function Body
Structure of a Python Program(not imp.)
def function1( ) :
:
def function2( ) :
: Top to Bottom
#top level statements
statement1
statement2
:
Interpreter start _main_ se karta hai
Flow of Execution(learn the flow)
def fun( ) :
print(‘Hello’)
:
print(‘Babye’) Top to Bottom
:
fun( )
:
:
Interpreter start _main_ se karta hai
Practice Time

Q1. w.a.p. to add two numbers using function. (using return)


Arguments & Parameters
Arguments : values being passed as arguments.
Parameters : values being received as arguments.

def multiply(x,y): parameters


return(x*y)

multiply(3,5) arguments
Arguments & Parameters
Arguments can be literals, variables, expressions.
But Parameters have to be some name/identifier, variable to hold incoming
values.

We can also call them :


Argument -> Actual Parameter or Actual Argument
Parameter-> Formal Parameter or Formal Argument
Passing Arguments
def calculate( a ,b ,c ):
:

calculate( 2, 4, 1 )
calculate( x, 8, 3 )
calculate( p, q, r )
calculate( 2, 1)
calculate( 5 )

*Positional arguments or Required arguments or Mandatory Arguments


Default Arguments
Sometimes we need passing arguments to be optional, i.e. if an argument is
passed we will use it and if not we will use the default value for that.

e.g. def food( main=‘Tinde’, sec=‘Parle-G’):


: : :

food(‘Paneer’, ‘Pulaao’)
food(‘Pasta’)
food( )
Important Rules for Default Parameters
Any parameter cannot have a default value unless all parameters appearing on
its right have default values.

def interest ( prin, time, rate = 0.15 ): ✔


def interest ( prin, time = 3, rate = 0.10 ):✔
def interest ( prin, time = 2, rate ): ❌

interest ( 3000, 5 )
interest ( 3000 )
Named Arguments
def interest ( prin, time, rate=0.15 ):
:
interest( rate=0.12, time=8, prin=1000 )
interest( time=5, rate=0.15, prin=2500 )
interest( time=5, prin=2500 )
interest( 1000, rate=0.12, time=4 )

Positional( required ) named


Some more rules
interest ( prin, time, rate=0.12 )

● As default parameters, named arguments also follow the rightmost


rule.
interest( prin=2000, 3, 0.15)
● No Multiple Values
interest( 2000, prin=1000,time=3.5 )
● No Parameter can be left empty
interest( prin=2000, rate=0.3 )
Practice Time
Q1. Find the output : Q2. What’s wrong with the code:

def interest( p , t=2, r = 0.10 ): def add(a, b, c):


return (p*t*r) return a+b+c
print( “the answer is : ”, a+b+c )
print( interest(6100, 1) )
print( interest(5000, r = 0.05) )
print( interest(5000, 3, 0.12) )
print( interest(t=4, p=5000) )
Practice Time
Q. Find the output : Q. Find the output :
def change(P, Q = 30):
def fun(s):
P=P+Q k=len(s)
Q=P-Q m=‘ ’
print(P, ‘#’, Q) for i in range (0,k):
return(P) if(s[i].isupper( )):
m = m + s[i].lower( )
A = 150 elif(s[i].isalpha( )):
B = 100 m = m + s[i].upper( )
A = change( A, B) else :
print(A, ‘#’, B) m = m + ‘bb’
print(m)
B = change(B) fun(‘@gmail.com’)

You might also like