Iteration While
while.py
i = 1
while i <= 6:
i = i + 1
print(i)
break.py
i = 1
while i <= 6:
i = i + 1
print(i)
if i == 3:
break #rejects all remaining statements in current iteration of loop, and (also) exits the loop
continue.py
i = 1
while i <= 6:
print(i)
i = i + 1
if i == 3:
continue #rejects all remaining statements in current iteration of loop, and moves back to top of loop
print("happy")
Using a WHILE loop:
- Count up from 1 to 10.
- Count backwards from 10 to 1, and then print "blastoff" on the next line.
- Count backwards from 50 to 1. Skip the number 40 entirely. Break the count at number 20.
- Challenge:print a list of even numbers between 40 to 0 (counting down). Only print the even numbers.
- Challenge:Develop a game called "Unmatch", where the aim is to count how many times 2 dice can be rolled without matching.
To play, 2 dice are rolled usingrandom.randint(1,6), and if the rolls don't match, the score can be increased by +1. If the rolls do match, the score gets reset to 0.
Try and keep a high score to see how many "unmatches" you can get in a row.