100% found this document useful (1 vote)
43 views

Functions PDF

The document discusses functions in Python, explaining that functions help divide programs into smaller, independent modules and allow code to be reused by calling the function. It covers defining functions using the def keyword, passing arguments to functions, using default parameter values, returning values from functions, and using variable length arguments. Examples are provided to demonstrate different aspects of functions like positional arguments, keyword arguments, and returning multiple values.

Uploaded by

Khushi Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (1 vote)
43 views

Functions PDF

The document discusses functions in Python, explaining that functions help divide programs into smaller, independent modules and allow code to be reused by calling the function. It covers defining functions using the def keyword, passing arguments to functions, using default parameter values, returning values from functions, and using variable length arguments. Examples are provided to demonstrate different aspects of functions like positional arguments, keyword arguments, and returning multiple values.

Uploaded by

Khushi Gupta
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 26

FUNCTIONS

Dr. Kusum Lata


Assistant professor, USME, EDC
Introduction to Functions
• Function help us to divide the big program into small pieces or modules.
• Function help us to divide our entire program in small independent modules.
• Thus, it is a self contained block of one or more statements that perform a special
task when called.
Syntax of function is as follows

def name_of_function(Parameters): Function Header


statement1
statement2
statement3
…………………………… Function Body
……………………………
statementN
Simple Program on Functions
def Demo():
print('Welcome to the Concepts of Functions')
Demo() #Call to Function Demo.

Output:
Welcome to the Concepts of Functions
Ex: Write a program to prompt the name of a user
and print welcome message “Dear name of user,
Welcome to Python Programming.
Use of a Function
• Write a program to add the sum of digits from 1 to 25, 50 to 75 and
90 to 101 using different loop.
Conventional Method: Using Function
Parameters, Arguments in a
Function

• Parameters are used to give input to a function.

• Parameters are specified with the pairs of parenthesis in the function


definition.

• Whereas, arguments are the values actually passed to a function


when calling it.

• Thus, parameters define what type of arguments a function can


accept.
Syntax to define parameters & Arguments

def printMax(num1,num2):
Statemen1
Statemen2 #Define a Function
………………………
………………………
StatementN

printMax(10, 20) #Invocation of function

• printMax(num1, num2) has two parameters num1 and num2.


• Where as 10 and 20 are the actual parameters and these actual
parameters are called “arguments”.
Program on Arguments and Parameters
Q. Write a program to calculate minimum of two numbers by making use of
arguments and parameters.

def FindMin(num1,num2):
if num1 < num2:
print(num1, 'is smaller than ',num2)
elif num2 < num1:
print(num2,' is smaller than ', num1)
else:
print(' Both are equal')
FindMin(20,40)

Output:
20 is smaller than 40
Ex: Write a program to calculate the factorial
of a number using function.
Positional Arguments
Consider the following:
If there are more than one parameters, how does the Python knows
which argument in the function call statement has to be assigned to
which parameter.
Answer:
Parameters are assigned by default according to their positions i.e., the
1st argument in the call statement is assigned to the first parameter
listed in the function definition and the second argument in the call
statement is assigned to the second parameter listed in the function
definition and so on.
Ex: Positional Arguments
def Display(Name,age):
print("Name = ",Name,"age = ",age)
Display("John",25)
Display(40,"Sachin")

Output:
Name = John age = 25
Name = 40 age = Sachin

Thus, the first argument binds to the first parameter and second
argument binds to the second parameter. This style of matching up
arguments and parameter is called “positional argument style” or
“positional parameter style”.
Ex: Positional Arguments
def Display(Name,age):
print("Name = ",Name,"age = ",age)
Display("John“)

Output:
Error

Python will show error when incorrect number of arguments are


passed to the function call.
Keyword Arguments
An alternative to positional argument is keyword argument.
• If we know the parameter name used in the function, we can use
parameter name while calling the function. We can pass a keyword
argument to a function by using its corresponding parameter name
rather than its position.
Program: Demonstrate use of Keyword Arguments

def Display(Name,age):
print("Name = ",Name,"age = ",age)
Display(age=25,Name="John") #Call function using keyword arguments

Output:
Name = John age = 25
Precautions while using Keyword Arguments

(i) A positional argument cannot follow a keyword argument.


Ex: Consider the function definition:
def Display(num1, num2) :

Thus, we can invoke the above function as :


Display( 40, num2=10)
But we cannot invoke the function as:
Display(num2=10, 40)
Precautions while using Keyword Arguments

(ii) We can not duplicate an argument by specifying it as both ,


a positional argument and keyword argument.
Consider the function definition:
def Display(num1, num2):

Thus, we can not invoke the above function as :


Display( 40, num1=40) # Error
Reason: Multiple values are specified for parameter num1.
Parameters with Default Values

• Parameters within the function definition can have default


values.
• Default value to an parameter can be given by using assignment
(=) Operator.

Following Program demonstrate the use of default values in function definition.

def greet(name,msg="Welcome to Python!!"):


print(" Hello ",name, msg)
greet(“Rahul")

Output:
Hello Rahul Welcome to Python!!
Parameters with Default Values
def greet(name,msg="Welcome to Python!!"):
print(" Hello ",name, msg)
greet(“Rahul")

Output:
Hello Rahul Welcome to Python!!

Test case 1:
greet(“amit”)
Test case 2:
greet (“Raj”, “How are you”)
Parameters with Default Values
Note:
In function definition, any number of arguments can have default
values, but once we have a default value to a parameter, all the
parameters to its right must also have default values.

def greet(msg="Welcome to Python!!“, name): # Error


Parameters with Default Values

Write a program to calculate the area of a circle. Declare the default parameter
value of pi as 3.142 and radius as 1.
The return statement
• The return statement is used to return a value from the
function.

• It is also used to return form a function i.e. break


out of the function.
def minimum(a,b):
if a<b:
Example: return a
elif b<a:
return b
else:
return "Both the numbers are
equal"
print(minimum(100,85))

Output:
8 is minimum
Returning Multiple Values
• In python yes it is possible to return multiple values.
• Syntax to return multiple values is as follows
return Value1,Value2,Value3

import math
def Sq_Cub_Srt(a,b,c):
return a**2, b**3, math.sqrt(c)
S,C,Sq = Sq_Cub_Srt(2,3,4)
print('Square = ',S)
print('Cube = ',C)
print('Cube = ',Sq)

Output
Square = 4
Cube = 27
Cube = 2.0
Variable length non-keyword (NKW) arguments
• The variable length argument allows a function to pass or accept “n” i.e
arbitrary no. of arguments.
• The arguments within the function are not named explicitly in the function
declaration because during the execution the no. of arguments may be
different on successive function calls.
• With * operator, a function can pass accept or pass NKW arguments.
Syntax:
def function_name(*args):
………………..
………………..
Function body
………………..
………………
Variable length non-keyword (NKW)
arguments
def calc(*args):
s=0
print(“the numbers are as follows”)
for num in args:
print(num,end=“ “)
s=s+num
return s
______________________________________
Total = calc(10,20)
Print(“sum=“,total)

You might also like