Python Mastery – From Basics to Brilliance / Control Flow & Decision Making

Loops: for, while

Loops are used in Python to repeat a block of code multiple times.

Python mainly has two types of loops:

  1. for loop

  2. while loop


1. for Loop

The for loop is used to iterate over a sequence or collection of items.

Syntax

for variable in sequence:
    # code to execute

Example

fruits = ["Apple", "Banana", "Mango"]

for fruit in fruits:
    print(fruit)
Apple
Banana
Mango

Here, the loop takes each item from the list one by one and executes the code.


Example for range()

range() is commonly used when we want to repeat something a specific number of times.

for i in range(5):
    print(i)
0
1
2
3
4

range(5) starts from 0 and stops before 5.

for i in range(2, 6):
    print(i)
2
3
4
5

The stop value is not included.

The third value determines how much the number changes each time.

for i in range(1, 10, 2):
    print(i)
1
3
5
7
9

Here:

  • 1 → Start

  • 10 → Stop

  • 2 → Step

A negative step can be used to count backwards.

for i in range(5, 0, -1):
    print(i)
5
4
3
2
1

2. while Loop

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

Syntax

while condition:
    # code to execute

Example

x = 1

while x <= 5:
    print(x)
    x += 1
1
2
3
4
5

3. while Loop with User Input

A while loop is useful when we don't know beforehand how many times the loop should run.

password = ""

while password != "1234":
    password = input("Enter password: ")

print("Access Granted")

The loop continues until the user enters the correct password.


4. Infinite while Loop

If the condition never becomes False, the loop will continue forever.

x = 1

while x <= 5:
    print(x)

Here, x never changes, so x <= 5 will always be True.

Therefore, always make sure a while loop has a way to eventually make its condition False.


for vs while

for Loop

while Loop

Used to iterate over a sequence

Runs while a condition is True

Usually used when the number of iterations is known

Useful when the number of iterations is unknown

Commonly used with range()

Commonly used with conditions

Less likely to create an infinite loop

Can create an infinite loop if the condition never becomes False