The following program finds the average of several test scores entered by the user.
num_students = input('Number of students? ')
sum = 0
for i in range(num_students):
score = input('Student score: ')
sum = sum + score
print 'Average is', float(sum) / num_students
This works fine, but it requires the user to tell us how many
students there are. We do this because we need to know how many
times to repeat the for loop. But it would be much more
convenient for a user if the user started by entering scores,
and then said I'm done
once there were no more scores to
enter. To allow this to happen, we'll us a while
loop.
num_students = 0
sum = 0
score = raw_input('Student_score: ')
while score != "I'm done":
sum = sum + int(score)
num_students = num_students + 1
score = raw_input('Student_score: ')
print 'Average is', float(sum) / num_students
We can also use this in a program to show a moving ball. In
this case, we want the animation to continue until the window is
closed. We can ask the window whether it is closed using its
isClosed method.
from graphics import *
import time
win = GraphWin('Bouncing') # Create a window
center = Point(100, 180) # Add a red circle at its bottom
ball = Circle(center, 20)
ball.setFill('red')
ball.draw(win)
x_vel = 1 # Track the ball's horizontal speed
y_vel = -6 # Track the ball's vertical speed
while not win.isClosed():
ball.move(x_vel, y_vel)
center = ball.getCenter()
y_vel += 0.2
if center.getY() > 180:
ball.move(0, 180 - center.getY()) # move it up to 180
y_vel = -0.9 * y_vel
if center.getX() < 20 or center.getX() > 180:
x_vel = -x_vel
click = win.checkMouse()
if click != None:
y_vel = -6
time.sleep(0.05) # Wait before drawing next animation frame
This uses the checkMouse method, which returns the
mouse location if the user has pressed the mouse button but None
if the user hasn't. This is different from getMouse,
which will always wait until the user presses the mouse button
before returning its location. If we had used getMouse
instead of clickMouse above, then the computer would
stall there each time through the loop, and the computer would
only continue downward to the line telling to the ball to move
once the user clicks the mouse. In other words, it would perform
very badly!