Contents
- average5.py
- forloop_ex2.py
- simple_for.py
- sum5.py
- using_xrange.py
- xrange_analysis.py
average5.py 1/6
[top][prev][next]
# Example of Implementation of "Accumulator" Design Pattern
# Finds the average of 5 numbers, given by the user
# by CS111 09.19.2007
# initialize the accumulator variable
total = 0
# loop until we're done
for count in xrange(5):
# update the value of the accumulator
total += input("Enter a number: ")
# Question: why did we add 1.0 to count?
print "Subaverage:", total/(count+1.0)
# display the result
print "The average is ", total/5.0
forloop_ex2.py 2/6
[top][prev][next]
#
#
#
for x in xrange(5): print "Hello!"
simple_for.py 3/6
[top][prev][next]
# Examples of for loops using xrange
# by Sara Sprenkle 09.19.2007
# typical for loop
for x in xrange(5):
print "You say 'hello'"
print "I say 'goodbye'..."
# for loop with only one statement that gets repeated
for x in xrange(5): print "Repeat the chorus!"
sum5.py 4/6
[top][prev][next]
# Example of Implementation of "Accumulator" Design Pattern
# Finds the total of 10 numbers, given by the user
# by CS111 09.19.2007
# initialize the accumulator variable
total = 0
# loop until done
for x in xrange(10):
# update the accumulator variable
# IMPROVEMENT TODO: Say which number to enter using 'x' variable
total += input("Enter a number: ")
print "Subtotal:", total
# display result
print "The total is ", total
using_xrange.py 5/6
[top][prev][next]
# Examples of using xrange, with different numbers of parameters
# by Sara Sprenkle, 09.19.2007
#
# Part 2: Use constants
print "------------ xrange(10) ------------"
for x in xrange(10):
print x
print "----------- xrange(5,10) -----------"
for x in xrange(5, 10):
print x
print "----------- xrange(1,10,2) -------------"
for x in xrange(1, 10, 2):
print x
xrange_analysis.py 6/6
[top][prev][next]
# Example of for loops using xrange
# by Sara Sprenkle 09.19.2007
# Question: what does xrange do?
for x in xrange(10):
squared = x * x
print x , "^2 =\t", squared
print x
# QUESTION FOR CLASS:
# How is x changing each time through the loop?
Generated by GNU enscript 1.6.4.