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-02
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.

82. Explain if statement.

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

83. Explain if-else statement.

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

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.

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.

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.

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.

88. What is break?

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

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.

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.

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.

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.

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}")

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.

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.

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}")

97. What is keyword argument?

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

greet(name="Alice")

98. What is *args?

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

99. What is **kwargs?

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

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).

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 )