Functions
Programming Languages · Python Functions & Data · 12 min
Name a block of code once, then reuse it as often as you like.
Define it, then call it
A function is a named block of code. def creates it; the indented lines are what it does. Nothing happens until you call it by writing its name with brackets.
def cheer():
print("Hooray!")
cheer()
cheer()
Define a function
say_hithat printsHi!.Call
say_hitwice.
Parameters
A parameter is a name in the brackets that receives a value when the function is called. It lets one function work with different data.
def shout(word):
print(word.upper())
shout("hey") # HEY
Define
greet(name)that printsHello,followed by the name and!.Call
greetwith"Ada", then with"Linus".
return
return hands a value back to whoever called the function, so you can print it, store it or use it in maths.
def double(n):
return n * 2
print(double(21)) # 42
Printing shows a value. Returning gives it back. Most useful functions return.
Define
square(n)that returnsn * n.Print
square(9).
Default values
A parameter can have a default value. If the caller leaves it out, the default is used.
def order(drink="tea"):
return f"One {drink}, please"
print(order()) # One tea, please
print(order("coffee")) # One coffee, please
Define
power(base, exp=2)that returnsbase ** exp.Print
power(5), thenpower(2, 3).
Functions using functions
A function can call another function. That way you build big jobs out of small, tested pieces.
def add_one(n):
return n + 1
def add_two(n):
return add_one(add_one(n))
Define
quadruple(n)that usesdoubletwice to return 4 timesn.Print
quadruple(5).
Put it together: a tip calculator
Build two small functions: one works out the tip, the other adds it to the bill. The tip is 15 percent unless you say otherwise.
total(40) should give 46.0, and total(40, 20) should give 48.0.
Define
tip(bill, percent=15)that returnsbill * percent / 100.Define
total(bill, percent=15)that returns the bill plustip(bill, percent).Print
total(40), thentotal(40, 20).
More in Python Functions & Data
Previous: Loops · Next: Dictionaries