How does it know what values to use for each parameter?



How does it know what values to use for each parameter?


Before you call the function, the program has no way of knowing what the values will be, unless you set a default by typing parameter_name=0, for example. That would set the default value of parameter parameter_name to 0.
Otherwise it simply assigns parameter values with the arguments provided when the function is called. With power(), the function defined and used in this exercise, we provide it two arguments: a base and an exponent, in that order. If we did power(10, 2), then 10 would be assigned to base, and 2 assigned to exponent to be used throughout the function with those values.

FAQ: Learn Python: Functions - Parameters and Arguments

The values will be read in to the function in the order they are written into the call arguments.

>>> def hotel_cost(days):
    return days * 140

>>> def car_rental_cost(days):
    return 40 * days

>>> def plane_ride_cost(city):
    if city == 'Tampa': return 222

>>> def trip_cost(city, days):
    return hotel_cost(days) + car_rental_cost(days) + plane_ride_cost(city)


What could possibly go wrong with this function? Answer, if the arguments are not given in the correct order things can quickly go awry.

>>> print (trip_cost(7, 'Tampa'))
Traceback (most recent call last):
  File "<pyshell#24>", line 1, in <module>
    print (trip_cost(7, 'Tampa'))
  File "<pyshell#23>", line 2, in trip_cost
    return hotel_cost(days) + car_rental_cost(days) + plane_ride_cost(city)
TypeError: Can't convert 'NoneType' object to str implicitly

We can see how important it is to pay close attention to order of arguments.


Why didn’t we use any return lines in this particular exercise?