yihang hwang
yihang hwang

Reputation: 419

error: 'int' object is not iterable in Python

look at the error message ,everything i can't find the error ,we insert the value into function trip_cost('Los Angeles', 4) , and city will be string and days will be int type ,is that any knowledge i should know?

code:

def hotel_cost(nights):
    return 140*nights

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
    else :
        return 123

def rental_car_cost(days):
    total = days *40
    if days >=7:
        total=total-50
        return total
    elif days >= 3 :

        total=total-20
        return total
    else :
        return total
def prev_add(a,b):
    return sum(a,b)
def trip_cost(city,days):
    nights = days
    hotel_cost_price = hotel_cost(nights)
    rental_car_price=rental_car_cost(days)
    prev_price = prev_add(rental_car_price,hotel_cost_price)
    plane_ride_price = plane_ride_cost(city)
    return sum(prev_price,plane_ride_price)

========================

error code :

 trip_cost('Los Angeles', 4) raised an error: 'int' object is not iterable 

===================

Upvotes: 0

Views: 509

Answers (3)

Code Piligrim
Code Piligrim

Reputation: 1

It's simpler, you don't need the extra prev_add function.

The solution is to set your city variable (which you pass to trip_cost) to the result of plane_ride_cost(city) inside trip_cost

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

Upvotes: 0

kvivek
kvivek

Reputation: 3461

Just check the sum help documentation. sum(3,2) will fail, but sum((3,2)) will work. Since sum(3,2) is considered as sum function called with two parameters passed, while sum((3,2)) is considered as one parameter passed to the sum function.

>>> help(sum)
Help on built-in function sum in module __builtin__:

sum(...)
    sum(sequence[, start]) -> value

    Return the sum of a sequence of numbers (NOT strings) plus the value
    of parameter 'start' (which defaults to 0).  When the sequence is
    empty, return start.

>>>

Upvotes: 2

NPE
NPE

Reputation: 500177

sum() computes the sum of an iterable, such as a list. However, you are trying to use it to add two numbers:

def prev_add(a,b):
    return sum(a,b)

If you want to simply add a and b, use +:

def prev_add(a,b):
    return a + b

In this case, I would get rid of the function altogether and just use addition.

The same goes for your use of sum() in

return sum(prev_price,plane_ride_price)

Upvotes: 4

Related Questions