PyForge ยท Python practice library
All topics

Topic 04 of 17

Loops

Iterate with for and while loops, break, continue, and else clauses.

for / while
range()
break & continue
Loop with else
Nested loops

Basic

2 programs

Program 1

Print 1 to N

Basic

Use range with a for loop.

python
for i in range(1, 11):
    print(i, end=" ")

Output

1 2 3 4 5 6 7 8 9 10

Program 2

Multiplication table

Basic

Print the table of a number.

python
n = 7
for i in range(1, 11):
    print(f"{n} x {i} = {n * i}")

Intermediate

2 programs

Program 1

Sum of digits

Intermediate

Sum the digits of a number using while.

python
n, total = 1729, 0
while n > 0:
    total += n % 10
    n //= 10
print("Sum:", total)

Program 2

Star pattern pyramid

Intermediate

Nested loops to print shapes.

python
rows = 5
for i in range(1, rows + 1):
    print(" " * (rows - i) + "*" * (2 * i - 1))

Advanced

1 program

Program 1

Prime check with for/else

Advanced

Loop else runs only if break wasn't hit.

python
n = 29
for i in range(2, int(n ** 0.5) + 1):
    if n % i == 0:
        print(n, "is composite")
        break
else:
    print(n, "is prime")