Contents
- ascii_dictionary.py
- break.py
- consecutiveHeads2.py
- consecutiveHeads.py
- file_read_while.py
- performance_check.py
ascii_dictionary.py 1/6
[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/6
[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/6
[top][prev][next]
# Count how many times it takes to get 3 consecutive heads
# Using a break statement
# By CSCI111
from random import randint
HEADS=0
TAILS=1
NUM_CONSECUTIVE = 3
consecutiveHeads = 0
totalFlips = 0
while True:
# flip the coin
if randint(HEADS, TAILS) == HEADS:
print("Heads!")
consecutiveHeads += 1
else:
print("Tails!")
consecutiveHeads = 0
# update the total number of flips
totalFlips += 1
# when to stop
if consecutiveHeads == NUM_CONSECUTIVE:
break
print("It took", totalFlips, "times to get", NUM_CONSECUTIVE, "heads")
consecutiveHeads.py 4/6
[top][prev][next]
# Count how many times it takes to get 3 consecutive heads
# By CSCI111
from random import randint
HEADS=0
TAILS=1
NUM_CONSECUTIVE = 3
consecutiveHeads = 0
totalFlips = 0
while consecutiveHeads < NUM_CONSECUTIVE:
# flip the coin
if randint(HEADS, TAILS) == HEADS:
print("Heads!")
consecutiveHeads += 1
else:
print("Tails!")
consecutiveHeads = 0
# update the total number of flips
totalFlips += 1
print("It took", totalFlips, "times to get", NUM_CONSECUTIVE, "heads")
file_read_while.py 5/6
[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()
performance_check.py 6/6
[top][prev][next]
# Performance test between while and for loop
#
import time
ITERATIONS=100000
start = time.time()
counter = 0
for x in range(ITERATIONS):
counter+=0
end = time.time()
print("Seconds lapsed: ", end-start)
start = time.time()
counter = 0
x = 0
while x < ITERATIONS:
x+=1
counter+=1
end = time.time()
print("Seconds lapsed: ", end-start)
Generated by GNU enscript 1.6.4.