LEARN COMPLETE PYTHON IN 24 HOURS

6. Loops in Python

Loops allow your program to repeat a block of code multiple times — very useful for tasks like printing tables, processing lists, or repeating until a condition is met.

Python has two main loop types: while and for.

6.1 while Loop (with else)

while repeats code as long as a condition is True.

Syntax:

Python

while condition: # code to repeat # update variable (very important!)

Example 1 – Basic while

Python

count = 1 while count <= 5: print("Count:", count) count += 1 # Important: increase count or loop forever!

Output:

text

Count: 1 Count: 2 Count: 3 Count: 4 Count: 5

while with else The else block runs only if the loop finishes normally (not stopped by break).

Python

i = 1 while i <= 3: print("i =", i) i += 1 else: print("Loop finished successfully!")

Output:

text

i = 1 i = 2 i = 3 Loop finished successfully!

Real-life Example – Guess Number Game (simple version)

Python

secret = 7 guess = 0 while guess != secret: guess = int(input("Guess a number (1-10): ")) if guess < secret: print("Too low!") elif guess > secret: print("Too high!") print("You guessed it! 🎉")

6.2 for Loop (with range(), strings, lists)

for loop is used when you know how many times to repeat (or when iterating over a sequence).

Syntax:

Python

for variable in sequence: # code to repeat

Most common ways to use for loop:

  1. for with range() – Repeat a fixed number of times

Python

# range(start, stop, step) stop is exclusive for i in range(5): # 0 to 4 print(i) print("---") for i in range(1, 6): # 1 to 5 print(i) print("---") for i in range(1, 10, 2): # 1,3,5,7,9 print(i)

Output:

text

0 1 2 3 4 --- 1 2 3 4 5 --- 1 3 5 7 9

  1. for with strings

Python

name = "Anshuman" for char in name: print(char)

Output:

text

A n s h u m a n

  1. for with lists (very common)

Python

fruits = ["apple", "banana", "mango", "orange"] for fruit in fruits: print("I like", fruit)

Output:

text

I like apple I like banana I like mango I like orange

Tip: Use range() when you need index numbers:

Python

colors = ["red", "green", "blue"] for i in range(len(colors)): print(f"Color {i+1}: {colors[i]}")

6.3 break, continue, and pass Keywords

These control the flow inside loops.

  • break → Exit the loop immediately

  • continue → Skip the rest of current iteration, go to next

  • pass → Do nothing (placeholder)

Example – All together

Python

for num in range(1, 11): if num == 3: continue # skip 3 if num == 7: break # stop at 7 if num == 5: pass # do nothing special print(num)

Output:

text

1 2 4 5 6

Real Example – Find first even number > 10

Python

numbers = [3, 7, 12, 15, 20, 8] for n in numbers: if n > 10 and n % 2 == 0: print("First even number > 10 is:", n) break

Output:

text

First even number > 10 is: 12

6.4 Nested Loops

A loop inside another loop — used for patterns, tables, grids, etc.

Example 1 – Multiplication Table

Python

for i in range(1, 6): # outer loop for j in range(1, 6): # inner loop print(f"{i} × {j} = {i*j}", end="\t") print() # new line after each row

Output (partial):

text

1 × 1 = 1 1 × 2 = 2 1 × 3 = 3 ... 2 × 1 = 2 2 × 2 = 4 2 × 3 = 6 ... ...

Example 2 – Star Pattern

Python

rows = 5 for i in range(1, rows + 1): for j in range(i): print("*", end=" ") print()

Output:

text

* * * * * * * * * * * * * * *

6.5 Infinite Loops – How to Avoid Them

An infinite loop runs forever (or until you force stop it).

Common Causes:

  • Forgot to update condition variable

  • Condition always True

Bad Example (Infinite):

Python

count = 1 while count < 10: print(count) # forgot count += 1 → infinite!

How to Avoid:

  1. Always update the loop variable inside the loop

  2. Use break when needed

  3. Test small cases first

  4. For while True (intentional infinite), add exit condition

Safe Infinite Loop Example (with break):

Python

while True: choice = input("Type 'exit' to quit: ") if choice.lower() == "exit": print("Goodbye!") break print("You typed:", choice)

Tip: In VS Code / terminal → Press Ctrl + C to force stop any infinite loop.

Mini Project – Number Guessing Game (Full)

Python

import random secret = random.randint(1, 100) attempts = 0 print("Guess the number (1-100)") while True: guess = int(input("Your guess: ")) attempts += 1 if guess == secret: print(f"Correct! You took {attempts} attempts. 🎉") break elif guess < secret: print("Too low!") else: print("Too high!")

This completes the full Loops in Python section — now your programs can repeat tasks powerfully!