Contents
- ascii_dictionary.py
- break.py
- consecutiveHeads2.py
- consecutiveHeads.py
- file_read_while.py
ascii_dictionary.py 1/5
[top][prev][next]
# Demonstrate use of dictionary, using ASCII values
#
# create an empty dictionary
ascii= {}
x = ord('a')
while x <= ord('z'):
# add mapping to dictionary of chr(x) --> x (ordinal value)
char = chr(x)
ascii[char] = x
x+=1
print(ascii)
break.py 2/5
[top][prev][next]
# Demonstrates use of break statement, but this is a pretty dumb program.
# ONLY use break statements with while loops
# Sara Sprenkle
x=10
i = 0
count = x
while i < 10 :
if count < 100 :
i += 1
else:
break
print("Done", i)
consecutiveHeads2.py 3/5
[top][prev][next]
# Count how many times it takes to get 3 consecutive heads
# Using a break statement
# By CSCI111, 03.12.2012
from random import randint
HEADS=0
TAILS=1
NUM_CONSECUTIVE = 3
numFlips = 0
numConsHeads = 0
while True:
numFlips += 1
# flip the coin
if randint(0,1) == HEADS:
print("heads")
numConsHeads += 1
else:
print("tails")
numConsHeads = 0
if numConsHeads == NUM_CONSECUTIVE:
break
print("It took", numFlips, "times to get", NUM_CONSECUTIVE,"consecutive heads")
consecutiveHeads.py 4/5
[top][prev][next]
# Count how many times it takes to get 3 consecutive heads
# By CSCI111, 03.12.2012
from random import randint
HEADS=0
TAILS=1
NUM_CONSECUTIVE = 3
numFlips = 0
numConsHeads = 0
while numConsHeads < NUM_CONSECUTIVE:
numFlips += 1
# flip the coin
if randint(0,1) == HEADS:
print("heads")
numConsHeads += 1
else:
print("tails")
numConsHeads = 0
print("It took", numFlips, "times to get", NUM_CONSECUTIVE,"consecutive heads")
file_read_while.py 5/5
[top][prev][next]
# Opens a file, reads the file one line at a time, and prints the
# contents
# by Sara Sprenkle
FILENAME="data/years.dat"
# creates a new file object, opening the file in "read" mode
dataFile = open(FILENAME, "r")
# reads in the file, line-by-line and displays the content of the file
line = dataFile.readline()
while line != "":
line = line.rstrip()
print(line)
line = dataFile.readline()
# close the file with the method "close"
dataFile.close()
Generated by GNU enscript 1.6.4.