2017.9.1 Codecademy-旅費計算

計算旅費的練習


def hotel_cost(nights):   # 每晚旅館費用140元
  return 140 * nights

def plane_ride_cost(city):    # 不同城市的機票錢
  if city == "Charlotte":
    return 183
  elif city == "Tampa":
    return 220
  elif city == "Pittsburgh":
    return 222
  elif city == "Los Angeles":
    return 475

def rental_car_cost(days):    # 每天租車費用與折扣
  total = 40 * days
  if days >= 7:
    total -= 50
  elif days >= 3:
    total -= 20
return total

# 利用所有已經設定之方程式,計算旅費總額
# spending_money為額外支出

def trip_cost(city,days,spending_money):
  return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money

# 飛洛杉磯5天,額外支出600元

print(trip_cost("Los Angeles",5,600))    

本次旅費總共 = 1955元


自我練習: 計算之前去日本旅遊的大概費用

def hotel(nights):    # 住宿每天約845元台幣
  return 845 * nights

def plane_ticket_go(city_go):    # 去程機票
  if city_go == "Tokyo":
    return 3978

def plane_ticket_back(city_back):    # 回程機票(包含不同機場價格)
  if city_back == "Tokyo":
    return 5779
  elif city_back == "Osaka":
    return 12660 * 0.272               # 當時匯率約 0.272

def trip_cost(city_go,city_back,nights,spending_money):   # 旅費總額計算(額外支出設定日幣->台幣)
  spending_money = spending_money * 0.272
  return hotel(nights) + plane_ticket_go(city_go) + plane_ticket_back(city_back) + spending_money

# 東京進出,8晚,額外支出設定10萬

print('案例1-總花費:')
print(trip_cost("Tokyo","Tokyo",8,100000))

# 東京進,大阪出,33晚,額外支出設定30萬

print('案例2-總花費:')
print(trip_cost("Tokyo","Osaka",33,300000))

案例1-總花費:
43717.0
案例2-總花費:
116906.52

2017.8.31 Codecademy

練習1

  1. def a function called cube that takes an argument called number.
  2. make that function return the cube of that number (i.e. that number multiplied by itself and multiplied by itself once again).
  3. def a second function called by_three that takes an argument called number.
  4. if that number is divisible by 3, by_three should call cube(number) and return its result.
  5. otherwise, by_three should return False.
def cube(number):
   return number * number * number

def by_three(number):
   if number % 3 == 0:
     return cube(number)
 else:
     return False

print(cube(2))
print(by_three(3))
print(by_three(4))

8
27
False

閱讀更多»

2017.8.30 Errors


“break" ouside the loop

break 不能用來中止 if statement,而是中止 Loop


unindent does not match any outer indentation level

新的 python 語法中,代碼縮進 (indentation) 不支援 Tab 和 Space 混用


name ‘raw_input’ is not defined

python 3 只需要 ‘input‘ 即可,沒有 ‘raw_input’


 

2017.8.29 Codecademy

  1. “%s" 可以被 “% ( )"內的字串給取代 (按照順序) (s=substitution)
  2.  " \ " 用來將程式碼換行
name='Jumping'
quest='learning Python'
color='black'

print('Ah, so your name is %s, your quest is %s,' \
' and your favorite color is %s.' % (name, quest, color))

Ah, so your name is Jumping, your quest is learning Python, and your favorite color is black.

閱讀更多»