
What is Control Flow?
Control flow is the order in which instructions in a computer program are executed, moving beyond simple top-to-bottom sequence using statements like if/else (decisions) and for/while loops (repetition) to create dynamic behavior, allowing programs to make choices, repeat tasks, and call functions, making them powerful and efficient. It dictates program logic, enabling branching and looping based on conditions or data, which is fundamental for complex software.
Conditional Statements
Conditional statements allow a program to make decisions based on conditions. They help the program choose different paths of execution depending on whether a condition is true or false. In Python, conditions are evaluated using comparison and logical operators.
If Statement
Executes the block only when the if condition is True
age = 18
if age >= 18:
print("Eligible to vote")
if-Else Statement
The else block runs when the if condition is false.
age = 16
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
If-Else-Elif Statement
Used when there are multiple conditions to check.
marks = 75
if marks >= 90:
print("Grade A")
elif marks >= 60:
print("Grade B")
else:
print("Grade C")
Try to get the input from user like we did in the last post
Loops
Loops are used to execute a block of code repeatedly until a certain condition is met.
for Loop
Used to iterate over a sequence such as a list, string, or range.
for i in range(5):
print(i)
while Loop
Runs as long as the given condition remains true.
count = 0
while count < 5:
print(count)
count += 1
Nested Loops
A loop inside another loop, commonly used for patterns or matrix-like data.
for i in range(3):
for j in range(2):
print(i, j)
Loop Control Statements
break
Stops the loop immediately.
for i in range(10):
if i == 5:
break
print(i)
#prints 0-4 and breaks at 5
continue
Skips the current iteration and moves to the next one.
for i in range(5):
if i == 2:
continue
print(i)
#skips 2 and prints the rest
pass
Acts as a placeholder where a statement is syntactically required.
if True:
pass