“””
起跳價:70元 (1.25 KM)
續程: +5元/0.2KM
“””
def taxi(km:float) -> int :
if 0 <= km <= 1.25:
cost = 70
elif km > 1.25:
cost = int( (70 + 5*(km-1.25)/0.2) )
else: cost=”請輸入正確的公里數(>=0)”
return cost
print(“預估車資為:”,taxi(1.25))
print(“預估車資為:”,taxi(1.45))
print(“預估車資為:”,taxi(-1))
![Python: 自定義函數計算計程車車資(先typing,再用預設值), 巢狀字典以及typing.Union[ ], assert 斷言 - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2022/09/20220917182038_43.png)
#使用assert 斷言:
#assert cond, msg相當於
#if not cond : raise AssertionError(msg)
![Python: 自定義函數計算計程車車資(先typing,再用預設值), 巢狀字典以及typing.Union[ ], assert 斷言 - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2022/09/20220926134907_11.png)
進階版:
“””
舒適型:
起跳價:70元 (1.25 KM)
續程: +5元/0.2KM
“””
def taxi(km:float,init=70,conti=5) -> int :
if 0 <= km <= 1.25:
cost = init
elif km > 1.25:
cost = int( (init + conti*(km-1.25)/0.2) )
else: cost=”請輸入正確的公里數(>=0)”
return cost
menu={
“舒適型”: False,
“豪華型”: False,
“6人座”: False,
“寶寶多元”: False
}
km = eval( input(“請輸入公里數(km) “) )
m = eval( input(“請輸入車型(1,2,3,4),\n \
1:舒適型, 2:豪華型, 3:六人座 , 4:寶寶多元 ” ) )
if m == 1 : menu[“舒適型”] = True
elif m == 2 : menu[“豪華型”] = True
elif m == 3 : menu[“6人座”] = True
elif m == 4 : menu[“寶寶多元”] = True
if menu[“舒適型”]: print(“預估車資為:”,taxi(km,70,5))
elif menu[“豪華型”]: print(“預估車資為:”,taxi(km,98,7))
elif menu[“6人座”]: print(“預估車資為:”,taxi(km,98,7))
elif menu[“寶寶多元”]: print(“預估車資為:”,taxi(km,84,6))
![Python: 自定義函數計算計程車車資(先typing,再用預設值), 巢狀字典以及typing.Union[ ], assert 斷言 - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2022/09/20220918130415_30.png)
輸出結果:
![Python: 自定義函數計算計程車車資(先typing,再用預設值), 巢狀字典以及typing.Union[ ], assert 斷言 - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2022/09/20220918130508_71.png)
#使用巢狀字典以及typing.Union[ ]
#注意Union[ ] 使用的是[ ], 不是( )
#且首字大寫
![Python: 自定義函數計算計程車車資(先typing,再用預設值), 巢狀字典以及typing.Union[ ], assert 斷言 - 儲蓄保險王](https://savingking.com.tw/wp-content/uploads/2022/09/20220923222039_57.png)
推薦hahow線上學習python: https://igrape.net/30afN






![Python: pandas.Series如何只保留str,去除重複值?#isinstance(x:Any, str) -> bool #.drop_duplicates() #Series.apply( function )逐元素應用function運算 #DataFrame.apply( function )逐Series應用function運算 .drop_duplicates() 跟.unique()有何差別? df.drop_duplicates() 等效於 df[~df.duplicated()] Python: pandas.Series如何只保留str,去除重複值?#isinstance(x:Any, str) -> bool #.drop_duplicates() #Series.apply( function )逐元素應用function運算 #DataFrame.apply( function )逐Series應用function運算 .drop_duplicates() 跟.unique()有何差別? df.drop_duplicates() 等效於 df[~df.duplicated()]](https://i2.wp.com/savingking.com.tw/wp-content/uploads/2024/11/20241123194900_0_5218de.png?quality=90&zoom=2&ssl=1&resize=350%2C233)



近期留言