Exercise 2-1
Repeating my advice from the previous chapter, whenever you learn a new feature, you
should try it out in interactive mode and make errors on purpose to see what goes wrong.
- We’ve seen that n = 42 is legal. What about 42 = n?
- How about x = y = 1?
- In some languages every statement ends with a semicolon, ;. What happens if you put
a semicolon at the end of a Python statement?- What if you put a period at the end of a statement?
- In math notation you can multiply x and y like this: xy. What happens if you try that in
Python?
# --- 1 ---
# We’ve seen that n = 42 is legal. What about 42 = n?
42=n #SyntaxError: can't assign to literal
# --- 2 ---
# How about x = y = 1?
x = y = 1
print(x) # 1
print(y) # 1
print(x, y) # 1 1
# --- 3 ---
# In some languages every statement ends with a semicolon, ; .
# What happens if you put a semicolon at the end of a Python statement?
print(1); # Inspection info: This inspection detects trailing semicolons in statements.
# --- 4 ---
# What if you put a period at the end of a statement?
print(1). # SyntaxError: invalid syntax
# --- 5 ---
# In math notation you can multiply x and y like this: xy .
# What happens if you try that in Python?
x = 1
y = 2
print(x*y) # 2
print(xy) # NameError: name 'xy' is not defined
Exercise 2-2
Practice using the Python interpreter as a calculator:
- The volume of a sphere with radius r is 4/3pi(r**3). What is the volume of a sphere with
radius 5?- Suppose the cover price of a book is $24.95, but bookstores get a 40% discount.
Shipping costs $3 for the first copy and 75 cents for each additional copy. What is
the total wholesale cost for 60 copies?- If I leave my house at 6:52 am and run 1 mile at an easy pace (8:15 per mile), then 3
miles at tempo (7:12 per mile) and 1 mile at an easy pace again, what time do I get
home for breakfast?
# ---1
pi = 3.1415926
r = 5
print(4/3*pi*r**3) # 523.5987666666666
# ---2
cover_price = 24.95
discount = 0.4
count = 60
books_price = cover_price * discount * count
shipping_price = 1*3 + (count-1)*0.75
total_price = books_price + shipping_price
print(total_price) # 646.0500000000001
# ---3
begin = 6*60*60 + 52*60
easy_pace = 8*60 + 15
tempo_pace = 7*60 + 12
total = begin + easy_pace*2 + tempo_pace*3
hour = total // (60*60)
minute = total % (60*60) // 60
second = total % (60*60) % 60
print(hour, minute, second) # 7 30 6