Download print(loopCounter) Python

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Python - Iteration
A FOR loop is ideal if we know how many times we want
to repeat. Try this code:
for loopCounter in range(10):
print(loopCounter)
There are two things to note:
Computers start counting at 0. This is actually better
than starting at 1, but isn’t always obvious straight away.
You have to finish the loop one number HIGHER than the
last number you actually want
- so it has repeated 10 times, but goes from 0 to 9
Python - Iteration
You can be a bit more specific with your loop by setting a
start and an end number:
for loopCounter in range(5,10):
print(loopCounter)
Python - Iteration
Remember that loops are closed (or finished) by removing
the indentation:
for loopCounter in range(1,4):
print(loopCounter,"potato")
print("4")
for loopCounter in range(5,8):
print(loopCounter,"potato")
print("more")
Python - Iteration
You can also specify how the counter will count:
for loopCounter in range(2,9,2):
print(loopCounter)
print("Who do we appreciate?")
Or the three times table:
for loopCounter in range(3,37,3):
print(loopCounter)
Python - Iteration
FOR Loop Challenge
1. Look closely at the three times table example on the
last page. Write a similar program to calculate the four
times table.
2.Write a program that will calculate the 5 times table.
3.Try writing a program that will prompt for an integer
(whole number) and print the correct times table (up to
12x).
Test with all of the tables up to 12.
Python - Iteration
Nested Loops
Sometimes you need to put one loop inside another loop.
The logic can get pretty complicated, so you have to be
careful
- but it does work!
A window cleaner has to clean all the windows in a hotel.
First, he (or she) cleans all the windows on the first floor:
for room in range(1,5):
print(“Room”,room,”cleaned”)
Python - Iteration
Then he (or she) does the 2nd floor and the 3rd, and so on:
floor = 1
for room in range(1,5):
print(“Room”,floor,room,”cleaned”)
floor = 2
for room in range(1,5):
print(“Room”,floor,room,”cleaned”)
floor = 3
for room in range(1,5):
print(“Room”,floor,room,”cleaned”)
Python - Iteration
A better way is to say
for floor in range (1,7):
for room in range(1,5):
print(“Room”,floor,room,”cleaned”)
Think about what this program will do. Decide what you
think will happen. Then try it.
for x in range(1,11):
for y in range(1,11):
print(x,"x",y,"=",x*y)
Python - Iteration
Get the user to type in how many stars across they want
to display and also how many stars down. Display the
stars