2016-12-25 118 views
-3
def hotel_cost(nights): 
    cost = nights * 40 
    return cost 
def plane_ride_cost(city): 
    if city == "charolette": 
     cost = 180 
    elif city == "los angeles": 
     cost = 480 
    elif city == "tampa": 
     cost = 200 
    elif city == "pittspurgh": 
     cost = 220 
    return cost 
def rental_car_cost(days): 
    cost = days * 40 
    if days >= 7: 
     cost -= 50 
    elif days >= 3: 
     cost -= 20 
    return cost 

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

city_list = ("charolette", "los angeles", "tampa", "pittspurgh") 

print "we only support one of those cities" + str(city_list) 

city = raw_input (" please choose the city you want to go ") 
days = 0 
spending_money = 0 
if city in city_list: 
    days = raw_input("how much days you wanna stay ") 
    spending_money = raw_input("how much money do you wanna spend there") 
    print trip_cost(city, days, spending_money) 
else: 
    print 'error' 

它總是產生這個錯誤什麼是錯這個腳本

rint trip_cost(city, days, spending_money) 
    File "/home/tito/test 3 .py", line 23, in trip_cost 
    return (hotel_cost(days)) + (plane_ride_cost(city)) + (rental_car_cost(days)) + (spending_money) 
TypeError: cannot concatenate 'str' and 'int' objects 
+2

'spend_money = int(raw_input(「你想在那裏花多少錢」))'會解決它。 –

回答

1

用戶輸入轉換爲相應的數據類型應該有所幫助:

if city in city_list: 
    days = int(raw_input("how many days you wanna stay ")) 
    spending_money = float(raw_input("how much money do you wanna spend there")) 

你總是得到一個字符串返回從raw_input。你可以將一個字符串轉換爲一個整數int()或一個浮點數float()。如果字符串不能轉換成這種數據類型,你將得到一個ValueError異常。

+0

感謝邁克,這是有用的:) :) –