A Beginner’s Guide to Python Loops

Python loops—from basic for and while constructs to control flow tools (break, continue, else) and comprehensions—offer versatile and expressive ways to automate repetition in code. By combining good practices and Pythonic patterns, you’ll write clear, efficient, and maintainable loops that scale with complexity.

                                                                                

 

WHAT IS A FOR LOOP IN PYTHON?

A for loop is used to repeat a block of code a certain number of times or for each item in a sequence (like a list, string, or range)

General syntax:

For a variable in sequence:

 #code to run for each item

 

Variable: The name you give to the item in the sequence during each loop.

 

Sequence: A list, string, range, or anything iterable.

 

Indentation matters:  everything inside the loop must be indented.

 

HOW TO WORK:

 Think of it like a teacher taking attendance:

  The teacher says each student’s name (loop variable) one by one (from the sequence).

  For each name, they take some action (e.g., mark present)

Examples:

1. Loop through a list

fruits = ["apple", "banana", "cherry"]

 
For fruit in fruits:
    print(fruit)

 

 2. Loop using range ()

   for i in range(5):  # 0 to 4
    print(i)

 

3. loop with custom start and step

  for i in range(2, 10, 2):
    print(i)

    output: 2 4 6 8

4.LOOP through a string

  for letter in "python":
    print(letter)

 

5. Loop with  an if condition

numbers = [1, 2, 3, 4, 5]
 
for num in numbers:
    if num % 2 == 0:
        print(num, "is even")

6. Nested for loop

for i in range(1, 4):
    for j in range(1, 4):
        print(f"i={i}, j={j}")

7. Using for with enumerate ()

names = ["Alice", "Bob", "Charlie"]
 
for index, name in enumerate(names):
    print(index, name)

8. Loop through a dictionary

student = {"name": "John", "age": 20, "grade": "A"}
 
for key, value in student.items():
    print(key, ":", value)

 9. Loop with break

 for num in range(10):
    if num == 5:
        break
    print(num)

10. Loop with continue

for n in range(5):
    if n == 2:
        continue
    print(n)

 

WHAT IS A WHILE LOOP IN PYTHON?

A while loop repeatedly executes a block of code as long as a given condition is true.

Syntax:

 

While condition:

    #code block

Condition: A boolean expression(true or false).

The loop keeps running until the condition becomes false.

You must make sure something inside the loop changes to stop it eventually. Otherwise, you get an infinite loop.

Examples:

1. Basic counting loop   

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

2. infinite loop (with break to stop)

count = 0
 
while True:
    print("running....")
    count += 1
    if count == 3:
        break

3. countdown

   num = 5

   while num  > 0:

           Print (num)

            num -= 1

 

4. Loop with user input

   Password = ” “

   while password   != ”python”:

    password= input(“enter password: ”)

      print(“access granted”)

 

5. Sum of the first N numbers

   n=5

   total=0

   while i<=n:

       total += i

        i+=1

  print (“sum:”, total)

6. Using continue in a while loop

    i = 0

    while i < 5:

        i += 1

        if  i == 3:

             continue

         print(i)

7. Reverse a string

   text = “python”

   i =  len (text)-1

   while i >= 0:

      print(text[i],end=””)

      i-=1

8. Guess the number game

Secret = 7

guess=0

while guess !=  secret:

              guess = int (input (“Guess the number:”))

      print(“you guessed it!”) 

           

9. Multiplication table

num  = 3

i=1

While i <=10:

     Print(f”{num} * {i} = {num*i}”)

     i += 1

10. Factorial calculation

n = 5

fact =1

while n  >0:

    fact  *=n

    n-=1

     print(“Factorial:”,fact)

 

CONDITIONAL STATEMENTS IN PYTHON:

 

Pass statement:

Purpose: Acts as a placeholder when a statement is syntactically required but you don’t want to do anything yet.

Effect: Does nothing ___the loop or block moves on.

Example:

1.    for  num  in range(5):

       if num ==2:

                pass  #do nothing for number 2

        else:

                print(num)

 

2. continue statement

 Purpose: skip the current iteration and move to the next loop iteration.

Effect: The loop does not stop_ it just skips the rest of the code for that iteration.

 

Example:

      for num in range(5):

      if  num  == 2:

             continue   #skip  printing number 2

        print(num)

3. break statement

 Purpose: exit the loop entirely, regardless of the loop condition.

Effect:  The loop ends immediately.

Example

for num in range(5):
    if num == 3:
        break
    print(num)

 

 

 

  

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

.