Functions and ErrorsLesson 13 of 1915 min
Defining Functions
Name a piece of logic once, then use it everywhere — with parameters and return values.
By the end you will be able to
- Define a function with def and call it
- Distinguish parameters from arguments
- Return a value rather than printing it
A function is a named block of code you can run on demand. Defining one does not run it — the body only executes when you call it.
Defined, but nothing has run yet.
Hello!
Welcome to CodeNest.
Hello!
Welcome to CodeNest.
— expected output; press Run to execute it yourselfParameters and arguments
A parameter is the name in the definition. An argument is the actual value you pass in when calling. Parameters make a function general instead of hard-coded.
Hello, Ada!
Good morning, Bob!
Hi, Cleo!
— expected output; press Run to execute it yourselfreturn: handing a value back
print shows something to a human. return hands a value back to the code that called the function, so it can be stored, compared, or passed on. A function that only prints cannot be reused in a calculation.
return also exits the function immediately.
5
captured: None
captured: 5
7
— expected output; press Run to execute it yourselfReturning several values, and early returns
Returning a tuple lets a function hand back more than one thing. And returning early on the simple cases keeps the main path un-nested.
low=4 high=42 mean=18.00
(0, 0, 0)
— expected output; press Run to execute it yourselfDocstrings
A string on the first line of a function documents it, and help() will show it. Worth writing for anything non-obvious.
212.0
Convert a Celsius temperature to Fahrenheit.
— expected output; press Run to execute it yourselfExercise
Write apply_discount(price, percent=10) that returns the price after subtracting the given percentage, rounded to 2 decimal places. apply_discount(50) should return 45.0.
Press Run to execute this code.