Don't understand the point of calling a function


#1


I'm stuck at Taking A Vacation, exercise 7.

I'm just confused at calling functions. Why does the following work in the semi last line:
hotel_cost(days)
when the original is
def hotel_cost(nights):
return 140 * nights

Does that mean days will replace nights? but in that case what happens to return 140 * nights? Does it become
hotel_cost(days):
return 140 * days
???
Thanks.


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
    
def rental_car_cost(days): 
    cost = 40 * days
    if days >= 7:
        cost -= 50
    elif days >= 3:
        cost -= 20
    return cost
    
def trip_cost(city, days, spending_money):
    return rental_car_cost(days) + hotel_cost(days) + plane_ride_cost(city) + spending_money


print trip_cost("Los Angeles", 5, 600)


#2

Yes, that is essentially what happens.

Inside a function definition you can make a new set of variables (even if they have the same name as somewhere else in the code) and the values passed in become those variables

Then when you call the function, whatever value you give it is put into the variable you made in the definition, so here the value of days is put into hotel_cost's nights. Then, in the function, math is done with that value, and then it's returned.


#3

Thank you for replying, it was sorta bugging me that the code worked but I couldn't understand why.


#4

The most basic thing about a function is it will do a job on any input you give it.

if a function is

def blah(a):
    return a + 2

then i can call blah(0) and I will get 2, but I can also just call blah(1) to get 3 or blah(2) to get 4 and so on. I never change the code of blah(); i only have to give it different information.

Later on you'll have all kinds of functions to do different things. an example is getting the average score of a student. You write one function to get an average grade, then just call average(Sally), average(Joe), etc. and the same code does the work on different students to get whatever value you want

In your question's example, the information we give it is the number of nights we stay. From the outside, when we call it with hotel_cost(days), we just mean that the value that is stored in "days" is the value that we want to give hotel_cost to multiply by 140. that's all.

it's bizarre but sometimes it's easier to understand when a function is written with (a, b, c, x, y) instead of (nights, days, cost, blah blah blah) just because it helps separate the function from the calling context


#5

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