🔹 1. If-Else Statements in Python
✅ Purpose:
Used to make decisions in your code. Based on a condition, different blocks of code are executed.
🔸 Syntax:
if condition:
# Code runs if condition is True
elif another_condition:
# Runs if first condition is False and this is True
else:
# Runs if none of the above conditions are True
🔸 Example:
x = 15
if x > 20:
print("Greater than 20")
elif x > 10:
print("Greater than 10 but not more than 20")
else:
print("10 or less")
🧠Explanation:
x = 15
x > 20
is Falsex > 10
is True, so it prints "Greater than 10 but not more than 20"
🔹 2. Loops in Python
Loops help repeat code until a condition is met.
➤ A. for
Loop
✅ Used for:
- Iterating over a sequence (like list, range, string)
🔸 Example:
for i in range(5):
print("Number:", i)
🧠Explanation:
range(5)
gives: 0, 1, 2, 3, 4- Loop prints each number from 0 to 4
➤ B. while
Loop
✅ Used for:
- Repeating a block while a condition is True
🔸 Example:
count = 1
while count <= 5:
print("Count is:", count)
count += 1
🧠Explanation:
- Starts from 1 and continues until 5
count += 1
increases the value in each loop
🔹 3. Loop Control Statements
🔸 break
- Stops the loop
for i in range(10):
if i == 5:
break
print(i)
➡️ Stops at 4, doesn't print 5
🔸 continue
- Skips the current loop iteration and continues with the next
for i in range(5):
if i == 2:
continue
print(i)
➡️ Skips printing 2, prints 0, 1, 3, 4
✅ Summary Table
Statement | Purpose |
---|---|
if |
Executes code when condition is True |
elif |
Checks next condition if previous is False |
else |
Executes when none of the above are True |
for |
Loop over sequences/ranges |
while |
Loop until condition is False |
break |
Exit the loop early |
continue |
Skip current iteration |
0 Comments