Loading notes...
Loading notes...
Class 11 • Chapter 6
Chapter 6 covers Flow of Control, teaching how to make decisions using if-elif-else statements and how to repeat tasks using for and while loops.
Normally, a Python script executes sequentially, line by line, from top to bottom. However, real-world applications require programs to make decisions and repeat tasks. 'Flow of Control' refers to the order in which statements are executed. We use Decision-Making statements to skip code based on conditions, and Iteration (Looping) statements to execute code repeatedly.
6.1 Decision Making: The 'if' Statement
The `if` statement allows a block of code to run ONLY if a specific boolean condition evaluates to `True`. Python relies heavily on Indentation (whitespace) to determine which lines of code belong inside the `if` block. If the indentation is wrong, the program will crash with an IndentationError.
age = 15
if age >= 18:
# This line is indented, so it belongs to the 'if' block
print("You are eligible to vote.")
# This line is not indented, so it runs regardless of the condition
print("Program execution finished.")6.2 if-else and if-elif-else
The `else` statement provides a fallback block of code that runs if the initial `if` condition is `False`. When you have more than two possible outcomes, you use `elif` (short for else if) to chain multiple conditions together. Python checks them from top to bottom and stops at the first one that is True.
marks = 85
if marks >= 90:
print("Grade: A")
elif marks >= 80:
# This runs if marks < 90 AND marks >= 80
print("Grade: B")
elif marks >= 70:
print("Grade: C")
else:
# This is the catch-all if none of the above are True
print("Grade: F")6.3 Iteration: The 'for' Loop
A `for` loop is used to iterate over a sequence (like a list, a string, or a range of numbers). It executes a block of code a specific, known number of times. It is almost always used in conjunction with the `range()` function.
# Prints 0, 1, 2, 3, 4
for i in range(5):
print(i)
# Prints 2, 4, 6, 8 (Starts at 2, goes up to 9, steps by 2)
for i in range(2, 10, 2):
print(i)6.4 Iteration: The 'while' Loop
A `while` loop executes a block of code repeatedly AS LONG AS a specific boolean condition remains `True`. It is used when you do not know beforehand exactly how many times the loop needs to run (e.g., waiting for a user to type 'quit'). Warning: If the condition never becomes False, you will create an Infinite Loop, and the program will crash or freeze.
count = 0
while count < 3:
print("Count is:", count)
# CRITICAL: We must update the variable, or the loop runs forever!
count += 16.5 Jump Statements: break and continue
Jump statements allow you to alter the normal flow of a loop.