#today we are going to cover while loops.
#While loops are very similar to for loops.
#To review, what does this print?
for x in range(5):
print x
0 1 2 3 4
#How do I do the same thing in while loops
#while ....:
#do something
#the code indented in the next line after the while loop is only
#executed if the thing next to the while statement evaluates to True.
#Example
x=0
while True:
x += 1 #x=3
if x==3:
continue
print x
if x==5:
break
#what does this print?
#In this case, True is always True,
#so the while loop executes until we break.
1 2 4 5
#Example
x=0
while x<=5:
x += 1
if x==3:
continue
print x
#if x==5:
# break
1 2 4 5 6
#what does this print?
y=0
x = []
while y <=5:
print y #y=4
y += 1 #y=5
x += [y] #x=[1,2,3,4,5]
print x
#x += [y]
print x
0 [1] 1 [1, 2] 2 [1, 2, 3] 3 [1, 2, 3, 4] 4 [1, 2, 3, 4, 5] 5 [1, 2, 3, 4, 5, 6] [1, 2, 3, 4, 5, 6]
#Example: Both of these code examples print
#only the odd numbers between 0 and 5.
myList = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
for x in myList:
if x > 5:
break
elif x%2 == 0:
continue
else:
print x
1 3 5
# Example with while loop. What does this do?
x=0
while True:
if x > 5:
break
elif x%2 == 0:
x += 1
continue
else:
print x
x += 1
1 3 5
# Example with while loop. What does this do?
x=0
while True:
if x > 5:
break
elif x%2 == 0:
#x += 1 <---now what happens if I don't have this line?
continue
else:
print x
x += 1
#You should always be careful when you use while loops.
#Because if you don't tell it when to stop, a while loop
#can go on forever.
# Example with while loop. What does this do?
x=0
while True:
if x > 5:
break
elif x%2 == 0:
x += 1
continue
else:
print x
x += 1 #<---now what happens if I don't have this line?