Conditional Statements
Conditional statements allow Python to make decisions based on conditions.They control the flow of execution by running different blocks of code depending on whether a condition is True or False.
---
The if Statement
Syntax:
if condition:
# code block (runs if condition is True)
The if-else Statement
if condition:
# runs if True
else:
# runs if False
The if-elif-else Statement (Multiple Conditions)
if condition1:
# runs if condition1 is True
elif condition2:
# runs if condition2 is True
else:
# runs if none of the above are True
Example:
marks = 85
if marks >= 90:
grade = "A+"
elif marks >= 80:
grade = "A"
elif marks >= 70:
grade = "B"
else:
grade = "C"
print(grade) # Output: A
---
Nested if Statements
You can place an if inside another if for more complex decision-making.
age = 20
has_id = True
if age >= 18:
if has_id:
print("Entry allowed")
else:
print("Show your ID")
else:
print("Not allowed")
---
Ternary Operator (One-Line if-else)
Python supports a concise inline conditional expression:
result = "Even" if x % 2 == 0 else "Odd"
---
Loops
Loops allow you to repeat a block of code multiple times. They are essential for iterating over data — processing each row in a dataset, each character in a string, or each item in a list.
---
The for Loop
Used to iterate over a sequence (list, tuple, string, range, dictionary).
Syntax:
for variable in sequence:
# code block
Examples:
# Iterate over a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)
# Using range()
for i in range(5): # 0, 1, 2, 3, 4
print(i)
for i in range(2, 10, 2): # 2, 4, 6, 8 (start, stop, step)
print(i)
---
The while Loop
Repeats a block of code as long as the condition remains True.
Syntax:
while condition:
# code block
Example:
count = 0
while count < 5:
print(count)
count += 1 # Don't forget to update! (Otherwise: infinite loop)
---
Loop Control Statements
| Statement | Purpose | Example |
|---|---|---|
break | Exit the loop immediately | Stop searching once item is found |
continue | Skip current iteration and move to next | Skip negative numbers |
pass | Do nothing (placeholder) | Empty loop or function body |
break Example:
for i in range(10):
if i == 5:
break # Stop at 5
print(i) # Prints 0, 1, 2, 3, 4
continue Example:
for i in range(10):
if i % 2 == 0:
continue # Skip even numbers
print(i) # Prints 1, 3, 5, 7, 9
---
Nested Loops
A loop inside another loop. The inner loop completes all iterations for each iteration of the outer loop.
for i in range(3):
for j in range(3):
print(f"({i}, {j})", end=" ")
print()
# Output:
# (0, 0) (0, 1) (0, 2)
# (1, 0) (1, 1) (1, 2)
# (2, 0) (2, 1) (2, 2)
---
List Comprehension (Pythonic Loops)
List comprehension is a concise way to create lists using a single line of code. It is one of Python's most powerful features and is widely used in Data Science.
Syntax: [expression for item in iterable if condition]
Examples:
- Squares:
squares = [x**2 for x in range(10)]→[0, 1, 4, 9, 16, ...] - Even numbers:
evens = [x for x in range(20) if x % 2 == 0] - Upper case:
upper = [s.upper() for s in ["hello", "world"]]
---
for vs while — When to Use Which?
| Feature | for Loop | while Loop |
|---|---|---|
| Use When | You know the number of iterations | You don't know when to stop |
| Iterates Over | Sequences (list, range, string) | A condition |
| Risk | Low (finite sequence) | High (infinite loop if condition never becomes False) |
| Common In DS | Iterating over data rows | Convergence algorithms (Gradient Descent) |
Summary
if/elif/elsecontrols decision-making based on conditions.forloops iterate over sequences;whileloops repeat until a condition is False.breakexits a loop;continueskips to the next iteration;passis a placeholder.- List comprehension provides a Pythonic, concise way to create lists.
- Nested loops are used for multi-dimensional data traversal.