Vous êtes sur la page 1sur 4

Introduction to Programming: Python

Repetition (while and for loops)

The While Loop


# loop1.py
while x < 20:
x = x+1
print x

The indent creates a block the same way that the if statement does. Everything that is indented
happens as long as the condition is true. The condition is checked at the start of each loop
iteration and only there. You will notice that x = x + 1 caused x to become 20, which makes the
condition false but print x still executed.
# loop2.py
name = ""
while name != "end":
name = raw_input("Enter name: <end to exit>")
print "Hello", name

As you can see we can use any condition to continue our loop, but in this case, because we only
exit at the beginning of the loop we have that awkward moment where we say hello to "end".
# loop3.py
while True:
name = raw_input("Enter name: <end to exit>")
if name == "end":
break
#end if
print "Hello", name
#end while

while True: will loop forever, because True is always True. It's like saying while 1==1. This can
be useful if we want to exit the loop at some other location. The break command exits the loop.
If we were inside more than one loop, break would only exit the inner loop.

# loop4.py
# enter marks (out of 100) until -1 is entered and display the number of
# marks and the average of all the marks.
count = 0
total = 0
while True:
mark = input("Enter a mark (0-100) <-1 to exit> ")
if mark == -1:
break
count += 1
total += mark
print "There were", count, "marks"
print "The average is", total / count

# float(total) / count

Two Important Concepts


Although we did not introduce any new syntax in this example we are using our variables.
Count is used as a "counter" and total is being used as an "accumulator".
Counter
A counter is an integer variable that we use to keep track of the number of times a
particular event has happened. The most common thing to count is the number of times
we went around a loop. This is what we are counting in the above example, because with
each time around the loop we enter one mark, so in effect we are counting the number of
marks. To use a counter:
1. Give the counter an initial value of 0. (before the loop)
2. Each time you encounter what you want to count increase the counter by one
( x = x + 1) or simply (x += 1)
3. Typically you check the value outside the loop
Accumulator
An accumulator is similar to a counter. Instead of increasing the variable by one we can
increase it by any number. An accumulator is typically used to add up a bunch of
numbers. (total = total + num) or (total += num)
# loop5
# Find the sum of all squares from 1 to 100 <let students try>
count = 0
total = 0
while count < 100:
count += 1
total += count ** 2
print "The sum is", total

The For Loop


The for loop in Python is quite useful. The most basic use is to set up a counter that will count in
a certain range. Range stops one short to be consistent.
# loop6
# Find the sum of all squares from 1 to 100
total = 0
for count in range(1,101):
total += count ** 2
print "The sum is", total
#
#
#
#

loop7
exponential growth and decay
If you invest $5000 at 6% interest for 5 years (compounded yearly)
how much would you have at the end?

money = 5000
for year in range(5):
# if I don't way where to start
year += 1
# it's 0
money = money + money * 0.06
# money *= 1.06
print "The sum is", round(money,2)

I wrote the money assignment in long form to show that it is still, ultimately an accumulator, but
I would normally write it the way have in the comments.
# loop8.py
# Using Loops with Strings
# This is a simple program that adds dots after each letter
name = raw_input("Enter your name:")
newName = ""
for let in name:
newName = newName + let + "."
print newName

This example points out two important things. First strings accumulate differently. Rather than
starting at zero, they start as an empty string "". When we add on letters they simply make the
string longer. Second, the for loop allows us to have the "loop control variable" BECOME each
letter of a string.

Repetition Exercises

1.

Create a program that gets the marks the user has for their classes this year (ask the user
how many classes they are taking). Tell them how many classes they are failing, their
best mark and their worst mark.
Save as repetitionEx1.py

2.

As you know the inventor of the game chess was quite a clever fellow. As the story goes
the inventor presented the game to the king and the king was quite pleased. The king
asked what the inventor wanted as payment. He asked for a grain of cereal for the first
square and to have each of the next 63 squares double the previous square. As the story
goes the king agrees, but was not too pleased by the final payment. Create a program that
computes how much grain the king had to pay. Express your answer in pounds; assume
there are 7000 grains to a pound.
Save as repetitionEx2.py

3.

Write a program to be used by student council in this upcoming election to tabulate the
votes after the election. Your program will list, and number, the three candidates for
president then allow the user to enter all of the ballets until they enter 0 then tell them
who won the election and what percentage each candidate earned. e.g.
Save as repetitionEx3.py
1. Sir John A Macdonald
2. Alexander Mackenzie
3. Sir John Abbott
Enter Vote (0 to exit) :
Enter Vote (0 to exit) :
Enter Vote (0 to exit) :
Enter Vote (0 to exit) :

1
1
1
2

Sir John A Macdonald won


Sir John A Macdonald earned 75% of the votes
Alexander Mackenzie earned 25% of the votes
Sir John Abbott earned 0% of the votes

4.

Palindromes are words that are the same forwards and backwards. Create a program that
gets a word from the user and tells them if it is palindrome or not. Your program should
not care about capitalization.
Save as repetitionEx4.py

Vous aimerez peut-être aussi