Python Interview Questions

Python Interview Questions - Control Flow & Functions

Prepare for Python interviews with advanced questions on loops, logical flow, functions, decorators, and closures.

By TechCoder TeamLast updated: 2026-06-23
In a Nutshell

Prepare for Python interviews with advanced questions on loops, logical flow, functions, decorators, and closures. This interview-focused guide covers essential python interview questions - control flow & functions concepts for technical interviews.

Python Interview Questions – Level 2: Control Flow & Functions

Master the logic and modularity of Python. This section covers decision-making, repetition, and the powerful functional programming features of Python.


81. What is conditional statement?

A conditional statement allows a program to execute different blocks of code based on whether a specific condition is True or False.

Example:

age = 18
if age >= 18:
    print("You can vote!")  # Runs because 18 >=18 is True

82. Explain if statement.

The if statement is the simplest form of control flow. It executes code only if the condition evaluates to True.

Example:

temperature = 25
if temperature > 20:
    print("It's a nice day!")  # Runs

83. Explain if-else statement.

Provides an alternative block of code that runs if the if condition is False.

Example:

is_raining = False
if is_raining:
    print("Take an umbrella!")
else:
    print("Enjoy the sunshine!")  # Runs

84. What is elif?

elif (short for else if) allows you to check multiple conditions in sequence. Once a condition is met, the rest of the chain is skipped.

Example:

score = 85
if score >= 90:
    print("A")
elif score >= 80:
    print("B")  # Runs
elif score >= 70:
    print("C")
else:
    print("D")

85. What are nested conditions?

An if statement placed inside another if statement.

[!TIP] Pro Tip: While nesting is powerful, too much of it makes code hard to read (the "arrow" anti-pattern). Try to use logical operators (and, or) to flatten your conditions when possible.

Example:

age = 20
has_license = True

if age >= 18:
    if has_license:
        print("You can drive!")  # Runs
    else:
        print("Get a license first!")
else:
    print("Too young to drive.")

86. What is a loop?

A loop is used to repeat a block of code multiple times as long as a condition is met or until a sequence is exhausted.

Example:

# For loop
for i in range(3):
    print(i)  # 0, 1, 2

87. Difference between for and while loop?

  • For Loop: Used when you know the number of iterations in advance or want to iterate over a sequence (list, string, range).
  • While Loop: Used when you want to repeat code as long as a condition remains True.

Example:

# For loop
print("For loop:")
for fruit in ["apple", "banana", "cherry"]:
    print(fruit)

# While loop
print("\nWhile loop:")
count = 0
while count < 3:
    print(count)
    count += 1

88. What is break?

The break statement immediately terminates the current loop and resumes execution at the next statement after the loop.

Example:

for number in range(10):
    if number == 5:
        break  # Exit loop when we hit 5
    print(number)  # 0, 1, 2, 3, 4

89. What is continue?

The continue statement skips the rest of the code inside the loop for the current iteration and moves to the next iteration.

Example:

for number in range(10):
    if number == 5:
        continue  # Skip printing 5
    print(number)  # 0,1,2,3,4,6,7,8,9

90. What is else with loops?

Python has a unique feature where you can use an else block after a loop. The else block executes only if the loop finishes normally (i.e., it wasn't terminated by a break).

[!IMPORTANT] Interview Question: When is else with a loop useful? Answer: It's perfect for searching. If you find the item and break, the else (which might say "Item not found") won't run.

Example:

numbers = [1, 2, 3, 4]
search_item = 5

for num in numbers:
    if num == search_item:
        print("Found it!")
        break
else:
    print("Item not found!")  # Runs because loop ended without break

91. What is pass in loops?

pass is a null placeholder. It's used if you need a loop structure but haven't written the logic yet.

Example:

for i in range(5):
    pass  # Placeholder for future code
print("Loop done!")

92. What is a function?

A function is a reusable block of code that performs a specific task. Functions help in modularizing code and following the DRY (Don't Repeat Yourself) principle.

Example:

def greet():
    print("Hello!")

greet()  # Call the function
greet()  # Call it again

93. How do you define a function?

Using the def keyword followed by the function name and parentheses.

def greet(name):
    print(f"Hello, {name}")

greet("Alice")  # Hello, Alice

94. What are parameters and arguments?

  • Parameters: Variables listed in the function definition (the placeholders).
  • Arguments: The actual values passed to the function when it is called.

Example:

def add(a, b):  # a and b are parameters
    return a + b

result = add(5, 3)  # 5 and 3 are arguments
print(result)  # 8

95. What is return?

The return statement exits a function and sends a result back to the caller. If no return is specified, the function returns None.

Example:

def square(x):
    return x ** 2

result = square(4)
print(result)  # 16

96. What is default argument?

A parameter that assumes a default value if no argument is provided in the function call.

def greet(name="Guest"):
    print(f"Hello, {name}")

greet()  # Hello, Guest
greet("Alice")  # Hello, Alice

97. What is keyword argument?

Arguments passed by explicitly stating the parameter name. This allows you to pass arguments in any order.

def describe_pet(animal_type, pet_name):
    print(f"I have a {animal_type} named {pet_name}")

# Call with keyword arguments in any order
describe_pet(pet_name="Rex", animal_type="dog")

98. What is *args?

*args allows a function to accept any number of positional arguments. It collects them into a tuple.

Example:

def sum_all(*args):
    total = 0
    for num in args:
        total += num
    return total

print(sum_all(1, 2, 3))  # 6
print(sum_all(10, 20))   # 30

99. What is **kwargs?

**kwargs allows a function to accept any number of keyword arguments. It collects them into a dictionary.

Example:

def print_info(**kwargs):
    for key, value in kwargs.items():
        print(f"{key}: {value}")

print_info(name="Alice", age=25, city="New York")

100. What is recursion?

Recursion is when a function calls itself. It must have a base case to prevent infinite loops (which eventually lead to a RecursionError or stack overflow).

Example:

def factorial(n):
    if n <= 1:  # Base case
        return 1
    return n * factorial(n-1)  # Recursive call

print(factorial(5))  # 120 (5*4*3*2*1)

101. What is lambda function?

A lambda function is a small, anonymous function defined with the lambda keyword. It can have any number of arguments but only one expression.

add = lambda x, y: x + y
print(add(5, 3)) # 8

102. Difference between lambda and def?

  • def: Used for complex functions with multiple lines, documentation, and a name.
  • lambda: Used for simple, one-off functions often passed as arguments to other functions (like map or filter).

103. What is map()?

The map() function applies a given function to each item of an iterable (list, tuple, etc.) and returns an iterator.

nums = [1, 2, 3]
squared = list(map(lambda x: x**2, nums)) # [1, 4, 9]

104. What is filter()?

The filter() function constructs an iterator from elements of an iterable for which a function returns True.

nums = [1, 2, 3, 4]
evens = list(filter(lambda x: x % 2 == 0, nums)) # [2, 4]

105. What is reduce()?

Part of the functools module, reduce() applies a rolling computation to sequential pairs of values in an iterable.

from functools import reduce
nums = [1, 2, 3, 4]
product = reduce(lambda x, y: x * y, nums) # product of all elements

106. What is scope?

Scope refers to the region of a program where a variable is accessible. Python follows the LEGB rule:

  • Local, Enclosing, Global, Built-in.

107. What is local scope?

Variables defined inside a function are in the local scope and cannot be accessed outside that function.

def my_func():
    x = 10  # Local scope
    print(x)

my_func()
# print(x) # Error: NameError (x is not defined)

108. What is global scope?

Variables defined outside any function or class are in the global scope and can be accessed throughout the module.

x = 100 # Global scope

def check_global():
    print(x) # Accesses global x

check_global() # 100

109. What is nonlocal keyword?

Used inside nested functions to indicate that a variable refers to a variable in the nearest enclosing scope (excluding global).

def outer():
    x = "local"
    def inner():
        nonlocal x
        x = "nonlocal" # Modifies outer x
    inner()
    print(x) 

outer() # "nonlocal"

110. What is global keyword?

Used inside a function to indicate that a variable refers to a variable in the global scope.

count = 0

def increment():
    global count
    count += 1 # Modifies the global variable

increment()
print(count) # 1

111. What is docstring?

A docstring (documentation string) is a literal string that occurs as the first statement in a module, function, class, or method definition.

def add(a, b):
    """
    Adds two numbers and returns the result.
    Args:
        a (int): First number
        b (int): Second number
    """
    return a + b

print(add.__doc__)

113. What is call stack?

The call stack is a mechanism used by the interpreter to keep track of function calls. When a function is called, it's pushed onto the stack; when it returns, it's popped off.

114. What is tail recursion?

Tail recursion is a specific form of recursion where the recursive call is the very last action in the function.

[!CAUTION] Important Note: Python does not optimize for tail recursion. Deep recursion will still hit the recursion limit.

115. What is function annotation?

A way to associate metadata with function parameters and return values.

def add(x: int, y: int) -> int:
    return x + y

116. What are closures?

A closure is a function object that remembers values in its enclosing scope even if they are no longer in memory.

def outer(msg):
    def inner():
        print(msg)
    return inner

hi_func = outer("Hello")
hi_func() # "Hello" (remembers 'msg')

117. What is decorator?

A decorator is a function that takes another function and extends its behavior without explicitly modifying it. It uses the @ syntax.

def my_decorator(func):
    def wrapper():
        print("Something is happening before the function is called.")
        func()
        print("Something is happening after the function is called.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

118. Why use decorators?

Decorators are used for "cross-cutting concerns" like logging, authentication, timing, or caching.

# Conceptual example
@login_required
@log_activity
def delete_user(user_id):
    # This core logic is kept clean
    db.delete(user_id)

119. What is nested function?

A function defined inside another function. It can access variables from the outer function's scope.

def outer(x):
    def inner(y):
        return x + y
    return inner(5)

print(outer(10)) # 15

120. What is higher-order function?

A higher-order function is a function that does at least one of the following:

  • Takes one or more functions as arguments (e.g., map, filter).
  • Returns a function as its result.
# Takes a function as argument
def apply_twice(func, arg):
    return func(func(arg))

def add_five(x):
    return x + 5

print(apply_twice(add_five, 10)) # 20 ( (10+5)+5 )