Python Interview Questions Custom Functions

Mondo Technology Updated on 2024-02-29

Custom functions in Python can use the keyword def, as shown below:

def function_name ( 

to do statements

Let's define a simple function:

def hello() 

print("hello world!")

The hello() function is a very simple function that only displays hello world!.

You can also pass arguments to a function. If you want the function hello() to print a personalized message, you need to pass the arguments to the function.

def hello(name) :

print("hello", name)

Function calls.

def hello(name) :

print("hello", name)

name = input("Please enter a first name:")

hello(name)

Output: Please enter the first name: jack

hello jack

There are two types of functions in Python:

Built-in Functions: Library Functions in PythonUser-Defined Functions: Defined by a developer in a program, many times a certain set of ** may be called again and again. Instead of writing the same segment where needed, define a function and put it in. This function can be called whenever needed. This saves time and effort, helps to organize your coding efforts, and makes testing easy.

The first line of a function definition that starts with def and ends with a colon (: is called the function header.

When a call is made to a function, the function is executed. It can be called directly from a python prompt or other function.

A parameter is a variable that is defined in a function definition, and a variable is the actual value passed to the function. The data carried in the variable is passed to the parameter.

def function_name(param):

In the preceding statement, param is a parameter.

Default parameters are also known as optional parameters. When defining a function, if a parameter provides a default value, it is called a default parameter. If the user doesn't provide any value for this parameter when the function is called, the function will use its default value. ** age is an optional parameter as follows.

def hello(name, age=10) :

print(f"my name is ,i'm years old.")

name = input("Please enter a first name:")

hello(name)

Output: Please enter the first name: jack

my name is jack,i'm 10 years old.

def hello(name, age=10) :

print(f"my name is ,i'm years old.")

name = input("Please enter a first name:")

hello(name,20)

Output: Please enter the first name: jack

my name is jack,i'm 20 years old.

There are three types of function arguments in Python:

Default Parameter: If the user does not provide any value, the default value is assumed.

Keyword parameters: For functions that have multiple default parameter values, you must specify their parameter values in order. When calling a function, use the parameter's keyword to specify which parameter to assign a value to, regardless of their position.

def hello(name, age) :

print(f"my name is ,i'm years old.")

hello(age=10,name='jack')

Variable-length parameter: If you are uncertain about the number of function parameters, you can use the variable-length parameter. In the function definition, a variable-length parameter is marked with an asterisk, and the multiple parameters passed in will be encapsulated into a tuple into the function. You can also pass in multiple keyword parameters at once to make the keyword parameters longer by passing in both the parameter name and the actual object to the input object. Unlike variable-length arguments, variable-length keyword arguments need to be described with two asterisks, and the actual incoming process is that Python will convert them to a dictionary for incoming.

def mysum(*num): 

r = 0for i in num:

r += i

return(r)

print(mysum(1,2))

print(mysum(1,2,3))

def myfun(**kwargs):

for i in kwargs:

print(i,'-',kwargs[i])

myfun(a=10, b=20, c=30, d=40)

If you pass immutable parameters such as strings, tuples, etc., to a function, object references are passed, but the values of those parameters cannot be changed. It works similarly to pass-by-value calls. Mutable objects are also passed through object references, but their values can be changed.

def factorial(number):

j = 1if number==0|number==1:

print(j)

else:for i in range (1, number+1):

print (j," * ",i," = ", j * i)

j = j*i

factorial(5)

def fibonacci(num):

i = 0j = 0

k = 0for i in range(num):

if i==0:

print(j)

elif i==1:

j = 1print(j)

else:temp = j

j = j+k

k = temp

print(j)

fibonacci(10)

def func(i, j):

if i == 0:

return j

else:return func(i-1, j+1)

print(func(6,7))

def func(i,j):

while i > 0:

i =i- 1

j = j + 1

return j

print(func(6, 7))

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

print (hcf(6,24))

total = 0

def add(a,b):

global total

total = a+b

print("inside total = ", total)

add(6,7)

print("outside total = ", total)

The output is as follows:

inside total = 13

outside total = 13

total = 0

def add(a,b):

total = a+b

print("inside total = ", total)

add(6,7)

print("outside total = ", total)

The output is as follows:

inside total = 13

outside total = 0

Euclidean's algorithm, also known as tossing and dividing, refers to the greatest common divisor used to calculate two non-negative integers a,b. The greatest common divisor of two integers is equal to the greater of the smaller of them and the greatest common divisor of the remainder of the division of the two numbers. The previous use of recursive functions to calculate the greatest common divisor also used the use of Euclidean's algorithm.

def gcd(a, b): 

while b != 0:

a, b = b, a % b

return a

a=28b=72

print(f"The greatest common divisor of and is:")

Slice the string into all possible substrings by using the for loop. Then check each substring to see if it's a palindrome.

The substring is converted into a list of individual characters. In reverse order, concatenate the characters in the list as strings. If the resulting string matches the original string, it is a palindrome.

def create_substrings(x):

substrings = [

for i in range(len(x)):

for j in range(1, len(x)+1):

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(x,"It's palindrome! ")

x = "mlayalam"

create_substrings(x)

Output.

m is palindrome! l is a palindrome! layal is palindrome! a is a palindrome! aya is a palindrome! y is a palindrome! a is a palindrome! ALA is a palindrome! l is a palindrome! a is a palindrome! m is palindrome! 
Lambda in Python can be used to create functions that don't have names. Such functions are also known as anonymous functions. There is only one line in the lambda function body, and no return statement is required.

total = lambda a, b: a + b

print(total(10,50))

The return statement exits the function and returns the value to the caller of the function, that is, the result of the function execution.

def func(a,b):

return a+b

total = func(1, 2)

print(total)

def happybirthday():

print("happy birthday")

a = happybirthday()

print(a)

Output.

happy birthdaynone

m = 1

n = 2def update_variables():

global m

m = 11

n = 22

update_variables()

print(m)

print(n)

It's not easy to create an article, if you like this article, please follow, like and share it with your friends. If you have comments and suggestions, please give us feedback in the comments!

Related Pages