Wednesday, June 2, 2021

Python - Functions and Recursions


  • A function is a group of statements performing a specific task.
  • When a program gets bigger in size and its complexity grows, it gets difficult for a programmer to keep track of which piece of code is doing what!
  • A function can be reused by the programmer in a given program any number of times.

Example and Syntax of a function

The syntax of a function looks as follows:

def func1():


This function can be called any number of times, anywhere in the program.

Function call:

Whenever we want to call a function, we put the name of the function followed by parenthesis as follows:

func1()          #This is called function call

Function definition:

The part containing the exact set of instructions that are executed during the function call.

Types of functions:

There are two types of functions in Python:

  • Built-in functions #Already present in Python
  • User-defined functions #Defined by the user

Examples of built-in function includes len(), print(), range(), etc.

The func1() function we defined is an example of user-defined function.

Functions with arguments:

A function can accept some values it can work with. We can put these values in the parenthesis. A function can also return values as shown below:

def greet(name):

gr = “Hello” + name

return gr

a = greet(“Tom”) #“Tom” is passed to greet in name

# a will now contain “Hello Tom”

Default Parameter Value:

We can have a value as default argument in a function.

If we specify name = “stranger” in the line containing def, this value is used when no argument is passed.

For Example:

def greet(name=’stranger’):

#function body

greet()                       #Name will be ‘stranger’ in function body(default)

greet(“Tom”)        #Name will be “Tom” in function body(passed)


Recursion is a function which calls itself.

It is used to directly use a mathematical formula as a function. For example:

factorial(n) = n * factorial(n-1)

This function can be defined as follows:

def factorial(n):

if i == 0 or i == 1 : #Base condition which doesn’t call the function any further

return i


return n*factorial(n-1) #Function calling itself

The programmer needs to be extremely careful while working with recursion to ensure that the function doesn’t infinitely keep calling itself.

Recursion is sometimes the most direct way to code an algorithm.



Write a program using the function to find the greatest of three numbers.

n1=int(input("Enter 1st num:"))
n2=int(input("Enter 2nd num:"))
n3=int(input("Enter 3rd num:"))
def greatestNumber(a,b,c):
    if a>b:
        if a>c:
            return a
            return c
        if b>c:
            return b
            return c

print(f"Greatest of {n1}{n2} and {n3} is: {g}")

Write a python program using the function to convert Celsius to Fahrenheit.

# (0°C × 9/5) + 32 = 32°F
def celsiusToFahrenheit(c):
    return (c * (9/5) + 32)


How do you prevent a python print() function to print a new line at the end?

print("something", end="")

Write a recursive function to calculate the sum of first n natural numbers.

# sum of n natural numbers
# sum(n)= n + sum(n-1)

def sumOfNaturalNumbers(n):
    if n==1:
        return 1
        return n + sumOfNaturalNumbers(n-1)

num = int(input("Enter n number to sum for natural numbers:"))


Write a python function to print the first n lines of the following pattern.


**       #For n = 3


Write a python function to remove a given word from a string and strip it at the same time.

def removeWordStrp(string,word):
    newString = string.replace(word,"").strip()
    return newString

string = "      Joy is a good boy       "


No comments:

Post a Comment

Featured Post

11g to 12c OSB projects migration points

1. Export 11g OSB code and import in 12c Jdeveloper. Steps to import OSB project in Jdeveloper:   File⇾Import⇾Service Bus Resources⇾ Se...