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:- Function Arguments: Positional vs Keyword argument passing
- Print formatting:
sepandendparameters - Packing and Unpacking:
*and**operators,*args, and**kwargs - Mutable Default Arguments Pitfall
- Variable Scope and resolution (LEGB rule,
globalandnonlocalkeywords)
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:- Positional Arguments: Matched by position (order).
- Keyword Arguments: Matched by parameter name.
Show Output
Show Output
Show Output
Show Output
Exercise 1
Create a functiondivide(a, b) and call it using keyword arguments such that b is passed first.
Solution
Solution
Print Formatting Parameters: sep and end
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").
Show Output
Show Output
Exercise 1
Print three words separated by a hyphen- using sep.
Solution
Solution
Exercise 2
Print numbers from1 to 5 on the same line separated by spaces using a for loop and the end argument.
Solution
Solution
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.
Show Output
Show Output
Unpacking arguments
You can expand lists/tuples/sets using* and dictionaries using ** while calling functions.
Show Output
Show Output
Exercise 1
Write a functionsum_all(*args) that sums all positional arguments passed to it.
Solution
Solution
Exercise 2
Explain the difference betweenfunc(*list_val) and func(list_val).
Solution
Solution
func(*list_val)unpacks each element oflist_valas 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.Show Output
Show Output
The Clean Solution
UseNone as the default value and instantiate a new mutable object inside the function if needed.
Show Output
Show Output
Exercise 1
Predict the output of the following code:Show Output
Show Output
Solution
Solution
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:- Local – Inside the current function.
- Enclosing – Inside nested/enclosing functions.
- Global – At the top level of the module.
- 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.Show Output
Show Output
Global Scope
Variables defined at the top level of a file are global and can be read from anywhere inside that file.Show Output
Show Output
The global Keyword
To modify a global variable inside a function, you must declare it using the global keyword.
Show Output
Show 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.
Show Output
Show Output
Exercise 1
Predict the output of the following code:Solution
Solution
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 by1 and prints it.
Solution
Solution
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
sepandend - Packing and Unpacking with
*and**operators - The mutable default argument pitfall and its solution
- LEGB Variable scopes and scope resolution
- The
globalandnonlocalkeywords