Think Python Exercises 2

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.

  1. We’ve seen that n = 42 is legal. What about 42 = n?
  2. How about x = y = 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?
  4. What if you put a period at the end of a statement?
  5. 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:

  1. The volume of a sphere with radius r is 4/3pi(r**3). What is the volume of a sphere with
    radius 5?
  2. 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?
  3. 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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值