Download presentation
Presentation is loading. Please wait.
1
Repetition In today’s lesson we will look at:
why you would want to repeat things in a program different ways of repeating things creating loops in Python
2
Repetition Imagine you wanted to print the word “Hello” ten times...
You could do it like this: print("Hello") print("Hello") print("Hello") print("Hello") print("Hello") print("Hello") print("Hello") print("Hello") print("Hello") print("Hello") Is that a sensible way to do it? What about if you change your mind about what you want it to say? What about if you want to change the number of times you say it?
3
Repetition Sometimes you might want to repeat a section of your program… a fixed number of times until something happens while a particular condition exists forever! In programming, these are called loops
4
Examples How many times do you need to repeat to:
choose lottery numbers for a “lucky dip”? print a list of all of the square numbers less than 100? ask the user for a number and make sure that it’s between 1 and 10?
5
Python In Python there are two commonly-used types of loop: FOR...
WHILE... (most languages have similar loops, and most have one called REPEAT... UNTIL as well, but Python doesn’t)
6
FOR Example A FOR... loop is probably the most common and most useful in all programming languages, e.g. for x in range(10): print(“Hello”) It is traditional to indent the repeated lines in all programming languages, but in Python you must indent them – the repeated section ends where you move back towards the left margin. Note that there isn’t the same idea of “counting” like there is in other languages; looping in Python is more like working through a list.
7
FOR Example You can use the value of the variable as you repeat:
for x in range(10): print(x) You can change the start and end points, or count backwards, e.g. for x in range(10, 0, -1) range() starts at 0, unless you say otherwise, and stops 1 short of what you might expect – e.g. range(10, 20) counts from 10 to 19. The variable is not always a number – you can loop through a string or list, e.g. for c in “hello”, in which case c becomes each letter in hello in turn.
8
WHILE Example A WHILE loop looks like this:
while x*x < 100: print(str(x) + “ squared is ” + str(x*x)) x += 1 Rather than repeating a fixed number of times, it repeats while a condition – in this case that the square is less than 100 – is true. The check is done at the start so the bit inside the loop may never run at all
9
Algorithm First! An algorithm is a plan for a program
Think about what the task requires in everyday terms before you rush to program it. For example, how many times do the following things repeat? ten green bottles times tables the Twelve Days of Christmas song
Similar presentations
© 2025 SlidePlayer.com Inc.
All rights reserved.