Python Loops (for & while)

Today you will learn loops, one of the most important concepts in Python. Loops help you repeat code automatically instead of writing the same line again and again.


For Loop

Use for when you know how many times you want to repeat.

Example 1: Print numbers 0–4

for i in range(5):
    print(i)

Example 2: Loop through a list

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

for fruit in fruits:
    print("I like", fruit)

2. While Loop

Use while when you repeat until a condition becomes false.

Example 1:

count = 1

while count <= 5:
    print("Count:", count)
    count += 1

Example 2:

password = ""

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

print("Correct!")

3. Break & Continue

break - stop the loop

continue - skip to next iteration

for i in range(10):
    if i == 5:
        break
    print(i)
for i in range(5):
    if i == 2:
        continue
    print(i)

Next

Lists & Dictionarie