3/7 Coding question


#1

First off, here is the code that was accepted and that allowed me to move forward to lesson 4:

Code #1:

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

I realized afterward that, technically, my code should have been this:

Code #2:

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

It is my understanding that Code #1 could possibly return several answers, when that is not necessarily desirable. On the other hand, Code #2 can only return one answer because elif statements are only evaluated if preceding if/elif statements are false. Which, in this case, is more meaningful to the task at hand.

So my question is: Why was I able to advance with Code #1? Is all of my above thinking correct? Could sticking with all if statements cause problems down the line?

Thanks!


#2

If im reading your question right and if i remember why its like that because if you do something like this

if number < 1:
    print "less than 1"
if number > 1:
    print "more than 1"
else:
    print "1"

if you do this it will check if the number is less than 1 and if it is print "less than 1"
and than goes to the next if statement which is
it checks if the number is greater than 1 and prints "more than 1"
if it is not greater than 1 (-5) it will print "1" even tho the number is less than 1 and should print "less than 1" but since the else statement is in the second if statement it doesnt check the first one

so if the number is -5 it will print the first if statement and also the else statement
but if you do

if number < 1:
    print "less than 1"
elif number > 1:
    print "more than 1"
else:
    print "1"

if will check all 3 of them and if neither of the first 2 are correct it will do the else and only the else

hope this helps