Summary
In this lesson, you learned that:
- A function is a named piece of code that you write once and can run as many times as you need. Thanks to functions, you don't have to repeat code, and when you change a function, the change applies everywhere it's used.
- You define a function with the keyword
def, a name, parentheses with parameters, a colon and an indented body:def print_area(width, height):. A definition alone doesn't run anything. - You call a function with its name and parentheses:
print_area(5, 6). A function must be defined before it is called, otherwise you get aNameError. - A parameter is a name in the definition, an argument is a value in the call. Arguments go into parameters in order. A missing argument ends with a
TypeError, unless the parameter has a default value:def print_price(price, currency="EUR"):. returngives a value back to the place of the call, so you can use the call like a value:print(add(2, 3)),total = add(2, 3) * 2.print()only shows a value; the program can't work with it. A function withoutreturnreturnsNone. A function that calculates something should return the result.returnends the function right away, and the rest of the function doesn't run. With conditions, the firstreturnthat runs wins.- Variables created inside a function, and its parameters, are local: they exist only inside that function. Values go into a function through its parameters and come out with
return. - A function can take a list, go through it with a loop and return a result. The
returngoes after the loop, indented as much as thefor.
In the next lesson, Dictionaries, you will learn to keep values that belong together, such as a person's name and age, in a single value.
Instructions
- 1
Let's practice. Write a function
cart_totalwith two parameters:prices(a list of prices) anddiscountwith the default value0. The function returns the sum of the prices minus the discount. Printcart_total(cart)andcart_total(cart, 50). The program prints280and230. - 2
Write a function
format_pricewith a parameterpricethat returns the price as text with the currency, for example"230 EUR"for230. Use it to print the discounted total with a label:print(f"To pay: {format_price(cart_total(cart, 50))}"). Python first callscart_total, and passes the value it returns toformat_price. The program printsTo pay: 230 EUR.