Function is a block of instructions that performs a specific and well defined task. This block can be repeatedly called by other programming instruction.
Functions AU : May-19, Dec.-19, Marks 12
What
is function ?
Function
is a block of instructions that performs a specific and well defined task. This
block can be repeatedly called by other programming instruction.
Every
function is specified by a name.
Following
are some reasons why do we need to use functions in Python
1.
All the logically related statements can be grouped together in one entity.
This
makes
the program easy to read, understand and debug.
2.
The repetition of frequently required code can be avoided by
using function.
3.
Dividing a long program into functions allows us to debug the parts one
at a time and then assemble them into a working whole.
4.
Once the code of the function is written and tested, we can reuse this code.
Reusability is an important use of function.
The
function can be defined using the def. The syntax of function definition is as
follows -
Example
:
Step
1 :
Create a function definition in a file.
Step
2:
Press F5 button and run the above program. You will get the following output -
•
The
first line of function definition is called function header and rest is called
body.
•
Note that - The code within every function starts with a colon (.) and should
be indented (space).
•
Python functions don't have any explicit begin or end like curly braces to
indicate the start and stop for the function, they have to rely on this
indentation.
•
For example : If we write the above function without indentation, then error
will occur. Following screenshot illustrates this –
•
If you type a function definition in interactive mode, the interpreter prints
dots (...) to let you know that the definition isn't complete. For example –
•
Then the call to the function in interactive mode is given as follows
•
The functional call is a statement that invokes the function. When a function
is called the program control jumps to the definition of the function
and executes the statements present in the function body.
•
Once all the statements in function body get executed, the control goes back to
the calling function.
Syntax
Function_name()
•
Sometimes there are some parameters to the function then the syntax becomes - Function_name(variable1,
variable2,...)
•
The argument is a value that is passed to the function when it is called.
•
On the calling side, it is an argument and on the function side it is a
parameter.
•
For
example - Consider following function in which there is single parameter passed
to the function Cube Demo
•
We can pass
1)
Directly a value as a parameter or
2)
A variable or
3)
An expression.
•
For example:
Example
2.13.1 Write a Python program to calculate area of
rectangle using function. Make use of parameter passing technique.
Solution
:
Circle.py
def
area_circle(r):
PI
= 3.14
Result
= PI*r*r
print("The
result of circle: "result)
Output
>>>
area_circle(10)
The
result of circle: 314.0
>>>
Example
2.13.2 Write a Python program to calculate square of a
given number.
Solution
:
SquareProg.py
def
Square(num):
result
= num*num
print("The
square of "num," is: "result)
Output
>>>
Square(5)
The
square of 5 is: 25
Example
2.13.3 Write a Python program to swap two numbers.
Solution
:
SwapProg.py
def
Swap(a,b):
print("Before
Swapping")
print("a
= "a)
print("b
= "b)
temp
= a
a
= b
b
= temp
print("After
Swapping")
print("a
= ",a)
print("b
= ",b)
Output
>>>
Swap(10,20)
Before
Swapping
a
= 10
b=
20
After
Swapping
a
= 20
b
= 10
>>>
Example
2.13.4 Write a Python program to check whether the
given number is even or odd.
Solution
:
EvenOddProg.py
def
EvenOddTest(num):
if(num%2==0):
print("The
number is even");
else:
print("The
number is odd");
Output
>>>
EvenOddTest(10)
The
number is even
>>>
EvenOddTest(11)
The
number is odd
>>>
Example
2.13.5 Write a Python program to test whether the year
is leap or not.
Solution
:
Leap
YearProg.py
def
Leap(year):
if
year % 4 == 0 and year %100 != 0 or year % 400 = = 0:
print
(year," is a leap-year")
else:
print
(year," is not a leap-year")
Output
>>>
Leap(2020)
Is
a leap-year
>>>
Leap(2019)
2019
is not a leap-year
>>>
Program
Explanation :
•
In above program, we have to check multiple conditions within one If Statement,
we used Logical AND and Logical OR operators. These conditions are -
1:
( year%400 == 0) OR
2:
( year%4 == 0 ) AND
3:
( year%100 == 0))
If
these conditions are true then the year value is a leap year value otherwise
not.
•
In this section, we will discuss some additional features of functions such as –
1)
Required Arguments
2)
Default Arguments boda
3)
Keyword Arguments
4)
Variable Length Arguments
a.
Required Arguments
•
Required arguments are mandatory arguments to the function. These argument
values must be passed in correct number and order during function call. Below
is a typical syntax for a required argument function.
For
example –
def
My_Function(str,num):
print(str)
print(num)
str="Lucky"
num=10
My_Function(num)
Output
TypeError:
My_Function() missing 1 required positional argument: 'num
Program
Explanation : In above program
•
We have defined a function named My_Function with two arguments. But
while calling a function we are passing only one arguments. That means we are
not passing the required number of arguments to the function. This
causes error. Hence is the output.
b.
Default Arguments
•
Default
values indicate that the function argument will take that value if no argument
value is passed during function call. The default value is assigned by using
assignment (=) operator. It is in the form keywordname = value.
For
example –
def
My_Function(Roll,name ="Nisha",course ="Mechanical"):
print(name,"is
having Roll Number: ",Roll,", enrolled for course: "course)
#1
positional Argument
My_Function(10)
#2
positional Argument
My_Function(11,"Sharda")
#3
postional Argument
My_Function(12,"Aditya",
"Electrical")
Output
Nisha
is having Roll Number: 10 ,enrolled for course: Mechanical
Sharda
is having Roll Number: 11 ,enrolled for course: Mechanical
Aditya
is having Roll Number: 12 ,enrolled for course: Electrical ->>>
Program
Explanation : In above program,
1)
We have passed default arguments to name and course.
2)
In the first call to the function we simply pass the roll number 10, hence the default
arguments name and course values are associated with it.
3)
In the second call to the function we pass two arguments – Roll number and name,
hence the default value of course argument is considered.
4)
In the third call to the function, all three arguments are passed to the
function. Hence no default argument is considered.
c.
Keyword Arguments
•
Keyword arguments are also called as named arguments. These are the
arguments in which the values are associated with the names. Hence the
positions of the arguments does not matter.
For
example - Consider following programming codes
print("name
name) print("course: "course)
•
Note that the arguments are associated with their keywords name and course. Hence
even if we change their sequence, it does not affect the output.
•
When calling functions in Python, you'll often have to choose between using
keyword arguments or positional arguments. Keyword arguments can often be used
to make function calls more explicit.
d.
Variable Length Arguments
•
The variable length argument is very useful when we do not know the exact number
of arguments that will be passed to a function.
•
The special syntax *args in function definitions in python is used to pass a
variable number of arguments to a
function. It is used to pass a non-keyword, variable length argument list.
Syntax
def
func(*args):
#
#
body of the function
#
Where,
func is the name of the function and *args holds variable length arguments.
For
example –
def
My_Function(*args):
print(args)
print("Call
with two arguments")
My_Function(10,20)
print("Call
with three arguments")
My_Function(10,20,30)
print("Call
with four arguments")
My_Function(10,20,30,40)
Output
Call
with two arguments
(10,
20)
Call
with three arguments
(10,
20, 30)
Call
with four arguments
(10,
20, 30, 40)
>>>
Review Questions
1. Outline about the function definition and call with example.
AU : May-19, Marks 10
2. Why are functions needed ?
AU : May-19, Marks 6
3. Explain the syntax and structure of user defined functions in
Python with examples. Also discuss about parameter passing in functions.
AU : Dec.-19, Marks 12
Problem Solving and Python Programming: UNIT II: Data Types, Expressions, Statements : Tag: Engineering Python : Need, Definition, Call, Syntax, Example Programs | Python Programming - Functions
Problem Solving and Python Programming
GE3151 1st Semester | 2021 Regulation | 1st Semester Common to all Dept 2021 Regulation