Contents
- fencepost_problem.py
- format_specifiers.py
- nested_for.py
- program_after.py
- program_before.py
- program.py
- xrange_analysis.py
fencepost_problem.py 1/7
[top][prev][next]
# Solution to the Fence Post Problem
# by Sara Sprenkle 09.24.2007
# Note that you have one more fence post (|) than you have beams (-).
# So, you must execute the for loop one less time and then add the
# last fencepost.
num_fp = input("Enter the length of fence you want, in fence posts: ")
fence_str = ""
for fp in xrange(num_fp - 1):
fence_str += "|-"
fence_str += "|"
print fence_str
# Alternative solution:
fence_str = "|-" * (num_fp -1)
fence_str += "|"
print fence_str
format_specifiers.py 2/7
[top][prev][next]
# Examples of Format Specifiers
# by Sara Sprenkle, 09.17.2007
#
# just a big floating point number
pct = 14543/2341.0
# default printing
print "The pct is", pct
# no format operator, so prints out literally
print "The pct is %.2f", pct
# shows correct use of format specifier
print "The pct is %.2f" % pct
# use with the %e format specifier
print "The pct is %.2e" % pct
print "*****************************"
print "Regularly prints out: ", .5
# precision bigger than decimal places
print "With bigger prec: %.5f" % .5
# precision bigger than decimal places
print "With bigger prec: %010.5f" % .5
print "*****************************"
# smaller fieldwidth than the number
number = 1000
print "The number is %2d" % number
number += .1234
print "The number is %2f" % number
print "The number is %5.2f" % number
print "With exponent format %%e %.7e:" % number
print "*****************************"
# string practice
string = "text"
# right-justify
print "%6s" % string
# left-justify
print "%-6s example" % string
nested_for.py 3/7
[top][prev][next]
for y in xrange(3):
for x in xrange(1,5):
print x,
print x+1
program_after.py 4/7
[top][prev][next]
# Converts kilometers to miles.
# NOTE: We should also give the script a useful/descriptive name
# (rather than "program_after.py")
# CS111, 09.24.2007
# conversion factor from kilometers to miles
# Note: we got rid of the "magic number" and gave it a useful name
KM_TO_MI = .62
print "This program converts kilometers to miles."
km = input("Enter the kilometers: ")
miles = km * KM_TO_MI
print km, "kilometers is", miles, "miles"
program_before.py 5/7
[top][prev][next]
#
km = input("Enter the km: ")
print km*0.62
program.py 6/7
[top][prev][next]
#
KM_TO_MI = .62
km = input("Enter the km: ")
print km*0.62
xrange_analysis.py 7/7
[top][prev][next]
# Example of for loops using xrange
# by Sara Sprenkle 09.21.2007
# Question: what does xrange do?
print "%5s %5s" %( "x", "x^2")
print "----- -----"
for x in xrange(-10, 11):
squared = x * x
# FORMAT NICELY
#print x , "^2 =\t", squared
print "%+5d %+5d" % (x, squared)
#print "%d \t%d" % (x, squared)
Generated by GNU enscript 1.6.4.