Plane_ride_cost does not return 220 when the city is Tampa


#1


www.codecademy.com/courses/python-beginner-P5YtY/1/2?curriculum_id=4f89dab3d788890003000096

Oops, try again. It looks like plane_ride_cost does not return 220 when the city is Tampa..>


def hotel_cost(nights):
    
    return 140 * nights

def plane_ride_cost(city):
    
    if city == 'Charlotte':
        return 183
        
        if city == 'Tampa':
            return 220
            
            if  city == 'Pittsburgh':
                return 222
                
                if  city == 'Los Angeles':
                    return 475


#2

I think the problem is because of the indentation. Put all if at same indent. But, better way is for the next condition check it with elif.

 def plane_ride_cost(city):
    if city == 'Charlotte':
        return 183 
    elif city == 'Tampa':
        return 220
     #and so on..

#3

Your indents are incorrect, it should be:

def hotel_cost(nights):
    
    return 140 * nights

def plane_ride_cost(city):
    
    if city == 'Charlotte':
        return 183
        
    if city == 'Tampa':
        return 220
            
    if  city == 'Pittsburgh':
         return 222
                
    if  city == 'Los Angeles':
         return 475

#4

@zylm It still works the same way with "if" instead of "elif", Codecademy simple taught us to use "elif". :slight_smile:


#5

@chipjumper36731 Yes, That is correct. Personally, i prefer to use "elif" simply because it make me easy to read my code. However, i do really confuse if there any different of them?

Updated:
After doing some test, I found out that, if we use if instead of elif, I think it is inefficient, because the condition will always be checked.

Here is what i do to see the different.

def test_if(x):
    if x <= 1:
        print "TRUE"
    if x == 1:
        print "TRUE"
    if x > 1:
        print "FALSE"

print test_if(1)

above code will output:

TRUE
TRUE

but, if change it to elif:

def test_if(x):
    if x <= 1:
        print "TRUE"
    elif x == 1:
        print "TRUE"
    elif x > 1:
        print "FALSE"
    
print test_if(1)

this code will output:

TRUE

So, I assume that, if we do not use "elif", although the condition already satisfied, it still will check the second condition. That's why I think if we work on a big project, this would be inefficient.

does my assumption right? I would really appreciate for a proper explanation about this.


#6

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.