i = 1
while i<=6:
print(i)
i=i+1
1
2
3
4
5
6
i=1
while i<6:
print(i)
if i == 3:
break
i+=1
1
2
3
i=0
while i<=6:
i+=1
if i == 3:
continue
print(i)
1
2
4
5
6
7
i = 1
while i <=6:
print(i)
i+=1
else:
print("i is no longer less than "+str(i))
1
2
3
4
5
6
i is no longer less than 7
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
apple
banana
cherry
for x in "banana":
print(x)
b
a
n
a
n
a
statement we can stop the loop before it has looped through all the items:
fruits = ["apple", "banana", "cherry"]
for x in fruits:
print(x)
if x == "banana":
break
apple
banana
fruits = ["apple", "banana", "cherry"]
for x in fruits:
if x == "banana":
break
print(x)
apple
statement we can stop the current iteration of the loop, and continue with
fruits = ["apple", "banana" ,"qw1","cherry"]
for x in fruits:
if x == "banana":
continue
print(x)
apple
qw1
cherry
for x in range(5):
print(x)
else:
print("Finally finished!")
0
1
2
3
4
Finally finished!
for x in range(1,10,2):
print(x)
1
3
5
7
9
for x in range(1,10):
print("*")
for j in range(x):
print("#",end="")
else:
print("\ndone printing ")
*
#*
##*
###*
####*
#####*
######*
#######*
########*
#########
done printing
adj = ["red", "big", "tasty"]
fruits = ["apple", "banana", "cherry"]
for x in adj:
for y in fruits:
print(x, y)
red apple
red banana
red cherry
big apple
big banana
big cherry
tasty apple
tasty banana
tasty cherry
but if you for some reason have a for loop with no content, put in the pass statement to avoid getting an error
for x in [0, 1, 2]:
pass