Skip to content
CodeNest

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.

Python
Output
Defined, but nothing has run yet.
Hello!
Welcome to CodeNest.
Hello!
Welcome to CodeNest.
— expected output; press Run to execute it yourself

Parameters 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.

Python
Output
Hello, Ada!
Good morning, Bob!
Hi, Cleo!
— expected output; press Run to execute it yourself

return: 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.

Python
Output
5
captured: None
captured: 5
7
— expected output; press Run to execute it yourself

Returning 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.

Python
Output
low=4 high=42 mean=18.00
(0, 0, 0)
— expected output; press Run to execute it yourself

Docstrings

A string on the first line of a function documents it, and help() will show it. Worth writing for anything non-obvious.

Python
Output
212.0
Convert a Celsius temperature to Fahrenheit.
— expected output; press Run to execute it yourself

Exercise

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.

Python
Output

Press Run to execute this code.

Check your understanding

0/3 answered
  1. 1.What does a function return if it has no return statement?
  2. 2.In def greet(name):, what is name?
  3. 3.Why prefer return over print inside a reusable function?