Skip to content

Chapter 4 of 7

Functions

Functions are defined using the def keyword, followed by the function name, parameters in parentheses, and a colon, as in def function_name(parameters):. The indented body contains the function's logic, and you call the function by writing its name followed by arguments, like function_name(args). It is important to distinguish between parameters, which are the variables listed in the function definition, and arguments, which are the actual values passed when calling the function. Keyword arguments can be passed using the name=value syntax.

The return statement, written as return value, exits the function and sends a value back to the caller. Without an explicit return, a function automatically returns None. Default parameters let you assign a default value to a parameter so the caller can omit it: def func(param=default):. This is helpful when a parameter has a common value most callers will want.

For more flexible function signatures, Python supports *args and **kwargs. The *args syntax packs extra positional arguments into a tuple, while **kwargs packs extra keyword arguments into a dictionary. These constructs allow a function to accept any number of arguments without specifying them all in advance.

All chapters
  1. 1Introduction to Python
  2. 2Variables, Types, and Operators
  3. 3Control Flow
  4. 4Functions
  5. 5Data Structures
  6. 6Object-Oriented Programming
  7. 7Modules, Exceptions, and Advanced Features

Drill it

Reading is not remembering. These come from the Python Programming deck:

Q

What is Python?

Python is a high-level, interpreted programming language known for its readability and simplicity. It supports multiple paradigms including procedural, object-o...

Q

Who created Python and when?

Guido van Rossum created Python, with the first version released in 1991. It was named after the British comedy series Monty Python.

Q

What are the key features of Python?

Python features dynamic typing, automatic memory management, extensive standard library, and cross-platform compatibility. It emphasizes code readability with s...

Q

How do you run a Python script from the command line?

Save the code in a file with .py extension, then run python filename.py in the terminal. Use python3 if Python 2 is also installed.