0% found this document useful (0 votes)
5 views7 pages

Chapter 3 Control Flow

Chapter 3 covers control flow in programming, including conditional statements and loops. It explains how to use if, if-else, and if-elif-else statements for decision-making, as well as comparison and logical operators. Additionally, it discusses loops (for and while), loop control statements (break and continue), and the importance of nested structures for complex logic.

Uploaded by

biwobi1674
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
5 views7 pages

Chapter 3 Control Flow

Chapter 3 covers control flow in programming, including conditional statements and loops. It explains how to use if, if-else, and if-elif-else statements for decision-making, as well as comparison and logical operators. Additionally, it discusses loops (for and while), loop control statements (break and continue), and the importance of nested structures for complex logic.

Uploaded by

biwobi1674
Copyright
© All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

CHAPTER 3: CONTROL FLOW

(CONDITIONALS AND LOOPS)

3.1 What is Control Flow?


Control flow refers to the order in which statements are executed in a program. By default, statements
execute sequentially from top to bottom. However, you often need to execute certain statements
conditionally or repeat them multiple times. This is where control flow statements become essential.
Control flow allows you to make decisions, repeat actions, and create complex program logic.
Mastering control flow is fundamental to programming.

3.2 Conditional Statements: Making Decisions


Conditional statements allow your program to execute different code based on different conditions.
They are the primary mechanism for adding decision-making to your programs. Every programming
language has conditional statements, and understanding how to use them properly is crucial.

3.2.1 The if Statement


The if statement executes a block of code only if a condition is true. The condition must evaluate to a
boolean value (True or False). The code block is indented to show it belongs to the if statement.

age = 16
if age >= 18:
print('You are an adult')
print('You can vote')

# Output: (nothing, because condition is False)

3.2.2 The if-else Statement


The if-else statement provides an alternative block to execute when the condition is false. Use else
when you have two mutually exclusive options. This creates a clear binary choice in your code.

age = 16
if age >= 18:
print('You are an adult')
else:
print('You are a minor')

# Output: You are a minor


3.2.3 The if-elif-else Statement
When you have multiple conditions to check, use elif (else if). You can have multiple elif statements.
The program checks conditions from top to bottom and executes the first block that matches. Use this
when you have more than two options.

score = 85
if score >= 90:
grade = 'A'
elif score >= 80:
grade = 'B'
elif score >= 70:
grade = 'C'
elif score >= 60:
grade = 'D'
else:
grade = 'F'

print(f'Grade: {grade}') # Output: Grade: B


3.3 Comparison Operators
Comparison operators are used to compare values. They always return a boolean (True or False).
Understanding these operators is essential for writing effective conditional statements.

Operator Name Example Result


== Equal to 5 == 5 True
!= Not equal to 5 != 3 True
> Greater than 5>3 True
< Less than 5<3 False
>= Greater or equal 5 >= 5 True
<= Less or equal 3 <= 5 True

3.4 Logical Operators


Logical operators combine boolean values or conditions. They are used to create complex conditions
by combining multiple comparisons.

3.4.1 The 'and' Operator:


The 'and' operator returns True only if ALL conditions are true. If any condition is false, the result is
false.
age = 25
has_license = True

if age >= 18 and has_license:


print('You can drive')

# True and True = True, so output: You can drive

3.4.2 The 'or' Operator:


The 'or' operator returns True if AT LEAST ONE condition is true. It returns false only if all conditions
are false.
day = 'Saturday'
is_holiday = False

if day == 'Saturday' or day == 'Sunday' or is_holiday:


print('No work today')

# True or ... = True, so output: No work today

3.4.3 The 'not' Operator:


The 'not' operator reverses the boolean value. True becomes False and False becomes True.
is_raining = False

if not is_raining:
print('Let\'s go outside')

# not False = True, so output: Let's go outside

3.5 Loops: Repetition


Loops allow you to execute a block of code multiple times. This eliminates code repetition and makes
programs more efficient. There are two main types of loops: for loops (fixed number of iterations) and
while loops (condition-based).

3.5.1 The for Loop


A for loop executes a block of code a specific number of times. It's useful when you know in advance
how many times you need to repeat something. The for loop iterates through a sequence (list, tuple,
string, range) and executes the block for each element.

# Loop through a range


for i in range(5):
print(i)
# Output: 0 1 2 3 4

# Loop through a list


fruits = ['apple', 'banana', 'orange']
for fruit in fruits:
print(fruit)
# Output: apple banana orange

3.5.2 The while Loop


A while loop executes a block of code as long as a condition is true. Use while loops when you don't
know in advance how many iterations you need. Be careful to modify the condition inside the loop,
otherwise you'll create an infinite loop.

count = 0
while count < 5:
print(count)
count += 1
# Output: 0 1 2 3 4

# User input loop


password = ''
while password != 'secret':
password = input('Enter password: ')
print('Access granted')
3.6 Loop Control Statements
Loop control statements allow you to change the normal flow of loops. You can skip iterations or exit
loops early.

3.6.1 The break Statement


The break statement immediately exits the loop, regardless of the loop condition. Use break to exit
when a specific condition is met.
for i in range(10):
if i == 5:
break
print(i)
# Output: 0 1 2 3 4

3.6.2 The continue Statement


The continue statement skips the rest of the current iteration and jumps to the next iteration. Use
continue to skip specific iterations based on conditions.
for i in range(5):
if i == 2:
continue
print(i)
# Output: 0 1 3 4

3.7 Nested Loops and Conditions


You can place loops inside loops and conditions inside conditions. This allows you to create complex
logic. However, deeply nested code can be hard to read, so try to keep nesting to 2-3 levels when
possible.

3.7.1 Nested Loop Example:


# Multiplication table
for i in range(1, 4):
for j in range(1, 4):
print(f'{i} × {j} = {i*j}', end=' ')
print() # New line after each row

3.8 Key Takeaways


• Control flow determines the order of code execution
• if statements execute code conditionally
• Use if-elif-else for multiple conditions
• Comparison operators (==, !=, >, <, etc.) return booleans
• Logical operators (and, or, not) combine conditions
• for loops iterate a fixed number of times
• while loops execute based on conditions
• break exits a loop immediately
• continue skips to the next iteration
• Nested structures allow complex logic

3.9 Practice Exercises


Exercise 1: Write a program that checks if a number is positive, negative, or zero

Exercise 2: Create a loop that prints numbers from 1 to 10

Exercise 3: Write a program that asks for a password until correct

Exercise 4: Create a program that prints the multiplication table for a number

Exercise 5: Write a program that calculates the sum of numbers from 1 to 100

You might also like