PythonLesson 9 of 16

Functions in Python: def and return

A function is a named piece of code you can call as often as you like. Write the discount rule once and use it everywhere.

Key points

  • def name(parameters): starts a function, the body is indented
  • return sends the result back to where the function was called
  • A function without return gives back None
  • percent=10 is a default, so the caller may leave it out
  • Arguments can be passed by name: final_price(500, percent=5)

Example

def greet(name, greeting="Hi"):    return f"{greeting}, {name}!" print(greet("Leo"))print(greet("Mia", "Good morning")) def area(width, height):    return width * height room = area(4, 3)print("Room:", room, "m2")

greet runs twice: first with the default greeting, then with a custom one. The result of area goes into a variable like any other value.

Task

How to use the editor⌘ Enter or Ctrl Enter runs the code, ⇧ ⌘ Enter checks the task.Tab and Shift Tab indent the line or the selection; Esc, then Tab leaves the editor.The check compares what the program printed with the task; spaces at line ends do not matter.After two failed checks you may open the solution. Your code is kept in this browser.

Finish final_price: it takes a price and a discount percent (10 by default) and returns the price after the discount.

Output

What your program prints appears here.