2 min read

    Python for DSA — Conditionals & Loops

    PythonDsaLoopsConditionalsFor-loopWhile-loopEnumerate

    6. Conditionals & Loops

    💡 Why this matters for DSA Every algorithm uses conditionals and loops. Most DSA solutions are a loop body with a few if-conditions inside.


    6.1 if / elif / else

    python
    x = 10
    
    if x > 0:
        print("positive")
    elif x == 0:
        print("zero")
    else:
        print("negative")
    

    Ternary (inline if-else)

    python
    result = "even" if x % 2 == 0 else "odd"
    

    ✅ Tip — Common DSA conditional patterns:

    python
    # Bounds check
    if 0 <= i < len(arr):   # chained comparison
    
    # None guard
    if result is not None:
    
    # Truthy check (prefer explicit for clarity)
    if arr:         # True if non-empty list
    if not arr:     # True if empty list
    

    6.2 for loop

    python
    # Over a range
    for i in range(5):           # 0, 1, 2, 3, 4
    for i in range(2, 7):        # 2, 3, 4, 5, 6
    for i in range(0, 10, 2):    # 0, 2, 4, 6, 8
    for i in range(5, 0, -1):    # 5, 4, 3, 2, 1
    
    # Over a list
    for x in [1, 2, 3]:
    for ch in "hello":
    for row in matrix:
    

    range() details

    CallResult
    range(5)0 to 4
    range(1, 5)1 to 4
    range(1, 10, 2)1, 3, 5, 7, 9
    range(5, 0, -1)5, 4, 3, 2, 1

    6.3 enumerate() — index + value together

    python
    arr = ["a", "b", "c"]
    
    for i, val in enumerate(arr):          # i=0,val='a'; i=1,val='b'; ...
    for i, val in enumerate(arr, start=1):  # start index at 1
    

    ✅ Tip — Essential for DSA: Whenever you need both index and element, use enumerate() — cleaner than range(len(arr)).


    6.4 zip() — iterate multiple lists together

    python
    names = ["a", "b", "c"]
    scores = [85, 92, 78]
    
    for name, score in zip(names, scores):
        print(f"{name}: {score}")
    
    # Unzip
    pairs = [(1, 'a'), (2, 'b'), (3, 'c')]
    nums, letters = zip(*pairs)
    
    # Zip to dict
    keys = ["name", "age"]
    vals = ["Manik", 25]
    d = dict(zip(keys, vals))  # {"name": "Manik", "age": 25}
    

    6.5 while loop

    python
    i = 0
    while i < 5:
        print(i)
        i += 1
    

    When to use while vs for

    ScenarioUse
    Known number of iterationsfor
    Until a condition changeswhile
    Binary searchwhile left <= right
    Two-pointer techniquewhile left < right

    ✅ Tip — Common DSA while patterns:

    python
    # Two pointers
    left, right = 0, len(arr) - 1
    while left < right:
        # ...
        left += 1
        right -= 1
    
    # Binary search
    while left <= right:
        mid = (left + right) // 2
        if arr[mid] == target: break
    
    # BFS/DFS with queue/stack
    while queue:
        node = queue.popleft()
    

    6.6 break, continue, pass

    python
    # break — exit loop immediately
    for x in arr:
        if x == target:
            break
    
    # continue — skip to next iteration
    for x in arr:
        if x % 2 == 0:
            continue
        print(x)        # only odd numbers
    
    # pass — do nothing (placeholder)
    if condition:
        pass  # TODO: handle later
    

    Practice Drill

    python
    # 1. Print all even numbers from 1 to 20
    # 2. Given a list, find the first negative number (use break)
    # 3. Count vowels in a string (using for loop)
    # 4. Print a multiplication table (nested loops)
    
    💡 Click for Solutions
    python
    # 1. Even numbers
    for i in range(2, 21, 2):
        print(i)
    
    # 2. First negative number
    arr = [3, 7, -1, 5, -8]
    for x in arr:
        if x < 0:
            print(f"First negative: {x}")
            break
    
    # 3. Count vowels
    s = "hello world"
    vowels = "aeiou"
    count = 0
    for ch in s:
        if ch in vowels:
            count += 1
    print(count)  # 3
    
    # 4. Multiplication table
    for i in range(1, 11):
        for j in range(1, 11):
            print(f"{i*j:4}", end="")
        print()
    

    ← Dictionaries | Next → Functions & Recursion