» Quick Introduction to Python » 1. Basics » 1.5 Loop

For Loop

a = ["lite", "rank", "tutorial"]
for item in a:
    print(item)

For Range Loop

# Outputs 0, 1, 2
for i in range(3):
    print(i)

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

# Outputs 3, 5, 7
for i in range(3, 8, 2): # 2 here means step
    print(i)

Break and Else Statement

a = ["hello", "world", "lite"]
target_prefix = "wo"
for item in a:
    if item.startswith(target_prefix):
        print(f"Found it: {item}")
        break
else:
    print("Nothing there")

Continue Statement

for item in range(58):
    if item % 5 == 0:
        continue
    print(item)

While Loop

a = ["lite", "rank", "tutorial"]
idx = 0
while idx < len(a):
    print(a[idx])
    idx += 1

Break Statement

a = ["hello", "world", "lite"]
target_prefix = "wo"
idx = 0
while idx < len(a):
    if a[idx].startswith(target_prefix):
        print(f"Found it: {item}")
        break

Continue Statement

i = 0
while i < 23:
    if i % 5 == 0:
        i += 1
        continue
    print(i, end=", ")
    i += 1

Code Challenge

Try to modify the code provided in the editor to make it print The number is a Pefect number.

Loading...
> code result goes here
Prev
Next