2016-04-22 77 views
0

我希望所有的函数返回一个数值量,但打印结果的时候给我的错误:的Python类型错误:不支持的操作数类型(S) - :“海峡”和“廉政”

Traceback (most recent call last): 

File "C:/Users/Servio/Desktop/TravelTrue.py", line 64, in <module> 
    print 'Its total investment is',costo_viaje(ciudad, model, dias, otros_gastos, noches) ,"$ , ", " Suerte!" 

File "C:/Users/Servio/Desktop/TravelTrue.py", line 59, in costo_viaje 
    return type_auto(model) + alquiler_de_auto(dias) + costo_hotel(noches) + costo_del_vuelo(ciudad) + otros_gastos 

File "C:/Users/Servio/Desktop/TravelTrue.py", line 41, in alquiler_de_auto 
    costo = costo - 100 TypeError: unsupported operand type(s) for -: 'str' and 'int' 

的代码是

def costo_hotel(noches): 

    return 140 * noches 

def costo_del_vuelo(ciudad): 

    cities = { 
     "Cordoba": 821, 

     "Iguazu": 941, 

     "Ushuaia": 1280, 

     "Bariloche": 1848, 

     "Palermo": 1242, 

     "Francia": 6235, 

     "Yugoslavia": 2125, 

     "Vietnam": 2532, 

     "Buenos Aires": 2499, 

     "Montevideo": 2129, 

     "Mexico": 1499, 

     "Moscu": 3499, 

     "Maracaibo": 4499, 

     "Irak": 9998, 

    } 

    return cities[ciudad] 


def type_auto(model): 
    costo_type = model 
    if model == "deportivo": 
     costo_type = 860 
    elif model == "familiar": 
     costo_type = 345 
    return costo_type 


def alquiler_de_auto(dias): 
    costo = dias * 338 
    if dias >= 7: 
     costo = costo - 100 
    elif dias >= 3: 
     costo = costo - 50 
    return costo 

model = raw_input("Que modelo de auto llevara?") 

noches = raw_input("Cuantas noches estara en el hotel?") 

dias = raw_input("Cuantos dias tendra el auto?") 

ciudad = raw_input("A que ciudad viajara?") 

otros_gastos = raw_input("Gastos Generales?") 



def costo_viaje(ciudad, model, dias, otros_gastos, noches): 
    return type_auto(model) + alquiler_de_auto(dias) + costo_hotel(noches) + costo_del_vuelo(ciudad) + otros_gastos 

print 'Its total investment is',costo_viaje(ciudad, model, dias, otros_gastos, noches) ,"$ , ", " Suerte!" 

回答

2

您不能使用操作数与不兼容的类型。举例来说,如果我有以下几点:

x = 3 
fruit = "apples" 

我不能这样做,

print(x + fruit) 

,因为它们的类型是不同的 - 一个是一个整数,其他的字符串。当强制(铸造)变量为另一种类型时,如下所示:

print(str(x) + " " + fruit) 

它们现在都是字符串和兼容的,3变为“3”。该语句将成功地打印出:

3 apples 

注意:做STR(X)时,变量x仍然保持一个整数,但STR(x)返回一个字符串。

因此,在功能

alquiler_de_auto(dias) 

你被乘以一个整数dias,但dias不是整数 - dias是一个字符串,因为raw_input()总是返回一个字符串。你可以这样做int(dias)将字符串更改为一个整数,从而使它们兼容的类型。

+1

我会补充说str(x)返回对象x的字符串版本,而x本身仍然是一个整数。 – EngineerCamp

+0

所以... 我认为我已经解决了“int”中的tranformando 3:函数 需要输入的数字 但是,raw_input链总是会问?然后这个很好的变换int或str,它取决于参数: –

+0

{model = raw_input(“Que modelo de auto llevara?”) noches = int(raw_input(“Cuntas noches estara en el hotel?”)) 迪亚斯= INT(的raw_input( “Cuantos Dias的tendra EL自动?”)) 城=的raw_input( “A阙城viajara?”) otros_gastos = INT(的raw_input( “Gastos GENERALES?”))} –

相关问题