Control Flow in Python - Interview Questions and Answers
Control flow refers to the order in which individual statements, instructions, or function calls are executed or evaluated in a program. Python's control flow statements allow decision-making, repetition, and control over execution.
An if statement evaluates an expression and executes the associated block of code if the condition is true. An elif statement is used when there are multiple conditions to check; if the previous if or elif conditions are false, the elif block will be evaluated.
The else statement executes a block of code if none of the preceding if or elif conditions are true.
If none of the conditions are true, the code in the else block will be executed. If there is no else block, no code will run.
No, you can only have one else block, but you can have multiple elif blocks.
The basic syntax is:
if condition:
# code to execute if condition is True
You can use logical operators like and, or, and not to combine multiple conditions.
if cond1 and cond2:
# code if both conditions are true
and: ReturnsTrueif both conditions are true.or: ReturnsTrueif at least one of the conditions is true.
if 10 <= number <= 20:
# code if number is between 10 and 20
The break statement is used to exit from a loop (like for or while) prematurely, regardless of the loop condition.
The continue statement skips the current iteration of a loop and moves to the next iteration.
The pass statement does nothing. It is used as a placeholder in loops, functions, or conditionals where code is syntactically required but you don?t want to write anything yet.
You can use the break statement to exit a while loop before its condition becomes false.
An infinite loop occurs when the loop?s condition never evaluates to false. For example:
while True:
# code that runs forever
The else clause in a loop executes when the loop completes normally (i.e., it doesn't exit via break).
Yes, else can be used with for loops. The else block executes if the loop completes without encountering a break statement.
The while loop executes as long as the condition is true:
while condition:
# code to execute
if number % 3 == 0 and number % 5 == 0:
# code if divisible by both
- A
forloop iterates over a sequence (like a list or range). - A
whileloop continues as long as a condition is true.
The range() function generates a sequence of numbers, which can be used to iterate over in a for loop. Example: range(5) generates numbers from 0 to 4.
Modifying a list during iteration can lead to unexpected results. It?s safer to iterate over a copy or use list comprehension.
for i in range(1, 6):
print(i)
for i in range(10):
if i % 2 == 0:
continue
print(i)
A ternary conditional expression is a shorthand way to write an if-else statement:
value = "Even" if number % 2 == 0 else "Odd"
x = 10
if x > 5:
print("Greater")
elif x == 5:
print("Equal")
else:
print("Smaller")Answer: The output is Greater.
for i in range(3):
if i == 1:
break
else:
print("Completed")Answer: There will be no output because the break statement prevents the else block from executing.
Short-circuiting refers to the behavior where the evaluation stops as soon as the outcome is determined. For and expressions, if the first condition is False, the second condition is not evaluated; for or expressions, if the first condition is True, the second condition is not evaluated.
Yes, the else block in a try-except structure is executed if no exception is raised during the try block execution.
The finally block will execute no matter what, whether an exception was raised or not, ensuring that cleanup code (like closing files) is always run.
breakexits the loop entirely.continueskips the current iteration and continues to the next iteration.
Yes, a for loop can iterate over any iterable object, such as lists, strings, or dictionaries.
for char in "Hello":
print(char)
Yes, a for loop can iterate over any iterable object, such as lists, strings, or dictionaries.
for char in "Hello":
print(char)
i = 0
while i < 5:
i += 1
if i == 3:
break
print(i)Answer: The code will print 3 because the loop breaks when i reaches 3.
if not string:
# code for empty string
The else block runs if no exceptions are raised in the try block. It?s typically used for code that should run only if the try block succeeds.
assert is used for debugging purposes. It tests a condition, and if the condition is False, it raises an AssertionError.
while condition:
# code to execute
string = "hello"
reversed_string = ""
for char in string:
reversed_string = char + reversed_string
for i in range(5):
if i == 3:
break
print(i)Answer: The output is:
0
1
2
Yes, a while loop can be used with a condition set to True, effectively making it an infinite loop:
while True:
# code
if checks a condition and runs the block if true. if-else adds an alternative block to run if the condition is false.
x = 5
if x < 5:
print("Less")
elif x == 5:
print("Equal")
else:
print("Greater")
Answer: The output is Equal.
You can use the else block after the loop:
for i in range(3):
print(i)
else:
print("Loop finished normally")
A nested loop is when one loop is inside another loop. Both loops run independently.
for i in range(3):
for j in range(2):
print(i, j)
A while loop continues until a condition is false, while a for loop iterates over a sequence (like a list or range).
Use a while loop with a condition that is initially False and use a break statement inside it.
Use the continue statement to skip the current iteration.
i = 0
while i < 5:
i += 1
if i == 3:
continue
print(i)Answer: The output will be:
1
2
4
5
break allows you to exit the loop early when a certain condition is met, improving efficiency.
You can use a flag variable or an exception to break out of multiple nested loops.
Tutorials
Random Blogs
- Understanding AI, ML, Data Science, and More: A Beginner's Guide to Choosing Your Career Path
- Exploratory Data Analysis On Iris Dataset
- What to Do When Your MySQL Table Grows Too Wide
- Python Challenging Programming Exercises Part 2
- The Ultimate Guide to Data Science: Everything You Need to Know
- Extract RGB Color From a Image Using CV2
- Big Data: The Future of Data-Driven Decision Making
- AI in Cybersecurity: The Future of Digital Protection
- AI in Marketing & Advertising: The Future of AI-Driven Strategies
- Understanding SQL vs MySQL vs PostgreSQL vs MS SQL vs Oracle and Other Popular Databases
