Contents
- coinFlip.py
- consecutiveHeads.py
- sumtillzero.py
coinFlip.py 1/3
[top][prev][next]
# This program demonstrates the use of the pseudo random number
# generator to simulate coin flips
# by Sara Sprenkle
from random import randint
HEADS=0
TAILS=1
# flip the coin
if randint(0,1) == HEADS:
print "heads"
else:
print "tails"
consecutiveHeads.py 2/3
[top][prev][next]
# This program demonstrates the use of the pseudo random number
# generator and while loops
# Counts the number of flips it takes to get to some goal of
# consecutive heads.
#
from random import randint
GOAL=3
HEADS=0
TAILS=1
print
print "This program counts how many flips it takes to get", GOAL,
print "consecutive heads"
print
consecutiveHeads = 0
numFlips = 0
while consecutiveHeads != GOAL :
numFlips += 1
coinValue = randint(0,1)
# flip
if coinValue == HEADS:
print "(", numFlips, ") heads"
consecutiveHeads += 1
else:
print "(", numFlips, ") tails"
consecutiveHeads = 0
print "It took", numFlips, "flips to get", GOAL, "consecutive heads."
sumtillzero.py 3/3
[top][prev][next]
# Program that demonstrates indefinite loop
# Sums until user enters 0
#
PROMPT = "Enter a number ('Enter' stops the summation) >> "
print "This program sums up values input by the user."
print "Stops summing when you hit enter"
print
sum = 0
data = raw_input( PROMPT )
while data != "" :
strToNum = float(data)
sum += strToNum
data = raw_input(PROMPT)
print "The sum of the numbers you entered is ", sum
Generated by GNU enscript 1.6.4.