TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’

这段代码是在Taking a Vacation中的“Plan Your Trip!”小节
按照要求,我定义了4个函数,程序流程是这样的:
1. 分别赋3个值给变量city,days和spending_money
2. 用这3个变量调用函数trip_cost()
3. 在函数trip_cost()中返回旅行的总花费,包括住宿费用,飞机费用和租车费用,这些费用用另外3个函数计算

def hotel_cost(nights):
    return nights*140

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):
    if days < 3:
    #不管是str或者int,都可以跟3进行对比
        return days*40
    elif days >= 3 and days < 7:
        return days*40-20
    elif days >= 7:
        return days*40-50 #<---20

def trip_cost(city, days, spending_money):
    a = hotel_cost(days)
    b = plane_ride_cost(city)
    c = rental_car_cost(days) #<---25
    return (a + b + c + spending_money) 

city=raw_input("Please provide city that you want to trip:")
days=raw_input("How many days you need to live and rent car:")
spending_money=raw_input("Other money spending:")
print trip_cost(city, days, spending_money) #<---31

看上去没什么问题,但执行时发现出现如下报错:

x-mac:python frank$ python trip.py 
Please provide city that you want to trip:Tampa
How many days you need to live and rent car:8
Other money spending:1000
Traceback (most recent call last):
  File "trip.py", line 31, in 
    print trip_cost(city, days, spending_money)
  File "trip.py", line 25, in trip_cost
    c = rental_car_cost(days)
  File "trip.py", line 20, in rental_car_cost
    return days*40-50
TypeError: unsupported operand type(s) for -: 'str' and 'int'

这是什么问题?
我尝试单独调用这3个子函数,发现没有任何问题,只要调用主函数trip_cost()就会有问题。。。
又测试了下,发现只要用raw_input才会有问题,如果不用raw_input,直接赋值打印“print trip_cost(“Tampa”, 8, 1000)”,也不会有问题!?
经过测试和google,终于发现了问题,raw_input() 得到的是字符串str,不是数字int;而在rental_car_cost()中,返回值需要计算,str不能跟int计算,所以必须转换str为int才可以。在调用函数时,只要这么调用就可以了:
print trip_cost(city, int(days), int(spending_money))
结果:

x-mac:python frank$ python trip.py 
Please provide city that you want to trip:Tampa
How many days you need to live and rent car:8
Other money spending:1000
2610
本文出自 Frank's Blog

版权声明:


本文链接:TypeError: unsupported operand type(s) for -: ‘str’ and ‘int’
版权声明:本文为原创文章,仅代表个人观点,版权归 Frank Zhao 所有,转载时请注明本文出处及文章链接
你可以留言,或者trackback 从你的网站

留言哦

blonde teen swallows load.xxx videos