Skip to content

Commit e3ed395

Browse files
committed
2 parents d91b727 + 5e40cfb commit e3ed395

27 files changed

+1886
-4
lines changed
Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
#!/usr/bin/env python
2+
3+
food_prefs = {"name": "Chris",
4+
"city": "Seattle",
5+
"cake": "chocolate",
6+
"fruit": "mango",
7+
"salad": "greek",
8+
"pasta": "lasagna"}
9+
10+
def sformat(**kwargs):
11+
""" input dict and return a formatted string """
12+
return "{name} is from {city}, and he likes {cake} cake, {fruit} fruit, {salad} salad, and {pasta} pasta".format(**kwargs)
13+
14+
def hexcomps():
15+
""" Using a list comprehension, build a dictionary of numbers from zero to fifteen and the hexadecimal equivalent (string is fine). """
16+
h1 = [hex(i) for i in range(16)]
17+
d1 = {i: j for i, j in enumerate(h1)}
18+
return d1
19+
20+
def hexcomps2():
21+
""" Do the previous entirely with a dict comprehension – should be a one-liner """
22+
dh = {i: hex(i) for i in range(16)}
23+
return dh
24+
25+
def counta():
26+
""" Build a new dictionary with food_prefs but replace values with number of a's in it """
27+
newdict = {i: j.count('a') for i, j in food_prefs.items()}
28+
return newdict
29+
30+
def seta():
31+
""" build sets with set comprehension """
32+
s2 = {i for i in range(21) if i%2 == 0}
33+
s3 = {i for i in range(21) if i%3 == 0}
34+
s4 = {i for i in range(21) if i%4 == 0}
35+
return "In seta(), s2 = {}, s3 = {}, s4 = {}".format(s2, s3, s4)
36+
37+
def setb():
38+
""" A list of sets """
39+
ls = [{i for i in range(21) if i%j == 0} for j in range(2, 5)]
40+
return ls
41+
42+
43+
if __name__ == '__main__':
44+
""" Main function """
45+
print(sformat(**food_prefs))
46+
print(hexcomps())
47+
print(hexcomps2())
48+
print(counta())
49+
print(seta())
50+
print(setb())
Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
#!/usr/bin/python
2+
3+
"""
4+
An exercise in playing with Exceptions.
5+
Make lots of try/except blocks for fun and profit.
6+
7+
Make sure to catch specifically the error you find, rather than all errors.
8+
"""
9+
10+
from except_test import fun, more_fun, last_fun
11+
12+
13+
# Figure out what the exception is, catch it and while still
14+
# in that catch block, try again with the second item in the list
15+
first_try = ['spam', 'cheese', 'mr death']
16+
17+
try:
18+
joke = fun(first_try[0])
19+
except NameError:
20+
print('Whoops! there is no joke for: {}'.format(first_try[0]))
21+
22+
# Here is a try/except block. Add an else that prints not_joke
23+
try:
24+
not_joke = fun(first_try[2])
25+
except SyntaxError:
26+
print('Run Away!')
27+
else:
28+
print(not_joke)
29+
30+
# What did that do? You can think of else in this context, as well as in
31+
# loops as meaning: "else if nothing went wrong"
32+
# (no breaks in loops, no exceptions in try blocks)
33+
34+
# Figure out what the exception is, catch it and in that same block
35+
#
36+
# try calling the more_fun function with the 2nd language in the list,
37+
# again assigning it to next_joke.
38+
#
39+
# If there are no exceptions, call the more_fun function with the last
40+
# language in the list regardless of whether there was an exception
41+
42+
# Finally, while still in the try/except block and regardless of whether
43+
# there were any exceptions, call the function last_fun with no
44+
# parameters. (pun intended)
45+
46+
langs = ['java', 'c', 'python']
47+
48+
try:
49+
more_joke = more_fun(langs[0])
50+
except IndexError:
51+
next_joke = more_fun(langs[1])
52+
more_fun(langs[2])
53+
last_fun()
54+
55+
Lines changed: 41 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,41 @@
1+
#!/usr/bin/env python3
2+
3+
"""
4+
silly little test module that is designed to trigger Exceptions when
5+
run from the except_exercise.py file
6+
"""
7+
8+
import time
9+
10+
conclude = "And what leads you to that conclusion?"
11+
district = "Finest in the district, sir."
12+
cheese = "It's certainly uncontaminated by cheese."
13+
clean = "Well, it's so clean."
14+
shop = "Not much of a cheese shop really, is it?"
15+
cust = "Customer: "
16+
clerk = "Shopkeeper: "
17+
18+
19+
def fun(reaper):
20+
if reaper == 'spam':
21+
print(s)
22+
elif reaper == 'cheese':
23+
print()
24+
print('Spam, Spam, Spam, Spam, Beautiful Spam')
25+
elif reaper == 'mr death':
26+
print()
27+
return('{}{}\n{}{}'.format(cust, shop, clerk, district))
28+
29+
30+
def more_fun(language):
31+
if language == 'java':
32+
test = [1, 2, 3]
33+
test[5] = language
34+
elif language == 'c':
35+
print('{}{}\n{}{}'.format(cust, conclude, clerk, clean))
36+
37+
38+
def last_fun():
39+
print(cust, cheese)
40+
time.sleep(1)
41+
import antigravity
Lines changed: 88 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,88 @@
1+
#!/usr/bin/env python
2+
import sys
3+
4+
donors = {"John Doe": [152.33, 700], "Jane Doe": [23.19, 50, 15.99]}
5+
6+
def main_loop():
7+
""" Main menu to call different functions """
8+
menu_dict = {'s': thank_you,
9+
'c': report,
10+
'e': email_all,
11+
'q': sys.exit}
12+
while True:
13+
print("\n========== Donation Management System Main Menu ==========")
14+
print("* (s) Send a Thank You *")
15+
print("* (c) Create a Report *")
16+
print("* (e) Send letters to everyone *")
17+
print("* (q) Quit *")
18+
print("==========================================================")
19+
result = input("Please select a menu item: ")
20+
try:
21+
menu_dict[result]()
22+
except KeyError:
23+
print("\n*** Selected item not in the menu. Please try again. ***")
24+
25+
def email(n):
26+
""" Send donor an email with latest donation """
27+
return """
28+
Dear {},
29+
30+
Thank you for your recent generous donation of ${}.
31+
Your support encourages our continued commitment to reaching our goal.
32+
33+
Sincerely,
34+
The Donation Management
35+
""".format(n, donors.get(n)[-1])
36+
37+
def thank_you():
38+
""" Thank you function """
39+
while True:
40+
result = input("\nPlease enter full name, 'list' for current donor list, or 'q' return to the main menu: ")
41+
42+
# Print donor list
43+
if result == "list":
44+
print(str(donors.keys())[11:-2])
45+
# Back to the main menu
46+
elif result == "q":
47+
break
48+
# Create new donations
49+
else:
50+
# Check if donor is already in dict, if not, create a empty list for value
51+
if result not in donors:
52+
donors[result] = []
53+
amount = input("Please enter the amount of donation: ")
54+
try:
55+
donors[result].append(float(amount))
56+
print("\nSending Thank You email...\n{}".format(email(result)))
57+
except ValueError:
58+
print("*** Wrong value format, please enter a valid number. ***")
59+
# Make sure to remove the donor if donation amount not entered correctly
60+
donors.pop(result)
61+
62+
def report():
63+
""" Generate report """
64+
print("\n* Donor Name | Total gifted | Donations | Average gifted *")
65+
print("====================================================================================")
66+
for donor in donors:
67+
# Total amount
68+
total = 0.0
69+
for i in donors[donor]:
70+
total += i
71+
# Number of donations
72+
don = len(donors[donor])
73+
# Average donation
74+
avg = total/don
75+
# Print report
76+
print("* {: <30}{:16.2f}{: >16}{:18.2f} *".format(donor, total, don, avg))
77+
print("====================================================================================")
78+
79+
def email_all():
80+
""" Write a full set of letters to everyone to individual files on disk """
81+
for donor in donors:
82+
with open('{}.txt'.format(donor).replace(" ", "_"), 'w') as f_out:
83+
f_out.write(email(donor))
84+
print("\nLetters generated!")
85+
86+
if __name__ == '__main__':
87+
""" Main function """
88+
main_loop()
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
When squirrels get together for a party, they like to have cigars.
5+
A squirrel party is successful when the number of cigars is between
6+
40 and 60, inclusive. Unless it is the weekend, in which case there
7+
is no upper bound on the number of cigars.
8+
9+
Return True if the party with the given values is successful,
10+
or False otherwise.
11+
"""
12+
13+
14+
def cigar_party(cigars, is_weekend):
15+
return cigars >= 40 and (cigars <= 60 or is_weekend)
Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
You and your date are trying to get a table at a restaurant.
5+
The parameter "you" is the stylishness of your clothes, in the range 0..10, and "date" is the stylishness of your date's clothes.
6+
The result getting the table is encoded as an int value with 0=no, 1=maybe, 2=yes.
7+
If either of you is very stylish, 8 or more, then the result is 2 (yes).
8+
With the exception that if either of you has style of 2 or less, then the result is 0 (no). Otherwise the result is 1 (maybe).
9+
"""
10+
11+
def date_fashion(you, date):
12+
if you <= 2 or date <= 2:
13+
return 0
14+
elif you >= 8 or date >= 8:
15+
return 2
16+
else:
17+
return 1

students/Chao/session06/kwa_ex.py

Lines changed: 9 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,9 @@
1+
#!/usr/bin/env python
2+
3+
def func(fore_color='red', back_color='blue', link_color='yellow', visited_color='green'):
4+
""" Color function with four optional parameters """
5+
return (fore_color, back_color, link_color, visited_color)
6+
7+
def func2(*args, **kwargs):
8+
""" Pass coloe thruogh args and kwargs """
9+
return (args, kwargs)
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
#!/usr/bin/env python
2+
import sys
3+
4+
donors = {"John Doe": [152.33, 700], "Jane Doe": [23.19, 50, 15.99]}
5+
6+
def main_loop():
7+
""" Main menu to call different functions """
8+
menu_dict = {'s': thank_you,
9+
'c': report,
10+
'e': email_all,
11+
'q': sys.exit}
12+
while True:
13+
print("\n========== Donation Management System Main Menu ==========")
14+
print("* (s) Send a Thank You *")
15+
print("* (c) Create a Report *")
16+
print("* (e) Send letters to everyone *")
17+
print("* (q) Quit *")
18+
print("==========================================================")
19+
result = input("Please select a menu item: ")
20+
try:
21+
menu_dict[result]()
22+
except KeyError:
23+
print("\n*** Selected item not in the menu. Please try again. ***")
24+
25+
def email(n):
26+
""" Send donor an email with latest donation """
27+
return """
28+
Dear {},
29+
30+
Thank you for your recent generous donation of ${}.
31+
Your support encourages our continued commitment to reaching our goal.
32+
33+
Sincerely,
34+
The Donation Management
35+
""".format(n, donors.get(n)[-1])
36+
37+
def donor_list():
38+
""" List name of donors """
39+
return str(donors.keys())[11:-2]
40+
41+
def add_donor(name):
42+
""" Create new donor entry """
43+
donors[name] = []
44+
45+
def add_donation(name, amount):
46+
""" Create new donation """
47+
try:
48+
donors[name].append(float(amount))
49+
print("\nSending Thank You email...\n{}".format(email(name)))
50+
except ValueError:
51+
print("*** Wrong value format, please enter a valid number. ***")
52+
# Make sure to remove the donor if donation amount not entered correctly
53+
donors.pop(name)
54+
55+
def thank_you():
56+
""" Thank you function """
57+
while True:
58+
result = input("\nPlease enter full name, 'list' for current donor list, or 'q' return to the main menu: ")
59+
60+
# Print donor list
61+
if result == "list":
62+
print(donor_list())
63+
# Back to the main menu
64+
elif result == "q":
65+
break
66+
# Create new donations
67+
else:
68+
# Check if donor is already in dict, if not, create a empty list for value
69+
if result not in donors:
70+
add_donor(result)
71+
amount = input("Please enter the amount of donation: ")
72+
add_donation(result, amount)
73+
74+
def gen_report(name):
75+
""" Generate report """
76+
total = 0.0
77+
for i in donors[name]:
78+
total += i
79+
# Number of donations
80+
don = len(donors[name])
81+
# Average donation
82+
avg = total/don
83+
# Print report
84+
return "* {: <30}{:16.2f}{: >16}{:18.2f} *".format(name, total, don, avg)
85+
86+
def report():
87+
""" Output report """
88+
print("\n* Donor Name | Total gifted | Donations | Average gifted *")
89+
print("====================================================================================")
90+
for donor in donors:
91+
# Print report
92+
print(gen_report(donor))
93+
print("====================================================================================")
94+
95+
def email_all():
96+
""" Write a full set of letters to everyone to individual files on disk """
97+
for donor in donors:
98+
with open('{}.txt'.format(donor).replace(" ", "_"), 'w') as f_out:
99+
f_out.write(email(donor))
100+
print("\nLetters generated!")
101+
102+
if __name__ == '__main__':
103+
""" Main function """
104+
main_loop()
Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
#!/usr/bin/env python
2+
3+
"""
4+
The squirrels in Palo Alto spend most of the day playing.
5+
In particular, they play if the temperature is between 60 and 90 (inclusive).
6+
Unless it is summer, then the upper limit is 100 instead of 90.
7+
Given an int temperature and a boolean is_summer, return True if the squirrels play and False otherwise.
8+
"""
9+
10+
def squirrel_play(temp, is_summer):
11+
return temp >= 60 and (temp <= 90 or (is_summer and temp <= 100))

0 commit comments

Comments
 (0)