Loading notes...
Loading notes...
BCA • Chapter 3
Chapter 3 explains how to control the execution flow of a Python program using conditional branching (if, elif, else) and iteration structures (for, while), along with statements to alter loops (break, continue, pass).
By default, a Python script executes sequentially—line by line, from top to bottom. However, real-world problems require decision-making and repetition. Control statements alter the flow of execution. They allow your program to skip lines of code, choose between different blocks of code, or repeat blocks of code. This chapter covers conditional statements (if-elif-else) and loops (for, while).
3.1 Decision Making: if, elif, and else
Decision making is anticipation of conditions occurring while execution of the program and specifying actions taken according to the conditions. Python relies on indentation (whitespace at the beginning of a line) to define the scope of the code block under a condition.
marks = 85
# Using if, elif, and else for branching logic
if marks >= 90:
print("Grade: A+")
elif marks >= 80:
print("Grade: A")
elif marks >= 70:
print("Grade: B")
else:
print("Grade: C")
# Nested If
# You can have an if statement inside another if statement
age = 20
has_ticket = True
if age >= 18:
if has_ticket:
print("You can enter the theater.")
else:
print("You need a ticket to enter.")
else:
print("You are too young for this movie.")Python also supports a one-line conditional expression, often called the Ternary Operator. It is useful for simple assignments based on a condition.
score = 65
# Format: [value_if_true] if [condition] else [value_if_false]
result = "Pass" if score >= 50 else "Fail"
print(result) # Output: Pass3.2 The 'for' Loop
A `for` loop is used for iterating over a sequence (that is either a list, a tuple, a dictionary, a set, or a string). Unlike traditional C-style for loops that use counters (`for(i=0; i<10; i++)`), Python's `for` loop behaves like an iterator method.
To loop through a set of code a specified number of times, we can use the `range()` function. The `range()` function returns a sequence of numbers, starting from 0 by default, increments by 1 (by default), and ends at a specified number.
# Looping over a string
for char in "BCA":
print(char)
# Using range(stop)
# Generates numbers from 0 up to (but not including) 5
for i in range(5):
print(i, end=" ") # Output: 0 1 2 3 4
print() # Newline
# Using range(start, stop, step)
# Generates numbers from 2 to 10, jumping by 2
for i in range(2, 11, 2):
print(i, end=" ") # Output: 2 4 6 8 103.3 The 'while' Loop
With the `while` loop we can execute a set of statements as long as a condition is true. This is particularly useful when you do not know beforehand how many times the loop needs to run (e.g., waiting for user input, game loops).
count = 1
while count <= 3:
print(f"Count is {count}")
count += 1 # Crucial: Must update the variable to avoid an infinite loop
# Output:
# Count is 1
# Count is 2
# Count is 33.4 Loop Control: break, continue, pass
Sometimes you need to alter the normal execution of a loop. Python provides three statements for this:
# Using break
for i in range(1, 10):
if i == 5:
break
print(i, end=" ")
# Output: 1 2 3 4
print() # Newline
# Using continue
for i in range(1, 6):
if i == 3:
continue
print(i, end=" ")
# Output: 1 2 4 5
# Using pass
if True:
pass # I will write code here later, but I don't want a syntax error now3.5 Loop with 'else' block
Python supports a unique feature: attaching an `else` block to a `for` or `while` loop. The code in the `else` block executes ONLY if the loop finishes completely naturally (i.e., it is NOT terminated by a `break` statement). This is highly useful for search operations.
target = 7
# Searching for a number
for i in range(5):
if i == target:
print("Found it!")
break
else:
# This runs because the loop finished all iterations and 'break' was never hit
print("Target not found in the range.")