User defined function python – Python Interview Questions on User Defined Functions

User defined function python: We have compiled most frequently asked Python Interview Questions which will help you with different expertise levels. You can also Observe Python coding questions and answers, Python tricky interview questions, Python coding interview questions geeksforgeeks, Python coding questions for placement, Python interview questions for 5 years experience, Tcs python interview questions, Python interview questions and answers, Python interview questions and answers pdf, Python interview questions and answers for freshers, Python interview questions on functions, Questions on user defined functions in python, Python interview questions on decorators, Python interview questions on oops, Python interview questions on oops concepts, Python interview questions on object oriented programming, Python oops interview questions with realtime examples, Python interview questions on variables.

Python Interview Questions on User Defined Functions

Python user defined function: While going through the chapter on standard data types you have learned about several inbuilt defined by functions. These functions already exist in Python libraries. However, programming is all about creating your own functions that can be called at any time. A function is basically a block of code that will execute only when it is called. To define a function we use the keyword def as shown in the following code:

def function_name ( ):
    to do statements

So, let’s define a simple function:

def new_year_greetings( ) :
    print("Wish you a very happy and properous new year")
new_year_greetings( )

The new_year_greetings( ) function is a very simple function that simply displays a new year message when called.

You can also pass a parameter to a function. So, if you want the function new_year_greetings( ) to print a personalized message, we may want to consider passing a name as a parameter to the function.

def new_year_greetings(name):
print("Hi ", name.upper(),"! ! Wish you a very happy and prosperous new year")
name = input("Hello!! May I know your good name please: ")
new_year_greetings(name)

The output for the code given above would be as follows:

Hello!! May I know your good name please: Jazz
Hi JAZZ !! Wish you a very happy and prosperous new year
>>>

Indentation is very important. In order to explain, let’s add another print statement to the code.

def new_year_greetings (name) :
print("Hi ", name.upper(),"! ! Wish you a very !
happy and prosperous new year")
print("Have a great year")
name = input("Hello!! May I know your good name please: ")
new_year_greetings(name)

So, when the function is called, the output will be as follows:

Hello!! May I know your good name please: Jazz
Hi JAZZ !! Wish you a very happy and properous new year
Have a great year

Improper indentation can change the meaning of the function: ;

def new_year_greetings(name):
print("Hi ", name.upper( ),"! ! Wish you a very happy and properous new year")
print("Have a great year")

In the code given above the second print, the statement will be executed even if the function is not called because it is not indented properly and it is no more part of the function. The output will be as follows:

Have a great year

Multiple functions can also be defined and one function can call the other.

def new_year_greetings(name):
print("Hi ", name.upper( ),"!! Wish you a very happy and properous new year")
extended_greetings( )
def extended_greetings( ):
print("Have a great year ahead") name = input ("Hello! !' May I know your good name please: ")
new-_year_greetings (name)

When a new year greeting ( ) a message is printed and then it calls the extended_greetings( ) function which prints another message.

Output

Hello!! May I know your good name please: Jazz
Hi JAZZ !! Wish you a very happy and properous new year
Have a great year ahead

Multiple parameters can also be passed to a function.

def new_year_greetings(name1,name2):
print("Hi ",namel," and ",name2,"!! Wish you a very happy and properous new year")
extended_greetings( )
def extended_greetings( ):
print("Have a great year ahead") new_year_greetings("Jazz","George")

The output will be as follows:

Hi Jazz and George !! Wish you a very happy and properous new year Have a great year ahead

Question 1.
What are the different types of functions in Python?
Answer:
There are two types of functions in Python:

  1. Built-in functions: library functions in Python
  2. User-defined functions: defined by the developer

Question 2.
Why are functions required?
Answer:
Many times in a program a certain set of instructions may be called again and again. Instead of writing the same piece of code where it is required it is better to define a function and place the code in it. This function can be called whenever there is a need. This saves time and effort and the program can be developed easily. Functions help in organizing coding work and testing of code also becomes easy.

Question 3.
What is a function header?
Answer:
The first line of function definition that starts with def and ends with a colon (:) is called a function header.

Question 4.
When does a function execute?
Answer:
A function executes when a call is made to it. It can be called directly from the Python prompt or from another function.

Question 5.
What is a parameter? What is the difference between a parameter and an argument?
Answer:
A parameter is a variable that is defined in a function definition whereas an argument is an actual value that is passed on to the function. The data carried in the argument is passed on to the parameters. An argument can be passed on as a literal or as a name.

def function_name(param):

In the preceding statement, param is a parameter. Now, take a look at the statement given below, it shows how a function is called:

function_name(arg):

arg is the data that we pass on while calling a function. In this statement arg is an argument.
So, a parameter is simply a variable in method definition and an argument is the data passed on the method’s parameter when a function is called.

Question 6.
What is a default parameter?
Answer:
The default parameter is also known as the optional parameter. While defining a function if a parameter has a default value provided to it then it is called a default parameter. If while calling a function the user does not provide any value for this parameter then the function will consider the default value assigned to it in the function definition.

Question 7.
What are the types of function arguments in Python?
Answer:
There are three types of function arguments in Python:
1. Default Arguments: assumes a default value, if no value is provided by the user.

def func(name = "Angel"):
print("Happy Birthday ", name)
func ( )
Happy Birthday Angel

You can see that the default value for the name is “Angel” and since the user has not provided any argument for it, it uses the default value.

2. Keyword Arguments: We can call a function and pass on values irrespective of their positions provided we use the name of the parameter and assign them values while calling the function.

def func(name1, name2):
print("Happy Birthday", name1, " and ",name2,"!!!")

Output:

func(name2 = "Richard",namel = "Marlin")
Happy Birthday Marlin and Richard !!!

3. Variable-length Arguments: If there is uncertainty about how many arguments might be required for processing a function we can make use of variable-length arguments. In the function definition, if a single is placed before the parameter then all positional arguments from this point to the end are taken as a tuple. On the other hand, if “**” is placed before the parameter name then all positional arguments from that point to the end are collected as a dictionary.

def func(*name, **age): print(name)
print(age)
func("Lucy","Aron","Alex", Lucy = "10",Aron ="15",Alex="12")

Output:

('Lucy', 'Aron', 'Alex')
{'Lucy': '10', 'Aron': '15', 'Alex': '12'}

Question 8.
What is a fruitful and non-fruitful function?
Answer:
The fruitful function is a function that returns a value and a non-fruitful function does not return a value. Non-fruitful functions are also known as void functions.

Question 9.
Write a function to find factorial of a number using for loop
Answer:
The code for finding a factorial using for loop will be as follows:
Code

def factorial(number):
j = 1
if number==0|number==1:
print(j)
else:
for i in range (1, number+1):
print (j," * ",i," = ", j * i)
j = j*i
print(j)

Execution

factorial(5)

Output

1 * 1 = 1
1 * 2 = 2
2 * 3 = 6
6 * 4 = 24
24 * 5 = 120
120

Question 10.
Write a function for Fibonacci series using a for loop:
Answer:
Fibonacci series: 0, 1, 1, 2, 3, 5, 8….
We take three variables:
i, j, and k:

  • If i = 0, j =0, k =0
  • If i =1, j =1, k =0
  • If i> 1:

temp =j
j =j+k
k=temp
The calculations are as shown as follows:

I K J
0 0 0
1 0 1
2 0 Temp = j = 1

J = j + k = 1+10 = 1

K = temp = 1

3 1 Temp = j = 1

J = j +k = 1 +1 = 2

K = temp = 1

4 1 Temp = j = 2

J = j + k = 2+1 = 3

K = temp = 2

5 2 Temp = j = 3

J = j + k = 3+2 = 5

K = temp = 3

6 3 Temp = j =5

J = j + k = 5+3=8

K = temp = 1

Code

def fibonacci_seq (num) :
i = 0
j = 0
k = 0
for i in range(num):
if i==0:
print(j)

elif i==1:
j = 1
print(j)
else:
temp = j
j = j+k
k = temp
print(j)

Execution

fibonacci_seq (10)

Output

0
1
1
2
3
5
8
13
21
34

Question 11.
How would you write the following code using a while loop?
[Note: You may want to refer to recursion before attempting this question.]

def test_function(i, j) :
if i == 0:
return j;
else:
return test_function(i-1, j+1)
print(test_function(6,7) )

Answer:

def test_function (i,j) :
while i > 0:
i =i- 1
j = j + 1
return j
print(test_function(6, 7) )

Question 12.
Write code for finding the HCF of two given numbers.
Answer:
HCF stands for Highest Common Factor or Greatest Common Divisor for two numbers. This means that it is the largest number within the range of 1 to smaller of the two given numbers that divides the two numbers perfectly giving the remainder as zero.
1. Define a function hcf() that takes two numbers as input.

def hcf(x,y):

2. Find out which of the two numbers is greatest, the other one will be the smallest.

small_num = 0
if x > y:
small_nura = y
else:
small_num = x

Set a for loop for the range 1 to small_num+1. (We take the upper limit as small_num+l because the for loop operates for one number less than the upper limit of the range). In this for loop, divide both the numbers with each number in the range and if any number divides both, perfectly assign that value to have as shown in the following code:

for i in range(1,small_num+1):
if (x % i == 0) and (y % i == 0) :
hcf = i

Suppose, the two numbers are 6 and 24, first both numbers are divisible by 2. So, hcf = 2, then both numbers will be divisible by 3 so, the value of 3 will be assigned to 3. Then the loop will encounter 6, which will again divide both the numbers equally. So, 6 will be assigned to hcf. Since the upper limit of the range has reached, the function will finally have hcf value of 6.
3. Return the value of hcf: return hcf
Code

def hcf (x,y) :
small_num = 0
if x>y:
small_num = y
else:
small_num = x

for i in range (1, small_num+1):
if (x % i ==0) and (y % i ==0):
hcf = i
return hcf

Execution

print (hcf(6,24))

Output

6

Scope of a variable

The scope of a variable can be used to know which program can be used from which section of a code. The scope of a variable can be local or global.
Local variables are defined inside a function and global functions are defined outside a function. Local variables can be accessed only within
the function in which they are defined. A global variable can be accessed throughout the program by all functions.

total = 0 # Global variable
def add(a,b) :
sumtotal = a+b #Local variable
print("inside total = ", total)

Question 13.
What will be the output of the following code?

total = 0
def add(a,b):
global total
total = a+b
print("inside total = ", total)

add(6,7)
print("outside total = ", total)

Answer:
The output will be as follows:

inside total = 13
outside total = 13

Question 14.
What would be the output for the following code?

total = 0
def add(a,b):
total = a+b
print("inside total = ", total)

add(6,7)
print("outside total = ", total)

Answer:

inside total = 13
outside total = 0

Question 15.
Write the code to find HCF using Euclidean Algorithm.
Answer:
The following figure shows two ways to find HCF.
On the left-hand side, you can see the traditional way of finding the HCF.

On the right-hand side is the implementation of the Euclidean Algorithm to find HCF.
Python Interview Questions on User Defined Functions chapter 5 img 1

Code

def hcf(x,y):
small_num = 0
greater_num = 0
temp = 0
if x > y:
small_num = y
greater_num = x
else:
small_num = x
greater_num = y

while small_num > 0:
temp = small_num
small_num = greater_num % small_num
greater_num = temp
return temp

Execution

print("HCF of 6 and 2 4 = ",hcf(6,24))
print("HCF of 400 and 300 = ",hcf(400,300))

Output

HCF of 6 and 24= 6
HCF of 400 and 300 = 100

Question 16.
Write code to find all possible palindromic partitions in a string.
Answer:
The code to find all possible palindromic partitions in a string will involve the following steps:

  1. Create a list of all possible substrings.
  2. Substrings are created by slicing the strings as all possible levels using for loop.
  3. Every substring is then checked to see if it is a palindrome.
  4. The substring is converted to a list of single characters.
  5. In reverse order, the characters from the list are added to a string.
  6. If the resultant string matches the original string then it is a palindrome.

Code

def create_substrings(x):
substrings = [ ]

for i in range(len (x)) :
for j in range(1, len(x)+l):
if x[i:j] != ' ' :
substrings.append(x[i:j])
for i in substrings:
check_palin(i)

def check_palin(x):
palin_str = ' '
palin_list = list(x)
y = len(x)-1
while y>=0:
palin_str = palin_str + palin_list[y]
y = y-1
if(palin_str == x):
print("String ", x," is a palindrome")

Execution

x = ''malayalam"
create_substrings(x)

Output

String m is a palindrome
String malayalam is a palindrome
String a is a palindrome
String ala is a palindrome
String alayala is a palindrome
String 1 is a palindrome
String layal is a palindrome
String a is a palindrome
String aya is a palindrome
String y is a palindrome
String a is a palindrome
String ala is a palindrome
String 1 is a palindrome
String a is a palindrome
String m is a palindrome

Question 17.
What are anonymous functions?
Answer:
Lambda facility in Python can be used for creating a function that has no names. Such functions are also known as anonymous functions. Lambda functions are very small functions that have just one line in the function body, ft requires no return statement.

total = lambda a, b: a + b
total(10,50)
60

Question 18.
What is the use of a return statement?
Answer:
The return statement exits the function and hands back value to the function’s caller. You can see this in the code given below. The function func( ) returns the sum of two numbers. This value assigned to “total” and then the value- of the total is printed.

def func(a,b):
return a+b
total = func(5,9)
print(total)
14

Question 19.
What will be the output of the following function?

def happyBirthday( ):
print("Happy Birthday")
a = happyBirthday() print(a)

Answer:

Happy Birthday
None

Question 20.
What will be the output of the following code?

def outerWishes( ):
global wishes
wishes = "Happy New Year"
def innerWishes():
global wishes
wishes = "Have a great year ahead"
print('wishes =', wishes)
wishes = "Happiness and Prosperity Always"
router wishes( )
print('wishes =', wishes)

Answer:
The output will be as follows:

wishes = Happy New Year

Question 21.
What is the difference between passing immutable and mutable objects as an argument to a function?
Answer:
If immutable arguments like strings, integers, or tuples are passed to a function, the object reference is passed but the value of these parameters cannot be changed. It acts like a pass-by-value call. Mutable objects too are passed by object reference but their values can be changed.