Skip to content

Latest commit

 

History

History
211 lines (199 loc) · 2.29 KB

Python Loops.md

File metadata and controls

211 lines (199 loc) · 2.29 KB
while Loop
i = 1
while i<=6:
	print(i)
	i=i+1
1
2
3
4
5
6
break Statement
i=1
while i<6:
	print(i)
	if i == 3:
		break
	i+=1
1
2
3
The continue Statement
i=0
while i<=6:
	i+=1
	if i == 3:
		continue  
	print(i)
1
2
4
5
6
7
The else Statement
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
Python For Loops
iterate through list
fruits = ["apple", "banana", "cherry"]
for x in fruits:
  print(x)
apple
banana
cherry
Python For Loops
Looping Through a String
for x in "banana":
  print(x)
b
a
n
a
n
a
The break Statement

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

continue Statement

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

range(start,stop,skip)

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

range(start,stop,skip)

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

The pass Statement

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