0% found this document useful (0 votes)
158 views9 pages

Function in Python

1. A function is a block of code that performs a specific task. It helps break programs into modular chunks, avoids repetition, and makes code reusable. 2. The key components of a function definition are the def keyword, function name, parameters, colon, docstring, statements with the same indentation, and optional return statement. 3. Functions can take default and keyword arguments, variable length arguments using *args, and have local and global scopes. Recursive functions call themselves and are used to break down complex problems.

Uploaded by

Vikas Khare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
0% found this document useful (0 votes)
158 views9 pages

Function in Python

1. A function is a block of code that performs a specific task. It helps break programs into modular chunks, avoids repetition, and makes code reusable. 2. The key components of a function definition are the def keyword, function name, parameters, colon, docstring, statements with the same indentation, and optional return statement. 3. Functions can take default and keyword arguments, variable length arguments using *args, and have local and global scopes. Recursive functions call themselves and are used to break down complex problems.

Uploaded by

Vikas Khare
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1/ 9

Definition: In Python, function is a group of related statements that perform a

specific task.Functions help break our program into smaller and modular chunks.
As our program grows larger and larger, functions
make it more organized and manageable.Furthermore, it avoids repetition and
makes code reusable.

Syntax of Function

def function_name(parameters):

"""docstring"""

statement(s)

Above shown is a function definition which consists of following components.

1. Keyword def marks the start of function header.


2. A function name to uniquely identify it. Function naming follows the
same rules of writing identifiers in Python.
3. Parameters (arguments) through which we pass values to a function.
They are optional.

4. A colon (:) to mark the end of function header.

5. Optional documentation string (docstring) to describe what the function


does.

6. One or more valid python statements that make up the function body.
Statements must have same indentation level (usually 4 spaces).

7. An optional return statement to return a value from the function.


The return statement

The  return  statement is used to exit a function and go back to the place from
where it was called.
Syntax of return
return [expression_list]

Example

# A simple Python function to check

# whether x is even or odd

def evenOdd( x ):

    if (x % 2 == 0):

        print "even"

    else:

        print "odd"

  

# Function Calling

evenOdd(2)

evenOdd(3)

Output:
even
odd
2. Write a python program to find the factorial of any number using function.

def fact(num): FUNCTION DEFINITION

f=1

for i in range(1,num+1):
FUNCTION BODY
f=f*i

return f

num=int(input("Enter any number"))

FUNCTION CALLING
print(fact(num))

The function allows us to implement code reusability. There are three kinds of functions

 Built-in functions ( As the name suggests, these functions come with the Python language,
for example, help() to ask for any help, max()- to get maximum value, type()- to return the
type of an object and many more.)
 User-defined functions ( These are the functions that users create to help them, like the
“sum” function we have created above).
 Anonymous Functions (also called lambda functions and unlike normal function which is
defined using def keyword are defined using lambda keyword).

Default arguments:

A default argument is a parameter that assumes a default value if a value is not


provided in the function call for that argument.The following example illustrates Default
arguments.

# Python program to demonstrate


# default arguments
def myFun(x, y=50):
    print("x: ", x)
    print("y: ", y)
  
# Driver code (We call myFun() with only
# argument)
myFun(10)

Output:
('x: ', 10)
('y: ', 50)

Keyword arguments:
The idea is to allow caller to specify argument name with values so that caller does not need to
remember order of parameters.

# Python program to demonstrate Keyword Arguments


def student(firstname, lastname): 
     print(firstname, lastname) 
    
    
# Keyword arguments                  
student(firstname ='Python', lastname ='Practice')    
student(lastname ='Practice', firstname ='Python')   

Output:
('Python', 'Practice')
('Python', 'Practice')

Variable length arguments:


We can have both normal and keyword variable number of arguments. Please see this for
details.

# Python program to illustrate  


# *args for variable number of arguments
def myFun(*argv): 
    for arg in argv: 
        print (arg)
    
myFun('Hello', 'Welcome', 'to', 'python') 
Output:
Hello
Welcome
to
python
Scope of Variables
All variables in a program may not be accessible at all locations in that program. This
depends on where you have declared a variable.
The scope of a variable determines the portion of the program where you can access a
particular identifier. There are two basic scopes of variables in Python −

 Global variables
 Local variables

Global vs. Local variables


Variables that are defined inside a function body have a local scope, and those defined
outside have a global scope.

RECURSIVE FUNCTION

What is recursion?

Recursion is the process of defining something in terms of itself.

A physical world example would be to place two parallel mirrors facing each
other. Any object in between them would be reflected recursively.

Python Recursive Function

In Python, we know that a function can call other functions. It is even possible


for the function to call itself. These types of construct are termed as recursive
functions.

The following image shows the working of a recursive function called  recurses .
Following is an example of a recursive function to find the factorial of an
integer.

Factorial of a number is the product of all the integers from 1 to that number.
For example, the factorial of 6 (denoted as 6!) is  1*2*3*4*5*6 = 720 .

Example of a recursive function


def factorial(x):
"""This is a recursive function to find the factorial of an integer"""

if x == 1:
return 1
else:
return (x * factorial(x-1))

num = 3
print("The factorial of", num, "is", factorial(num))

In the above example,  factorial()  is a recursive function as it calls itself.


When we call this function with a positive integer, it will recursively call itself
by decreasing the number.
Each function multiplies the number with the factorial of the number below it
until it is equal to one. This recursive call can be explained in the following
steps.

factorial(3) # 1st call with 3

3 * factorial(2) # 2nd call with 2

3 * 2 * factorial(1) # 3rd call with 1

3 * 2 * 1 # return from 3rd call as number=1

3 * 2 # return from 2nd call

6 # return from 1st call

Let's look at an image that shows a step-by-step process of what is going on:
WORKING OF A RECURSIVE FACTORIAL FUNCTION

Our recursion ends when the number reduces to 1. This is called the base
condition.Every recursive function must have a base condition that stops the
recursion or else the function calls itself infinitely.

Advantages of Recursion

1. Recursive functions make the code look clean and elegant.

2. A complex task can be broken down into simpler sub-problems using


recursion.
3. Sequence generation is easier with recursion than using some nested
iteration.

Disadvantages of Recursion

1. Sometimes the logic behind recursion is hard to follow through.

2. Recursive calls are expensive (inefficient) as they take up a lot of


memory and time.

3. Recursive functions are hard to debug.

You might also like