True/False
- True
- False
- True
- False
- True
- True
- False
- False
- True
- False
Multiple Choice
- c
- c
- b
- c
- b
- c
- a
- c
- c
- c
Discussion
- Answers will vary.
- Simlar in that the try/except conditionally executes a block of code. Different in that the try except does not contain a specific desicion, but executes the except based on an exception that ay be raised by any statement in the try block.
-
- Trees
Larch
Done - Trees
Chestnut
Done - Spam Please!
Done - Cheese Shoppe
Cheddar
Done - It's a late parrot!
Done - Cheese Shoppe
Cheddar
Done
- Trees
Programming Exercises
1.
def main():
try:
t = float(input("Enter the work time: "))
w = float(input("Enter the standard wage: "))
if t<=40:
s = t * w
else:
s = 40 * t + 1.5 * w * (t - 40)
print("The total week salary is {0:.2f} dollars.".format(s))
except:
print("Something went wrong,sorry!")
main()
2
def main():
n = int(input('Enter the mark; '))
if n==5:
print('A')
elif n==4:
print('B')
elif n==3:
print('C')
elif n==2:
print('D')
elif n==1:
print('E')
else:
print('F')
if __name__ == '__main__':
main()
3
def main():
n = int(input('Enter the mark: '))
if 89 < n <= 100:
print('A')
elif 80 <= n < 90:
print('B')
elif 70 <= n < 80:
print('C')
elif 60 <= n < 70:
print('D')
else:
print('F')
if __name__ == '__main__':
main()
4
def main():
n = int(input('Enter the mark: '))
if 89 < n <= 100:
print('A')
elif 80 <= n < 90:
print('B')
elif 70 <= n < 80:
print('C')
elif 60 <= n < 70:
print('D')
else:
print('F')
if __name__ == '__main__':
main()
5
def main():
try:
weight = float(input("Enter your weight(in pounds): "))
height = float(input("Enter your height(in inches): "))
BMI = 720 * weight / height / height
if BMI < 19:
print("Your weight is below the healthy weight.")
elif BMI >25:
print("Your weight is above the healthy weight.")
else:
print("Congratulaions!Your weight is normal.")
except:
print("Please check your input.")
if __name__ == "__main__":
main()
6
def fine(speed,limitSpeed):
if speed <= limitSpeed:
print('The speed is in legal range.')
elif limitSpeed < speed <= 90:
charge = 50 + 5 * (speed - limitSpeed)
print('Speeding!Speeding ticket is {0:.2f} dollars.'.format(charge))
else:
charge = 250 + 5 * (speed - limitSpeed)
print('Speeding!Speeding ticket is {0:.2f} dollars.'.format(charge))
def main():
speed = float(input("Enter the speed: "))
limitSpeed = float(input("Enter the limit-speed: "))
fine(speed,limitSpeed)
if __name__ == "__main__":
main()
7
def workTime(sh,sm,eh,em):
wtime = 60 * (eh - sh) + em - sm
return wtime
def main():
start = input("Enter the start time: ").split(':')
end = input("Enter the end time: ").split(':')
startH,startM = int(start[0]),int(start[1])
endH,endM = int(end[0]),int(end[1])
changeH,changeM = 21,0
worktime = workTime(startH,startM,endH,endM)
if worktime < 0:
worktime = workTime(startH,startM,endH + 24,endM)
if endH < changeH:
wage = 2.50 * worktime / 60
elif startH >= changeH:
wage = 1.75 * worktime / 60
else:
wage1 = workTime(startH,startM,changeH,changeM)*2.50 / 60
wage2 = workTime(changeH,changeM,endH,endM)*1.75 / 60
wage = wage1 + wage2
print("The wage is ${0:.2f}.".format(wage))
if __name__ =="__main__":
main()
8
def main():
print("Congressional Eligibility\n")
age = int(input("Enter your age: "))
residency = int(input("Enter years of residency: "))
if age > 24 and residency > 6 :
if age > 29 and residency > 8 :
print("You are eligible for the Senate and the House.")
else:
print("You are eligible only for the House.")
else:
print("You are not eligible for Congress.")
if __name__ =='__main__':
main()
9
def main():
year = int(input("Enter a year(1982-2048): "))
a = year % 19
b = year % 4
c = year % 7
d = (19*a + 24) % 30
e = (2*b + 4*c + 6*d + 5) % 7
f = d + e
if 1982 <= year<= 2048:
if f <= 9:
day = 22 + f
print("The date of the Easter is March {0}.".format(day))
else:
day = f - 9
print("The date of the Easter is April {0}.".format(day))
else:
print("That is not a year between 1982 and 2048.")
if __name__ == '__main__':
main()
10
def main():
print("Easter Calculator for 1900-2099\n")
year = int(input("Enter the year: "))
if 1900 <= year <= 2099:
a = year % 19
b = year % 4
c = year % 7
d = (19*a + 24) % 30
e = (2*b + 4*c + 6*d +5)%7
day = 22 + d + e
# This could also be a multi-way decision
if year in [1954, 1981, 2049, 2076]:
day = day - 7
if day > 31:
print("Easter is on April", day-31)
else:
print("Easter is on March", day)
else:
print("That's not a year between 1900 and 2099.")
if __name__ == '__main__':
main()
11
def main():
year = int(input("Enter a year: "))
if year % 400 == 0 or (year % 4==0 and year % 100 != 0):
print(year,"is a leap year.")
else:
print(year,"is not a leap year.")
if __name__ =="__main__":
main()
12
def main():
inDate = input("Enter the date(year/month/day): ").split("/")
year,month,day = int(inDate[0]),int(inDate[1]),int(inDate[2])
if jugdeYear(year) == True:
days = [31,29,31,30,31,30,31,31,30,31,30,31]
else:
days = [31,28,31,30,31,30,31,31,30,31,30,31]
if month in [1,2,3,4,5,6,7,8,9,10,11,12]:
if 0< day <= days[month - 1]:
print("Valid date.")
else:
print("Invalid date.")
else:
print("Invalid date")
def jugdeYear(year):
if year % 400 == 0 or (year % 4==0 and year % 100 != 0):
return True
else:
return False
if __name__ == '__main__':
main()
13
def main():
inDate = input("Enter the date(year/month/day): ").split("/")
year,month,day = int(inDate[0]),int(inDate[1]),int(inDate[2])
if jugdeYear(year) == True:
days = [31,29,31,30,31,30,31,31,30,31,30,31]
else:
days = [31,28,31,30,31,30,31,31,30,31,30,31]
if month in [1,2,3,4,5,6,7,8,9,10,11,12]:
print("Valid date.")
num = 0
if 0 < day <= days[month - 1]:
for i in range(month):
if i != (month - 1):
num = num + days[i]
else:
num = num + day
print("The day number is {0}.".format(num))
else:
print("Invalid date.")
else:
print("Invalid date")
def jugdeYear(year):
if year % 400 == 0 or (year % 4==0 and year % 100 != 0):
return True
else:
return False
if __name__ == '__main__':
main()
14
from graphics import *
import math
def main():
r = float(input("Enter r: "))
y = float(input("Enter y: "))
if r*r-y*y >= 0:
win = GraphWin('',800,800)
win.setCoords(-10,-10,10,10)
x = math.sqrt(r*r - y*y)
cic = Circle(Point(0,0),r)
lin = Line(Point(-10,y),Point(10,y))
cic.draw(win)
lin.draw(win)
p1 = Point(-x,y)
p1.setFill("red")
p1.draw(win)
p2 = p1.clone()
p2.move(2*x,0)
print("Click to quit.")
win.getMouse()
win.close()
else:
print("Unsupported condition!")
if __name__ =='__main__':
main()
15
from graphics import *
import math
def main():
win = GraphWin("Line Segment Info", 400, 400)
win.setCoords(-10,-10,10,10)
win.setBackground(color_rgb(255,255,255))
msg = Text(Point(0,-9.5), "Click on endpoints of a line segment.")
p1 = win.getMouse()
p2 = win.getMouse()
ln = Line(p1,p2)
ln.draw(win)
p = ln.getCenter()
p.setFill("red")
p.draw(win)
dx = p1.getX() - p2.getX()
dy = p1.getY() - p2.getY()
if dx == 0:
slope = 'inf'
else:
slope = dy/dx
length = math.sqrt(dx*dx+dy*dy)
print("The length is {0:.3},the slope is {1:.3}.".format(length,slope))
win.getMouse()
win.close()
if __name__ == '__main__':
main()
16
from graphics import *
import math
def drawTarget(color,window,radius):
cic = Circle(Point(0,0),radius)
cic.setFill(color)
cic.setOutline(color)
cic.draw(window)
def dist(p):
dx = p.getX()
dy = p.getY()
d = math.sqrt(dx**2 + dy**2)
return d
def drawShot(p,window):
sq = Circle(p,0.15)
sq.setFill(color_rgb(0,255,255))
sq.setOutline(color_rgb(0,255,255))
sq.draw(window)
def main():
win = GraphWin('Arrow Target',600,600)
win.setCoords(-12.5,-12.5,12.5,12.5)
win.setBackground(color_rgb(144,144,144))
colors = ['white','black','blue','red','yellow']
word1 = Text(Point(-9,11.5),"Shoot !")
word1.setStyle("bold")
word1.setTextColor("red")
word1.draw(win)
word2 = Text(Point(7,11.5),"Score:")
word2.setStyle("bold")
word2.draw(win)
word2.setFill("blue")
word3 = Text(Point(-2,11.5),"Bonus point:")
word3.setStyle("bold")
word3.setFill(color_rgb(255,255,0))
word3.draw(win)
for i in range(5):
drawTarget(colors[i],win,(10 - 2*i))
score = 0
for i in range(5):
p = win.getMouse()
drawShot(p,win)
if dist(p) <= 2:
score = score + 9
bonus = 9
elif 2 < dist(p) <= 4:
score = score + 7
bonus = 7
elif 4 < dist(p) <= 6:
score = score + 5
bonus = 5
elif 6 < dist(p) <= 8:
score = score + 3
bonus = 3
elif 8 < dist(p) <= 10:
score = score + 1
bonus = 1
else:
score = score
print("The score is {0}".format(score))
word2.setText("score: {0}".format(score))
word3.setText("Bonus point: {0}".format(bonus))
word1.setText('Total score: {0}'.format(score))
win.getMouse()
word1.setText("Click to quit.")
win.getMouse()
win.close()
if __name__ =='__main__':
main()
17
# c07ex17.py
# Bouncing circle
import time
from graphics import *
def main():
win = GraphWin("Bounce", 401, 401)
win.setCoords(-200,-200, 200, 200)
radius = 20
c = Circle(Point(0,160), radius)
c.setFill("red")
c.draw(win)
dx = 1
dy = 1
for i in range(10000):
c.move(dx,dy)
center = c.getCenter()
cx, cy = center.getX(), center.getY()
if 200 - abs(cx) == radius:
dx = -dx
if 200 - abs(cy) == radius:
dy = -dy
update(30)
# This exit is optional. The break statement is covered in Chapter 8
if win.checkMouse() != None:
break
win.close()
main()
17题答案是针对一种特殊情况的,不适用绝大多数情况。笔者日后会对其进行改进。
18:寻找上一章第六题
def caulateCS():
a,b,c = 0,0,0
while a <= 0:
a = float(input("Please enter the value of a: "))
while b <= 0:
b = float(input("Please enter the value of b: "))
while c <= 0:
c = float(input("Please enter the value of c: "))
if a+b <= c or a+c <= b or b+c <= a:
print("The three sides cannot form a triangle!")
else:
p = (a + b + c)/2
area = ((p - a)*(p - b)*(p - c)*p)**0.5
print("The area of the triangle is {0:.2f},the circumfirence of the triangle is {1:.2f}.".format(area,2*p))
def main():
try:
caulateCS()
except:
print("Check the data you input.")
if __name__ == "__main__":
main()
笔者想要实现即使输入错误数据,程序也不会结束,而是继续提示知道用户输入完全正确的数据。日后完善。各位也可以在评论区或者私信我,提出改进意见。