Python, like many programming languages, has functions. A function is a block of code you can call to run that code. Code that's inside a function isn't executed until you call the function.
Python comes with many built-in functions, but you can also define your own functions with the
Pretty much every Python Morsels exercise will involve writing at least one function.
Python's functions often have a lot of "wait I didn't know that" features.
You can specify default arguments when defining a function, you can use keyword arguments when calling a function, you can capture any number of arguments given to your function using the
** operators, and you can define "keyword-only arguments" using
Python has first-class functions, which means functions are just another object in Python: our functions can be passed into or returned from other functions. You can even write a function that creates another function.
A "lambda function" is Python's flavor of an anonymous function. I try to avoid using lambda expressions personally.
We often use the word callable in Python to refer to something which can be called.
A function is a callable but a class is also a callable (you can use parenthesis,
(), to call either one).
We also frequently use the word "function" to refer to classes (and sometimes other callable non-functions).
Almost one-third of the Python built-in functions are actually classes (
enumerate are all classes for example).
You'll also hear the word "method" used in Python. A "method" is a function that lives on a class (see the classes section below).
Recursion is also something we use occasionally in Python, but we typically only use it in a few specific classes of problems (often iterating over arbitrarily nested data structures).
Hello friendly web visitor! 👋
This page is part of Python Morsels, an online Python skill-building service.
The best way to learn is by doing. In the case of Python that means writing Python code. If you'd like to improve your Python skills every week, try out Python Morsels by entering your email below to create an account.
Python Morsels topics pages are free and the first month's worth of exercises is free as well. You don't need to enter payment details to sign up.
You can find explanations of many other Python topics by signing up below.