🔹 Python Decision Making and Loops
This topic covers conditional statements and looping constructs — the backbone of
controlling program flow in Python.
✅ 1. Conditional Statements (Decision Making)
Python uses if, if...else, and if...elif...else statements for decision making.
🔸 A. If Statement
Used to execute a block of code only if the condition is True.
x = 10
if x > 5:
print("x is greater than 5")
🔸 B. If...Else Statement
Executes one block if the condition is true, another if false.
age = 18
if age >= 18:
print("Eligible to vote")
else:
print("Not eligible to vote")
🔸 C. Elif (Else If)
Used when you have multiple conditions to check.
score = 75
if score >= 90:
print("Grade A")
elif score >= 75:
print("Grade B")
elif score >= 50:
print("Grade C")
else:
print("Fail")
🔸 D. Boolean Expressions
These are conditions that evaluate to True or False.
Examples:
x = 5
print(x > 3) # True
print(x == 10) # False
Boolean expressions are the core of decision-making.
✅ 2. Loops in Python
Loops are used to execute a block of code repeatedly.
🔸 A. While Loop
Repeats while a condition is true.
count = 1
while count <= 5:
print("Count is:", count)
count += 1
⚠️ Infinite While Loop:
If you don’t update the condition, the loop may never stop.
# CAUTION: This is infinite!
# while True:
# print("Running...")
🔸 B. For Loop
Used to iterate over a sequence (list, tuple, string, etc.)
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
You can also use range() to repeat a block a specific number of times:
for i in range(5):
print("Number:", i)
🔸 C. Nested Loops
A loop inside another loop.
for i in range(1, 4):
for j in range(1, 4):
print(f"({i}, {j})")
✅ 3. Loop Control Statements
These control the behavior of loops:
Statement Description
break Stops the loop completely
continue Skips current iteration, continues with next
pass Does nothing (placeholder)
🔸 Break Example:
for i in range(10):
if i == 5:
break
print(i)
🔸 Continue Example:
for i in range(5):
if i == 2:
continue
print(i)
🔸 Pass Example:
for i in range(3):
pass # Future code will go here
✅ 4. Using Loops with Lists, Sets, and Dictionaries
🔹 With List:
numbers = [10, 20, 30]
for n in numbers:
print(n * 2)
🔹 With Set:
colors = {"red", "green", "blue"}
for color in colors:
print(color.upper())
🔹 With Dictionary:
student = {"name": "Alice", "age": 21}
for key, value in student.items():
print(f"{key}: {value}")
🔹 With while and Lists:
fruits = ["apple", "banana", "cherry"]
i = 0
while i < len(fruits):
print(fruits[i])
i += 1
Practical
Python Decision Making and Loops
✅ 1. Print even numbers from 1 to 20
for i in range(1, 21):
if i % 2 == 0:
print(i)
✅ 2. Ask user for password until it's correct
password = ""
while password != "admin123":
password = input("Enter password: ")
print("Access Granted")
✅ 3. Iterate dictionary of employees
employees = {
"John": 50000,
"Alice": 60000,
"Bob": 55000
}
for name, salary in employees.items():
print(f"{name}: ₹{salary}")
✅ 4. Multiplication table (1 to 5) using nested loop
for i in range(1, 6):
for j in range(1, 11):
print(f"{i} x {j} = {i * j}")
print() # blank line after each table
✅ 5. Check if number is positive, negative, or zero
num = int(input("Enter a number: "))
if num > 0:
print("Positive number")
elif num < 0:
print("Negative number")
else:
print("Zero")
✅ 6. Sum of first N numbers using while loop
n = int(input("Enter a number: "))
i = 1
total = 0
while i <= n:
total += i
i += 1
print("Sum:", total)
✅ 7. Skip printing number 5 using continue
for i in range(1, 10):
if i == 5:
continue
print(i)
✅ 8. Print elements of a list using while loop
items = ["pen", "pencil", "eraser"]
i = 0
while i < len(items):
print(items[i])
i += 1
🔹 Using Loops with Built-in Functions + Plotting + Logic Programs
✅ 1. Loops with Lists, Sets, and Dictionaries
🔸 List Example
nums = [1, 2, 3]
for i in nums:
print(i * 2) # Multiply each element by 2
🔸 Set Example
colors = {"red", "green"}
for c in colors:
print(c.upper()) # Print each color in uppercase
🔸 Dictionary Example
student = {"name": "A", "age": 20}
for k, v in student.items():
print(k, ":", v) # Print keys and values
✅ 2. Built-in Functions in Use
Function Use Example Purpose
len() len(nums) Count elements
sum() sum(nums) Add all numbers
sorted() sorted(nums) Sort list in ascending order
✅ 3. Plotting Data with matplotlib
📌 Basic Line Plot
import matplotlib.pyplot as plt
x = [1, 2, 3]
y = [2, 4, 6]
plt.plot(x, y)
plt.show() # Display the graph
🟢 Use for visualizing numeric data.
✅ 4. Programs with Loops + Conditions
🔸 Grade Calculator
marks = 80
if marks >= 75:
print("Grade B") # Decide grade using condition
🔸 Prime Numbers
for n in range(2, 10):
for i in range(2, n):
if n % i == 0:
break
else:
print(n) # Print prime numbers only
🔸 Sum and Average
data = [10, 20]
print(sum(data), sum(data)/len(data)) # Total and avg
🔸 Count Vowels
text = "hello"
count = sum(1 for ch in text if ch in "aeiou")
print(count) # Number of vowels