Contents
- assign_constant.py
- average5.py
- new_for.py
- simple_for.py
- sum5.py
- using_xrange.py
- xrange_analysis.py
assign_constant.py 1/7
[top][prev][next]
# In response to Ty's question
from math import e, pi
import math
print "PI =", pi
print "e =", e
e = "Eclipse"
print e
print math.e
average5.py 2/7
[top][prev][next]
# Example of Implementation of "Accumulator" Design Pattern
# Finds the average of 5 numbers, given by the user
# by CS111
# 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
new_for.py 3/7
[top][prev][next]
# Examples of using xrange, with different numbers of parameters
# by Sara Sprenkle
print "-------------- xrange(1, 15, 3) ------------"
for a in xrange(1,15,3):
print a
print "-------------- xrange(5, -15, -5) ------------"
for b in xrange(5, -15, -5):
print b
print "-------------- xrange(5, -15, 5) ------------"
for counter in xrange(5, -15, 5):
print counter
print "-------------- xrange(5, 15, 1.5) ------------"
# Note that xrange expects integer values
for counter in xrange(5, 15, 1.5):
print counter
simple_for.py 4/7
[top][prev][next]
# Examples of for loops using xrange
# by Sara Sprenkle
# typical for loop
for var in xrange(5):
print "You say 'hello'"
print "I say 'goodbye'..."
# for loop with only one statement that gets repeated
for i in xrange(5): print "Repeat the chorus!"
sum5.py 5/7
[top][prev][next]
# Example of Implementation of "Accumulator" Design Pattern
# Finds the total of 10 numbers, given by the user
# by CS111
# initialize the accumulator variable
total = 0
# loop until done
for x in xrange(5):
# 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 6/7
[top][prev][next]
# Examples of using xrange, with different numbers of parameters
# by Sara Sprenkle
# Part 2: Use constants
print "------------ xrange(10) ------------"
for x in xrange(10):
print x
print "----------- xrange(5,10) -----------"
for y in xrange(5, 10):
print y
print "----------- xrange(1,10,2) -------------"
for z in xrange(1, 10, 2):
print z
xrange_analysis.py 7/7
[top][prev][next]
# Example of for loops using xrange
# by Sara Sprenkle
# Question: what does xrange do?
for x in xrange(10):
squared = x * x
print "%d^2 =\t%d" % (x,squared)
print x
# QUESTION FOR CLASS:
# How is x changing each time through the loop?
Generated by GNU enscript 1.6.4.