Skip to content
For and While loops

For and While loops

For loop

1#example for a simple for loop
2for i in range(5):
3    print(f'Attempt {i + 1} of 5')
4
5#example for a simple for loop using an array as source
6names = ['Max', 'Alice', 'Bob']
7for name in names:
8    print(f'Hello, {name}!')

While loop

 1#example for a simple while loop and how to exit it
 2while True:
 3    for i in range(5):
 4        print(f'Attempt {i + 1} of 5')
 5    break
 6
 7#example for a while loop with an else clause
 8i = 1
 9while i < 6:
10    print(f'Attempt {i} of 5')
11    i += 1
12else:
13    print("Loop has finished.")