这个脚本有什么问题

时间:2016-12-25 11:07:54

标签: python python-2.x

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

1 个答案:

答案 0 :(得分: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异常。