Let’s check out some exercises that will help understand “Defining Functions” better.

Exercise 16-a

Define a function named f_1 which will print "Hello World!"


The syntax for defining functions is:

def FunctionName ():

After your 1st line of function definition your statement needs to be indented either as:

  1. 1 Tab key
  2. 4 Space characters.
def f_1():
    print("Hello World!")

Exercise 16-b

Now define the same function f_1 and assign it to variable ans_1. See what happens.


The syntax for defining functions is:

def FunctionName ():

After your 1st line of function definition your statement needs to be indented either as:

  1. 1 Tab key
  2. 4 Space characters.
ans_1 = f_1()

Exercise 16-c

Now define the same f_1 function this time so that it returns a value instead of just printing it..


return keyword will allow your function to return a value.

def f_1():
    return "Hello World!"

Exercise 16-d

Now create a function named f_1 which both prints and returns "Hello World!"


It’s important to note that after return statement you can not have any line in your function.
Return ends your function. So make sure any other statement you’d like to make comes before return.

def f_1():
    print("Hello World!")
    return "Hello World!"

Exercise 16-e

Create a function named f_1 which always returns the number: 100 .


Simply return 100.

def f_1(x):
    return 100

Exercise 16-f

Create a function named f_1 which takes an integer as input and then returns it.


You can type a variable inside the parenthesis and then return it in the function.

def f_1(x):
    return x

Exercise 16-g

Can you define a function that takes a list as input and returns the reverse of that list?


.reverse() method will reverse the indexing of a list.

def f_1(lst):
    return lst.reverse()

Exercise 16-h

Write a function named f_1 which will ask user for their name and print Hello!, Name


You can use input() function to ask for user input. Then you can assign it to a variable.

def f_1():
    name = input("Please enter your name.")
    print("Hello!, ", name)

Exercise 16-i

Write 2 functions named f_1 and f_2. First one takes a number as input and returns that number +5, second function takes a number as input and returns first function's result multiplied by 2.


After defining the first function just pass it inside the second function.

def f_1(x):
    return x+5
def f_2(y):
return f_1(y)*2