Link Search Menu Expand Document

for loops

# for loops
for i in range(1, 10, 2):
    print(i)
1
3
5
7
9
# for...else loop
for i in range(1, 5):
    print(i)
else:
    print('printed all items')
1
2
3
4
printed all items
# for...else loop with a break
for i in range(1, 5):
    print(i)
    if i > 2:
        break
else:
    print('printed all items')
1
2
3

while loops

# while loop
condition = True
i = 0
while condition:
    print(i)
    i += 1
    if i > 3:
        condition = False
0
1
2
3
# while...else loop
condition = True
i = 0
while condition:
    print(i)
    i += 1
    if i > 3:
        condition = False
else:
    print('done')
0
1
2
3
done
# while...else loop with a break
condition = True
i = 0
while condition:
    print(i)
    i += 1
    if i > 3:
        break
else:
    print('done')
0
1
2
3

nested loops

width = 5
chars = "*@"
for char in chars:
    for i in range(1, width):
        print(char * i)
    for j in range(width, 0, -1):
        print(char * j)
*
**
***
****
*****
****
***
**
*
@
@@
@@@
@@@@
@@@@@
@@@@
@@@
@@
@
width = 5
chars = "*@"
for char in chars:
    for i in range(1, width):
        for spaces in range(width - i, 0, -1):
            print(' ', end='')
        print(char * i)
    for j in range(width, 0, -1):
        for spaces in range(width - j, 0, -1):
            print(' ', end='')
        print(char * j)
    *
   **
  ***
 ****
*****
 ****
  ***
   **
    *
    @
   @@
  @@@
 @@@@
@@@@@
 @@@@
  @@@
   @@
    @