Contents
- fence_post.py
- nested_for.py
- pick4.py
- random_test.py
- tictactoe.py
fence_post.py 1/5
[top][prev][next]
# Solution to the Fence Post Problem
# by Sara Sprenkle
# 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
nested_for.py 2/5
[top][prev][next]
# Nested for loops
#
for x in xrange(4):
print "Outer"
for y in xrange(3):
print "Inner"
print x, y
pick4.py 3/5
[top][prev][next]
# Simulate Pick 4 lottery game - selecting ping pong balls at random
# By CS111
import random
# Accumulator variable for the winning number
winningNum = ""
for num in xrange(3):
# generate a random number (simulating the ping pong ball machine
# spitting out a random ping pong ball)
randomNum = random.randint(0,9)
# add the random number to the winning number
winningNum = winningNum + str(randomNum)
# add the hyphen to the winning number
winningNum += "-"
# Check our results as we go ...
#print "On iteration", num, ":", winningNum
# add the final random number to the winning number
winningNum += str(random.randint(0,9))
# display the winning number
print "The winning number is", winningNum
random_test.py 4/5
[top][prev][next]
# Demonstrating random module
# by Sara Sprenkle
import random
# Demonstrates that it's a pseudo-random number generator
# If using the same seed, then gets the same list of numbers
#random.seed(1)
for x in xrange(10):
print random.random()
tictactoe.py 5/5
[top][prev][next]
# Print a tic-tac-toe board
# By CS111
verticalBars = " | |"
dashedLine = "-"*11
for i in xrange(2):
print verticalBars
print dashedLine
print verticalBars
Generated by GNU enscript 1.6.4.