LOOPS (IF, WHILE, AND FOR)

When to Use Each Type of Loop

Summary of Crucial Best Practices:

  • Use a ‘for’ loop over a ‘while’ loop when possible because ‘for’ loops are generally more readable and less prone to causing infinite loops if the loop control variable is not properly updated.

  • Keep the loop body concise and readable. Extract complex logic into functions if necessary.

  • Utilize list comprehensions whenever appropriate, as they can simplify code and improve performance.


Use a ‘while’ loop when:

  • You don’t know the exact number of repetitions required beforehand, and the loop’s termination depends on a specific condition.

  • Repetition is controlled by a condition that can change during the loop execution.

  • You need to perform a task until a specific condition is met or until a user interrupts the process.

#Sample Code: Printing 0-4
count = o
while count <5:
 print(“Count is: “, count)
 count += 1
#Output
Output:
Count is: 0
Count is: 1
Count is: 2
Count is: 3
Count is: 4

Use a ‘for’ loop when:

  • You want to run the same block of code for each item in a collection (e.g., list, string, dictionary) and process each item individually.

  • The number of repetitions is known or defined by the length of the collection.

Use case: print all the elements in a given list


#Sample Code: Printing all of the elements in a list
fruits = [“apple”, “banana”, “cherry”]
 for fruit in fruits:
 Print(fruit)
#Output
Output:
 apple
 banana
 cherry

Use nested loops when:

  • You need to go through multi-dimensional data structures like 2D arrays or nested lists.

  • You want to perform a repetitive task that requires iterations over multiple dimensions.

#Sample Code: Print a 2D array list from 0–2 and 0–1 inside the first list
For I in range(3):
 For j in range(2):
 Print(f”({1}, {j})”)
#This code prints the first loop and then prints the second loop inside of the list being printed for the first loop simultaneously.
#Output
Output:
 (0, 0)
 (0, 1)
 (1, 0)
 (1, 1)
 (2, 0)
 (2, 1)

Continue, Break, and Else Statements

The ‘break’ statement is used to terminate the loop prematurely. When the ‘break’ statement is encountered inside the loop, the loop is immediately exited and the program continues with the next statement after the loop.Which type of loop should I use?

#Sample Code
numbers =[1,2,3,4,5]
for num in numbers:
 If num ==3:
 Break
 Print(num)
#Output
1
2

The ‘continue’ statement

The ‘continue’ statement is used to skip the current iteration of a loop and move to the next iteration, this means when the ‘continue’ statement is encountered, the loop moves to the next item in the sequence without executing the remaining block of code for the current iteration.


#Sample Code
numbers = [1,2,3,4,5]
for num in numbers:
 if num ==3:
 continue
 print(num)
#Loop completed without encountering ‘break’
#Output 
 1
 2
 4
 5

The ‘else’ Statement

In Python, a unique feature of loops is the ‘else’ statement, which is used in conjunction with a loop. The ‘else’ block is executed when the loop completes all it’s iterations without encountering any ‘break’ statement. It is not executed if the loop is terminated prematurely using ‘break’.

#Sample Code
Numbers = [1,2,3,4,5]
 For num in numbers:
 If num ==6:
 Print(num)
 else:
 print(“Loop completed without encountering ‘break’”)

NESTED IF LOOPS — INCOMPLETE!

WHILE LOOPS

SIMPLIFIED BREAKDOWN

For most counting while loops:

counter = starting_value

while condition:
    # do something
    counter = counter + 1

The counter:

  1. Starts somewhere

  2. Gets checked in the condition

  3. Changes each time through the loop

  4. Eventually makes the condition false so the loop ends


FOR LOOPS

Purpose: Used to iterate over a sequence (e.g., a list, tuple, set, dictionary, string, range), executing the same block of code once for each item in the sequence.

Python For Loops - GeeksforGeeks

How Its Used:

  • no indexing variable required

  • for loop header follows simple structure (as seen below)

for (initialization; condition; update): 
    #code block to be executed during each iteration

initialization

  • sets starting point

  • runs exactly once when loop begins

  • usually this where counter variable is declared & set


condition

  • boolean expression checked BEFORE every iteration

  • if evaluates true → code block will run

  • if evaluates false → code block won’t run


update

  • changes counter variable after code block executes

  • this moves the loop towards pre-determined end of sequence

  • ensures loop doesn’t run on forever


(a) Looping through a sequence.

# Looping through a string

# Looping through a list 
spiders = 

# Looping through a dictionary 

# Looping through a range

In the sample code above:

  • ‘x’ —> “loop variable”; temporarily holds each value from the list as the FOR loop iterates through it

  • When Python reaches for x in jerseyNum:, it automatically does the following:

    • Takes the first item in jerseyNum (55).

    • Assigns that value to x.

    • Executes print(x), displaying 55.

    • Moves to the next item (21), assigns it to x, and prints it.

    • Continues until every item has been processed.


b) ‘Break Statement”


(c) ‘Continue statemnet’


(d) ‘Range’ function


(e) ‘else’


(f) ‘nested loops’

This is a common nested-loop pattern:


for row in range(...):      # controls which row
    for col in range(...):  # controls items in that row
        print(row, end=" ")
    print()

(h) ‘pass’ statement