Siksha Sarovar

Siksha Sarovar (sikshasarovar.com) is a free educational web application that helps students in India learn programming and prepare for academic and competitive exams. The platform offers structured coding courses (C, C++, Python, Java, HTML, CSS, PHP, Power BI, AI, Machine Learning, Data Science), complete university curriculum notes for BCA/MCA students with previous year question papers, Class 10 and Class 12 CBSE/HBSE school notes, and dedicated preparation material for SSC, UPSC, Banking, Railway and other government exams. Browsing the site is completely free and requires no account. Users may optionally sign in with Google solely to save their learning progress, quiz scores and personal preferences across devices.

Privacy Policy | Terms of Service | Contact Siksha Sarovar | About Siksha Sarovar

v4.0.9 · PWA
Siksha Sarovar logo
Siksha Sarovar
Your Learning Universe

Siksha Sarovar is a free e-learning platform for coding courses, BCA university notes and competitive exam preparation. Optional Google sign-in saves your learning progress across devices.

Initializing knowledge base…
Compiling modules 0%

Loops & Conditional Statements

Lesson 19 of 37 in the free Data Science notes on Siksha Sarovar, written by Rohit Jangra.

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

StatementPurposeExample
breakExit the loop immediatelyStop searching once item is found
continueSkip current iteration and move to nextSkip negative numbers
passDo 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?

Featurefor Loopwhile Loop
Use WhenYou know the number of iterationsYou don't know when to stop
Iterates OverSequences (list, range, string)A condition
RiskLow (finite sequence)High (infinite loop if condition never becomes False)
Common In DSIterating over data rowsConvergence algorithms (Gradient Descent)

Summary

  • if/elif/else controls decision-making based on conditions.
  • for loops iterate over sequences; while loops repeat until a condition is False.
  • break exits a loop; continue skips to the next iteration; pass is a placeholder.
  • List comprehension provides a Pythonic, concise way to create lists.
  • Nested loops are used for multi-dimensional data traversal.