Skip to main content

Python Functions

Understanding how Python passes arguments, manages variables/scopes, and executes functions behind the scenes will help you write more predictable, efficient, and bug-free code.

Topics Covered

In this module, you’ll learn:
  1. Function Arguments: Positional vs Keyword argument passing
  2. Print formatting: sep and end parameters
  3. Packing and Unpacking: * and ** operators, *args, and **kwargs
  4. Mutable Default Arguments Pitfall
  5. Variable Scope and resolution (LEGB rule, global and nonlocal keywords)
Try Yourself: 💻 VS Code | 🚀 Colab | 📥 Download
Verify Solutions: 💻 VS Code | 🚀 Colab | 📥 Download

Function Arguments: Positional and Keyword passing

When calling functions, you can pass arguments in two ways:
  1. Positional Arguments: Matched by position (order).
  2. Keyword Arguments: Matched by parameter name.
Output ?
All positional arguments must appear before keyword arguments.
Output ?

Exercise 1

Create a function divide(a, b) and call it using keyword arguments such that b is passed first.

The print() function contains two special parameters that format how text is displayed:
  • sep: Specifies the separator character placed between multiple arguments (defaults to a space " ").
  • end: Specifies what character is printed at the very end of the output (defaults to a newline "\n").
Output

Exercise 1

Print three words separated by a hyphen - using sep.

Exercise 2

Print numbers from 1 to 5 on the same line separated by spaces using a for loop and the end argument.

Packing and Unpacking

Python provides the * and ** operators to pack or unpack values during function calls and parameter definitions.

Packing with *args and **kwargs

  • *args (Positional Packing): Collects extra positional arguments into a tuple.
  • **kwargs (Keyword Packing): Collects extra keyword arguments into a dictionary.
Output

Unpacking arguments

You can expand lists/tuples/sets using * and dictionaries using ** while calling functions.
Output ?

Exercise 1

Write a function sum_all(*args) that sums all positional arguments passed to it.

Exercise 2

Explain the difference between func(*list_val) and func(list_val).
  • func(*list_val) unpacks each element of list_val as a separate positional argument.
  • func(list_val) passes the entire list as a single positional argument.

Mutable Default Argument Pitfall

When defining a function, default arguments are evaluated only once when the function is defined, not when it is called. If you use a mutable default argument (like a list or a dictionary) and modify it inside the function, those modifications persist across subsequent calls.
Output

The Clean Solution

Use None as the default value and instantiate a new mutable object inside the function if needed.
Output

Exercise 1

Predict the output of the following code:
Output ?
Because the default dictionary my_dict={} is mutable, modifications persist across subsequent function calls.

Variable Scope

A variable’s scope determines where it can be accessed in a program. Python resolves variables using the LEGB Rule:
  1. Local – Inside the current function.
  2. Enclosing – Inside nested/enclosing functions.
  3. Global – At the top level of the module.
  4. Built-in – Built-in functions and names (e.g., print, len).

Local Scope

Variables defined inside a function belong to the local scope of that function and cannot be accessed outside.
Output ?

Global Scope

Variables defined at the top level of a file are global and can be read from anywhere inside that file.
Output

The global Keyword

To modify a global variable inside a function, you must declare it using the global keyword.
Output

Enclosing Scope and the nonlocal Keyword

When you nest functions, the outer function’s scope is the enclosing scope for the inner function. To modify a variable in the enclosing scope, use nonlocal.
Output

Exercise 1

Predict the output of the following code:
Output ?
The global x statement inside func() makes any assignment to x modify the global variable x.

Exercise 2

Write a nested function where the inner function increments a variable defined in the outer function’s scope by 1 and prints it.

Practice

To reinforce what you’ve learned in this section, practice with the interactive follow-along notebook:

Follow-Along Practice

Practice local and global scope resolution, LEGB rules, sep and end parameters, arguments packing/unpacking, and mutable default arguments.💻 VS Code | 🚀 Colab | 📥 Download

Summary

In this module, you learned how Python manages variables, scopes, function parameters, and execution behind the scenes.

Key Concepts Covered

  • Positional vs Keyword function argument passing
  • print parameters sep and end
  • Packing and Unpacking with * and ** operators
  • The mutable default argument pitfall and its solution
  • LEGB Variable scopes and scope resolution
  • The global and nonlocal keywords