Contents
- demo_str.py
- escape_sequence.py
- format_examples.py
- pick4winner_alt.py
- pick4winner_better_error_handling.py
- pick4winner.py
- sales_tax2.py
- sales_tax.py
- search.py
- string_methods.py
- temp_table_final.py
- 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?"')
format_examples.py 3/12
[top][prev][next]
# Formatting examples, from handout
# CSCI111
x = 10
y = 3.5
z = "apple"
print("{:6d}".format(x))
print("{:6.2f}".format(x))
print("{:06.2f}".format(y))
print("{:6.2f}".format(y))
print("{:+6.2f}".format(y))
print("{:^10s}".format(z))
print("*{:^10s}*".format(z))
print("{:5d} {:<7.3f}".format(x,y))
pick4winner_alt.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 *
# 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 5/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 + ") ")
###### TODO: handle bad input ######
# Use of sys.exit(1) cleans up our program a bit.
# 1) Figure out if bad input, then exit the program
# 2) Continue with the code that works if we don't have errors.
if not pickedNum.isdigit(): # if pickedNum.isdigit() == False:
print("Your input contained non-digits")
sys.exit(1)
if len(pickedNum) != NUM_PICKS:
print("Check your input: should be", NUM_PICKS, "digits long")
sys.exit(1)
# 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)
if winningNum == pickedNum:
print("Congratulations! You won!")
else:
print("Sorry. Better luck next time!")
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 + ") ")
###### TODO: handle 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)
if winningNum == pickedNum:
print("Congratulations! You won!")
else:
print("Sorry. Better luck next time!")
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=.053 # 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}".format(value), end=' ')
print("costs ${:.2f} with tax".format(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=.053 # 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}".format("Temp F", "Temp C", "Temp K"))
print("{:6s} {:>10s} {:>10s}".format("-"*6, "-"*6, "-"*6))
ftemp = -459.67
ctemp = -273.15
ktemp=0
print("{:6.1f} {:10.1f} {:10.1f}".format(ftemp, ctemp, ktemp))
ftemp = 0
ctemp = -17.77778
ktemp= 255.222
print("{:6.1f} {:10.1f} {:10.1f}".format(ftemp, ctemp, ktemp))
ftemp = 32
ctemp = 0
ktemp= 273.15
print("{:6.1f} {:10.1f} {:10.1f}".format(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.