05 Control Flow
05 Control Flow
Repo (5)
Control Flow and Decision Making
in Python
1. Introduction to Control Flow
Control flow in Python determines the order in which statements are executed. Decision-
making is achieved using if, elif, and else statements, along with comparison and logical
operators.
2. Comparison Operators
Comparison operators are used to compare values and return True or False:
==: Equal to
!=: Not equal to
>: Greater than
<: Less than
>=: Greater than or equal to
<=: Less than or equal to
x = 10
y = 20
age = 25
is_student = True
4. The if Statement
The if statement executes a block of code if a condition is True.
num = 10
if num > 0:
print("The number is positive.")
num = -5
if num > 0:
print("The number is positive.")
else:
print("The number is not positive.")
num = 0
if num > 0:
print("The number is positive.")
elif num < 0:
print("The number is negative.")
else:
print("The number is zero.")
7. Nested if Statements
if statements can be nested inside each other to check multiple conditions.
num = 10
if num > 0:
if num % 2 == 0:
print("The number is positive and even.")
else:
print("The number is positive and odd.")
else:
print("The number is negative.")
8. Practical Examples
Simple Calculator
if operation == '+':
result = num1 + num2
elif operation == '-':
result = num1 - num2
elif operation == '*':
result = num1 * num2
elif operation == '/':
if num2 != 0:
result = num1 / num2
else:
result = "Error: Division by zero."
else:
result = "Invalid operation."
print("Result:", result)
Grading System
def grading_system(marks):
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
elif marks >= 60:
grade = "C"
elif marks >= 50:
grade = "D"
else:
grade = "F"
return grade
numbers = [1, 2, 3, 4, 5]
for num in numbers:
print(num)
else:
print("Loop completed successfully!")
count = 1
while count <= 5:
print(count)
count += 1
for i in range(10):
if i == 5:
break
print(i)
for i in range(5):
if i == 3:
continue
print(i)
6. Nested Loops
A nested loop places one loop inside another, with the inner loop iterating through its cycle
for each iteration of the outer loop.
# Multiplication table
for i in range(1, 6):
for j in range(1, 6):
print(f"{i} * {j} = {i * j}")
This guide covers fundamental concepts in control flow, decision-making, loops, and iteration
in Python, along with hands-on examples to enhance understanding.
These MCQs and explanations should help clarify the key concepts of control flow, decision
making, and loops in Python! If you'd like to explore more examples or concepts, feel free to
ask.