Python - Iteration

advertisement
Starter
Look at the hand-out.
Could you program the
robot to light all the
squares up?
What instructions would
you give it?
Python - Iteration
Iteration
Iteration is a posh way of saying “loop”
(iteration literally means to do something
again).
Loops are absolutely vital in programming
in order to avoid having to write sequences
of code out again and again. And
they come in several forms:
Python - Iteration
While Loops
A WHILE loop is a way of repeating a
section of code. It is easy to understand
because it uses something that looks a
lot like an IF statement at the top.
Python - Iteration
How many times do you think this loop will
repeat? Try it and find out:
number = 1
while number < 10:
print(“This is turn ”,number)
number = number + 1
print(“The loop is now finished”)
Make sure you understand why the last line
only prints out once, at the end of the loop.
Python - Iteration
A WHILE loop is ideal if you don’t know
exactly how many times you will need to
repeat the code.
Python - Iteration
# this is the correct number
targetNumber = 7
# ask for a guess
guess = int(input(“Guess a number between 1 and
10”))
# repeat if the answer is wrong
while guess != targetNumber:
print(“Wrong, try again”)
guess = int(input(“Guess a number between 1
and 10”))
# do this after the loop
print(“Congratulations - that’s right!”)
Python - Iteration
Tasks
Create a program that gets two players to enter in
their names and then you choose a Gamenumber
between 10 and 50. Each player takes it in turns to
choose either 1,2 or 3. This number is then deducted
from the Gamenumber. The last person to deduct a
number from the Gamenumber before it reaches 0
loses.
Python - Iteration
Solution – Pseudo Code
Playing = 1
GameNumber = INPUT
Valid = false
While GameNumber > 0
While Valid = false
Get number from user
if number 1,2 or 3 and Gamenumber –
number >= 0
Valid = true
GameNumber – number
Show GameNumber
if GameNumber > 0
if Playing = 1
Playing = 2
else
Playing = 1
IF playing = 1 THEN
OUTPUT “Player 2 loses”
ELSE
OUTPUT “Player 1 loses”
END IF
Download