Loops


Python uses two different loops while and for.

while loops can execute a set of statements as long as a condition is true for example:

Input:

i = 1
while i < 6:
  print(i)
  i += 1

Output:

1

2

3

4

5

The break statement can stop the loop before its looped through everything for example:

Input:

i = 1
while i < 6:
  print(i)
  if i == 3:
    break
  i += 1

Output:

1

2

4

5

6

The else statement can run a chunk of code once when the condition is no longer true for example 

Input:

i = 1
while i < 6:
  print(i)
  i += 1
else:
  print("i is no longer less than 6")

Output:

1
2
3
4
5
i is no longer less than 6

 

A for loop is used for a sequence for example:

Input:

fruits = ["apple""banana""cherry"]
for in fruits:
  print(x)

Output:

apple
banana
cherry

The break statement can stop the loop before its looped through everything for example:

Input:

fruits = ["apple""banana""cherry"]
for x in fruits:
  print(x)
  if x == "banana":
    break

Output:

apple
banana

Leave a comment

Log in with itch.io to leave a comment.