Python Functions

pavanbaddi

pavanbaddi

Posted on April 29, 2020

Python Functions

Functions play most of the important parts in a programming language they are a block of subprograms to execute a specific task.

Declaration of function: use def the keyword before declaring function name

def new_func():
    print("Called new_func() method")

new_func() #Calling function

#PYTHON OUTPUT
Called new_func() method

Note: You should declare function before calling else will give error name 'new_func' is not defined

new_func()

def new_func():
    print("Called new_func() method")

#PYTHON ERROR OUTPUT 
NameError: name 'new_func' is not defined

Function Parameters

For processing complex data or to supply required values for the function to process data, we must supply

parameters. The parameters may be string, primitive data types, objects or dictionary, list, tuples etc can be considered as parameters.

Note: Parameter is also called arguments.

In the below examples, we'll be using return keyword inside at the end of the function.

return is a statement returns the processed data from the function. It may be of any type.

Some examples related to function parameters.

Functions without parameter and with return values.

def new_func():
    return 15

a = new_func()

print(a)

#PYTHON OUTPUT 
15

Function with parameters and return value

def new_func(a,b):
    return a+b

a=15
b=3
k = new_func(a,b)

print(k)

#PYTHON OUTPUT 
18

Function with parameters and no return value

def new_func(a,b):
    k = a+b
    print(k)

a=15
b=3
new_func(a,b)

#PYTHON OUTPUT 
18

Function with no parameters and return value

def new_func():
    k = 12*2
    print(k)

new_func()

#PYTHON OUTPUT 
24

Function with default parameter.

def fruits(name="Apple"):
    print(name)

fruits()
fruits("Orange")

#PYTHON OUTPUT 
Apple
Orange    

Recursive Functions

Recursion is a process of calling a function inside it repeatedly until the given condition is True.

To print even numbers

def even(n, i):
    if i%2==0:
        print('{} is a even number \n '.format(i))

    if i<=n:
        i+=1
        return even(n,i)
    else:
        return 0

even(10,1)

#PYTHON OUTPUT
2 is a even number

4 is a even number

6 is a even number

8 is a even number

10 is a even number

You can find complete post here

💖 💪 🙅 🚩
pavanbaddi
pavanbaddi

Posted on April 29, 2020

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related