DMarlon Studio

Lesson 15 · 15 of 20

Functions · Python

Create your own Python functions with def, pass them data and send results back with return, while printing a café's receipts.

Python · Functions in DMarlon Studio: the example's code and its output in the terminal

A function is a named block of code you can use as many times as you like. You create it with def, the name, parentheses and a colon; the body is indented. Creating it does not run it: welcome() calls it, and only then are the greeting and the line printed.

Inside the parentheses you can put parameters: names that receive the values of the call. In serve("latte"), drink is "latte"; in the next call it is "hot chocolate". So one function works for any drink.

return sends a result back to the caller. with_vat(2.50) works out the price with 21 % VAT and returns it, so the call can go inside an f-string, be stored in a variable or be added to another: with_vat(3.00) + with_vat(1.80).

A function can call other functions: receipt_line() uses with_vat() to print each line of the receipt, with the name aligned left and the price aligned right.

Code · main.py

# def creates a function: a named block of code you can reuse.def welcome():    print("Welcome to the Python Cafe!")    print("-" * 27)welcome()# A function can receive a value (a parameter)...def serve(drink):    print(f"One {drink}, coming right up.")serve("latte")serve("hot chocolate")# ...and give back a result with return.def with_vat(price):    return price * 1.21print(f"A 2.50 tea costs {with_vat(2.50):.2f} with VAT.")# The result can be stored and used like any other value.total = with_vat(3.00) + with_vat(1.80)print(f"Coffee and a croissant: {total:.2f}")# A function can call other functions.def receipt_line(drink, price):    print(f"{drink:<14}{with_vat(price):>6.2f}")receipt_line("Cappuccino", 2.80)receipt_line("Orange juice", 3.20)

Output · python3 main.py

Welcome to the Python Cafe!
---------------------------
One latte, coming right up.
One hot chocolate, coming right up.
A 2.50 tea costs 3.02 with VAT.
Coffee and a croissant: 5.81
Cappuccino      3.39
Orange juice    3.87

Key points

  • def name(parameters): creates a function.
  • The function only runs when you call it: name(...).
  • Parameters receive the values of the call.
  • return sends back a result you can store or use.

Exercise

Write a to_fahrenheit(celsius) function that returns celsius * 9 / 5 + 32 and use it in a for loop to convert 0, 20, 37 and 100 degrees.