Contents
- consecutiveHeads2.py
- consecutiveHeads.py
- game.py
- string_compare.py
- string_iteration.py
consecutiveHeads2.py 1/5
[top][prev][next]
# Count how many times it takes to get 3 consecutive heads.
# This version uses a break statement
# By CSCI111
from game import *
NUM_CONSECUTIVE = 3
print("This program finds how many coin flips are required before")
print("we get", NUM_CONSECUTIVE, "consecutive heads")
numFlips = 0
numHeads = 0
while True:
# flip coin
coinFlip = flipCoin()
# update my number of flips
numFlips += 1
print(numFlips, end=": ")
# if the coin flip is tails
# reset numHeads to 0
if coinFlip == TAILS:
numHeads = 0
print("Tails")
else:
numHeads += 1
print("Heads")
if numHeads == NUM_CONSECUTIVE:
break
print("The total number of flips to get", NUM_CONSECUTIVE, "heads was", numFlips)
consecutiveHeads.py 2/5
[top][prev][next]
# Count how many times it takes to get 3 consecutive heads
# By CSCI111
from game import *
NUM_CONSECUTIVE = 3
print("This program finds how many coin flips are required before")
print("we get", NUM_CONSECUTIVE, "consecutive heads")
numFlips = 0
numHeads = 0
while numHeads < NUM_CONSECUTIVE:
# flip coin
coinFlip = flipCoin()
# update my number of flips
numFlips += 1
print(numFlips, end=": ")
# if the coin flip is tails
# reset numHeads to 0
if coinFlip == TAILS:
numHeads = 0
print("Tails")
else:
numHeads += 1
print("Heads")
print("The total number of flips to get", NUM_CONSECUTIVE, "heads was", numFlips)
game.py 3/5
[top][prev][next]
# Helpful functions for games
# by CSCI111
from random import *
HEADS=0
TAILS=1
def flipCoin():
"""
Simulates flipping a non-biased coin.
returns either HEADS or TAILS.
"""
return randint(HEADS, TAILS)
def testFlipCoin():
""" tests the flipCoin function """
numTests = 20
numSuccesses = 0
for x in range(numTests):
flipped = flipCoin()
if flipped == HEADS or flipped == TAILS:
numSuccesses += 1
print( numSuccesses, "out of", numTests, "tests passed.")
if __name__ == '__main__':
testFlipCoin()
string_compare.py 4/5
[top][prev][next]
# Program compares two strings
# by Sara Sprenkle
str1 = input("Enter a string to compare: ")
str2 = input("Compare '" + str1 + "' with what string? ")
print("-" * 40)
if str1 < str2 :
print("Alphabetically,", str1, "comes before", str2 + ".")
elif str1 > str2:
print("Alphabetically,", str2, "comes before", str1 + ".")
else:
print("You tried to trick me!", str1, "and", str2, "are the same word!")
string_iteration.py 5/5
[top][prev][next]
# Iterating through strings
# by Sara Sprenkle
phrase = input("Enter a phrase: ")
print("Iterate through phrase, using characters:")
for char in phrase:
print(char)
print()
print("Iterate through phrase, using positions of characters:")
for pos in range(len(phrase)):
print(pos, phrase[pos])
Generated by GNU Enscript 1.6.6.