Contents

  1. coinFlip.py
  2. consecutiveHeads.py
  3. random_test.py
  4. sumtillzero.py
  5. whilevsfor.py

coinFlip.py 1/5

[
top][prev][next]
# This program demonstrates the use of the pseudo random number
# generator.
# by Sara Sprenkle, 10.01.2007

from random import randint

HEADS=0
TAILS=1

# flip the coin
if randint(0,1) == HEADS:
    print "heads"
else:
    print "tails"

consecutiveHeads.py 2/5

[
top][prev][next]
# This program demonstrates the use of the pseudo random number
# generator.
# Counts the number of flips it takes to get to some goal of
# consecutive heads.
# by Sara Sprenkle, 10.01.2007

from random import randint

GOAL=4
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."

random_test.py 3/5

[
top][prev][next]
# Demonstrating random module
# by Sara Sprenkle, 10.01.2007

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()


sumtillzero.py 4/5

[
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

whilevsfor.py 5/5

[
top][prev][next]
# Compares a while loop with a for loop
# by Sara Sprenkle, 10.01.2007

# WHILE LOOP

print "While Loop Demo"
i=0
while i < 10:
    print "i equals", i
    i += 1
print "Done", i

# FOR LOOP

print "\nFor Loop Demo"
for i in xrange(10):
    print "i equals", i

print "Done", i

Generated by GNU enscript 1.6.4.