Contents

  1. demo_str.py
  2. escape_sequence.py
  3. pick4winner_alt.py
  4. pick4winner_better_error_handling.py
  5. pick4winner_places.py
  6. pick4winner.py
  7. sales_tax2.py
  8. sales_tax.py
  9. search.py
  10. string_methods.py
  11. temp_table_final.py
  12. temp_table.py

demo_str.py 1/12

[
top][prev][next]
# Demonstrate long strings and escape sequences
# by Sara Sprenkle

string = """This is a long string.
Like, really long.
Sooooo loooooong"""

print(string)

print("To print a \\, you must use \"\\\\\"")


escape_sequence.py 2/12

[
top][prev][next]
# Practice with escape sequences
# CS111

# Display To print a tab, you must use '\t'.
# If you use double quotes, you don't _need_ to escape the single quote
print("To print a tab, you must use a '\\t'.")
print('To print a tab, you must use a \'\\t\'.')

# Display I said, "How are you?"
print("I said, \"How are you?\"")
print('I said, "How are you?"')


pick4winner_alt.py 3/12

[
top][prev][next]
# Simulate Pick 4 lottery game - selecting ping pong balls at random
# Modified to figure out if the user entered the winning number
# By CSCI111

from random import *

# define constants that are easy to change so that our
# program is flexible
NUM_PICKS = 4
MIN_VALUE = 0
MAX_VALUE = 9

NUMFORMAT="####"

pickedNum = input("What is your pick? (Format: " + NUMFORMAT + ") ")

winningNum = ""
won = True

print("The winning Pick 4 lottery number is ", end='')

for i in range(NUM_PICKS):
    randNum = randint(MIN_VALUE,MAX_VALUE)
    print(randNum, end='')
    # If they don't match, we know the user didn't win
    if str(randNum) != pickedNum[i]:
        won = False

print()

if won:
    print("Congratulations!  You are very lucky and rich!")
    print("We should be friends!")
else:
    print("Sorry, you lost.")

pick4winner_better_error_handling.py 4/12

[
top][prev][next]
# Simulate Pick 4 lottery game - selecting ping pong balls at random
# Modified to figure out if the user entered the winning number
# By CSCI111

from random import *
import sys

# define constants that are easy to change so that our
# program is flexible
NUM_PICKS = 4
MIN_VALUE = 0
MAX_VALUE = 9

NUMFORMAT="####"

pickedNum = input("What is your pick? (Format: " + NUMFORMAT + ") ")

######  handle bad input ######

### incorrect length ###
if len(pickedNum) != NUM_PICKS:
    print("Error: incorrect number of digits")
    print("You need", NUM_PICKS, "digits")
    sys.exit()


### handle if the user doesn't input all digits ###

isvalid = True

for char in pickedNum:
    if not char.isdigit():
        print(char, "is not a digit")
        isvalid = False
  
# why wait until now to exit?
if not isvalid:
    print("Please try entering another number.")
    sys.exit()


# accumulate the random number

# the equivalent of starting the accumulator at 0 for a string is
# starting with an empty string: 
winningNum = ""

for x in range(NUM_PICKS):
    # create the random number and make it a string
    randnum = str(randint(MIN_VALUE, MAX_VALUE))
    # concatenate the newly generated number to the end of the
    # winning number
    winningNum = winningNum + randnum
    
print("The winning number is", winningNum)

# determine if the input number is a winner
if winningNum == pickedNum:
    print("Congratulations!  You are very lucky and rich!")
    print("We should be friends!")
else:
    print("Bummer.  You probably should spend your money more wisely.")
    
# Question: What are good test cases for this program? 
# 

pick4winner_places.py 5/12

[
top][prev][next]
# Simulate Pick 4 lottery game - selecting ping pong balls at random
# Modified to count number of correctly chosen numbers
# By CSCI111

from random import *
import sys

# define constants that are easy to change so that our
# program is flexible
NUM_PICKS = 4
MIN_VALUE = 0
MAX_VALUE = 9

NUMFORMAT="#" * NUM_PICKS

# get the user's input, as a string to maintain the four digits
userNumber = input("What is your pick (format: " + NUMFORMAT + ")? ")

# check if the user's number is valid
# Specifically, check if the user's number has the correct number of digits
if len(userNumber) != NUM_PICKS:
    print("Error: incorrect number of digits")
    print("You need", NUM_PICKS, "digits")
    sys.exit()
# TODO: check if the user's number is only numbers

winningNum = ""
# accumulate the number of matches
numMatches = 0

for whichPick in range(NUM_PICKS):
    chosen = str(randint(MIN_VALUE, MAX_VALUE))
    # concatenate the chosen number to the winning number
    winningNum = winningNum + chosen
    if chosen == userNumber[whichPick]: 
        # alternative, use winningNum[whichPick] instead of chosen
        numMatches = numMatches + 1
        
print("The winning Pick 4 number is", winningNum)
print()

# determine if the user won
if userNumber == winningNum:
    print("Congratulations!  You won!")
elif numMatches >= 1:
    print("You matched", numMatches, "numbers.  Collect your prize.")
else:    
    print("Sorry, no matches.  You shouldn't be wasting your money anyway.")
    
    
    
    
    
    
    
    
    

pick4winner.py 6/12

[
top][prev][next]
# Simulate Pick 4 lottery game - selecting ping pong balls at random
# Modified to figure out if the user entered the winning number
# By CSCI111

from random import *

# define constants that are easy to change so that our
# program is flexible
NUM_PICKS = 4
MIN_VALUE = 0
MAX_VALUE = 9

NUMFORMAT="####"

pickedNum = input("What is your pick? (Format: " + NUMFORMAT + ") ")

######  handle bad input ######
if len(pickedNum) != NUM_PICKS:
    print("Error: incorrect number of digits")
    print("You need", NUM_PICKS, "digits")
    sys.exit()
    
######  TODO: handle other bad input ######


# accumulate the random number

# for a string, the equivalent of starting the accumulator at 0 is
# starting with an empty string: 
winningNum = ""

for x in range(NUM_PICKS):
    # create the random number and make it a string
    randnum = str(randint(MIN_VALUE, MAX_VALUE))
    # concatenate the newly generated number to the end of the
    # winning number
    winningNum = winningNum + randnum
    
print("The winning number is", winningNum)

# determine if the input number is a winner
if winningNum == pickedNum:
    print("Congratulations!  You are very lucky and rich!")
    print("We should be friends!")
else:
    print("Bummer.  You probably should spend your money more wisely.")
    
# Question: What are good test cases for this program? 
# 

sales_tax2.py 7/12

[
top][prev][next]
# Compute the cost of an item, plus sales tax.
# The displayed cost uses a format specifier.
# by Sara Sprenkle

SALES_TAX=.05  # the sales tax in VA

value = eval(input("How much does your item cost? "))

with_tax = value * (1+SALES_TAX)

print("Your item that cost $%.2f" % value, end=' ')
print("costs $%.2f with tax" % with_tax)

sales_tax.py 8/12

[
top][prev][next]
# Compute the cost of an item, plus sales tax
# Demonstrate need for/use of format specifiers
# by Sara Sprenkle

SALES_TAX=.05  # the sales tax in VA

# Test with a variety of values
value = eval(input("How much does your item cost? "))

with_tax = value * (1+SALES_TAX)

print("Your item that cost $", value, end=' ')
print("costs $", with_tax, "with tax.")

search.py 9/12

[
top][prev][next]
# Demonstrate use of "in" operator for strings as well
# as an if test
# Sara Sprenkle

# QUESTION: Why is this a constant?
PYTHON_EXT = ".py"

filename = raw_input("Enter a filename: ")

if filename[-(len(PYTHON_EXT)):] == PYTHON_EXT:
    print "That's a name for Python script"

if PYTHON_EXT in filename:
    print "That filename contains", PYTHON_EXT

# QUESTION: SHOULD THIS BE AN IF/ELIF?
# What is the impact of that change?




string_methods.py 10/12

[
top][prev][next]
# Manipulate strings, using methods
# by Sara Sprenkle

sentence = input("Enter a sentence to mangle: ")

length = len(sentence)

# Question: What does the statement below do?
print("*", sentence.center(int(length*1.5)), "*")

print("Uppercase: ", sentence.upper())
print()
print("Lowercase: ", sentence.lower())
print()

# Answer before running...
print("Did sentence change?: ", sentence)

temp_table_final.py 11/12

[
top][prev][next]
# Print out the table of temperatures
# By CS111

# Better to calculate these conversions but that's not the 
# focus today.

# First, figure out the format specifier for each column.
# - determine the type
# - determine the width
# - determine the flags and/or precision

# Second, fill in the values into each of those columns.

print("%6s %10s %10s" % ("Temp F", "Temp C", "Temp K"))
print("%6s %10s %10s" % ("-"*6, "-"*6, "-"*6))

ftemp = -459.67
ctemp = -273.15
ktemp=0

print("%6.1f %10.1f %10.1f" % (ftemp, ctemp, ktemp))


ftemp = 0
ctemp = -17.77778
ktemp= 255.222
print("%6.1f %10.1f %10.1f" % (ftemp, ctemp, ktemp))


ftemp = 32
ctemp = 0
ktemp= 273.15
print("%6.1f %10.1f %10.1f" % (ftemp, ctemp, ktemp))



temp_table.py 12/12

[
top][prev][next]
# Print out the table of temperatures
# By CS111

# Better to calculate these conversions but that's not the focus today

# Some starter code; not filled in with printing the table.
# See temp_table_final.py

ftemp = -459.67
ctemp = -273.15
ktemp=0

ftemp = 0
ctemp = -17.77778
ktemp= 255.222


ftemp = 32
ctemp = 0
ktemp= 273.15



Generated by GNU Enscript 1.6.6.