SyntaxPilot
Courses/Python/Lesson 14

Python · Lesson 14 of 40 · 12 min

Scope, *args and **kwargs

queued

These are the notes for Python episode 14. Last episode we invented functions. Today two new problems show up. A variable made inside a function seems to vanish, and Raju's running total throws a strange UnboundLocalError. And our functions accept a fixed number of inputs, while real orders come in every size, with any number of special requests. You will learn local and global scope, the LEGB rule, shadowing, the global keyword (and why parameters plus return is better), *args, **kwargs, unpacking with * and ** in a call, keyword-only parameters, and the full parameter order. Every example below runs as-is in the SyntaxPilot compiler, with its real output from Python 3.13.

Variables that vanish

Raju's sell function stores the price in a variable called sale and prints it. After calling it, we print sale outside the function:

def sell(price):
    sale = price
    print("Sold for", sale)

sell(10)
print(sale)

Output:

Sold for 10
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print(sale)
          ^^^^
NameError: name 'sale' is not defined. Did you mean: 'False'?

Inside, it worked. Outside: NameError. Why: sale was created inside the function, and it disappeared when the function finished. (The "Did you mean" part is just Python guessing a similarly spelled name; ignore it.) If you need a value outside a function, return it.

UnboundLocalError: the total that is "right there"

So Raju tries the other way: keep the day's total outside the function, starting at zero, and add each sale to it inside.

total = 0

def sell(price):
    total = total + price
    print("Sold for", price)

sell(10)

Output:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    sell(10)
    ~~~~^^^^
  File "main.py", line 4, in sell
    total = total + price
            ^^^^^
UnboundLocalError: cannot access local variable 'total' where it is not associated with a value

A confusing message: total is right there on line 1! Here is what actually happened:

total = 0                 # global
def sell(price):
    total = total + price  # assigns → total is LOCAL
  • Before running sell, Python sees total = ... inside it, and decides: total is a local variable of this function, for the whole function, not just from that line onwards.
  • The right side, total + price, then tries to read that local total, which has no value yet.
  • Unbound means "not tied to any value". Hence the error.
  • Reading a global without assigning to it is fine (next section).

Local vs global: a room inside a house

In a house In Python
Your room's whiteboard: only seen inside the room, wiped when you leave a local variable: made inside a function, gone when the function ends
The fridge note: everyone in the house can read it a global variable: made outside all functions, seen from every function
Writing "total" on your own whiteboard: a new note, same word total = ... inside a function makes a new local name, even if a global total exists

The scope of a name is the part of the program where that name can be seen.

Reading a global just works

shop = "Raju's Chai"

def receipt(price):
    print(shop, "- Rs", price)

receipt(10)

Output:

Raju's Chai - Rs 10

receipt never assigns to shop, so Python doesn't find it locally and looks it up in the file (the global scope).

Shadowing: same name, two variables

Now assign without reading first:

total = 0

def sell(price):
    total = price
    print("inside:", total)

sell(10)
print("outside:", total)

Output:

inside: 10
outside: 0

Inside 10, outside 0. These are two different variables with the same name. The local total hides, or shadows, the global one, and the global never changed. No error, which is exactly why shadowing bugs are sneaky.

The LEGB rule

When Python meets a name, it searches four places, in this order:

Letter Scope Where Example
L Local inside the function you're in sale in sell
E Enclosing a function around this function outer's x, seen from inner
G Global the whole file shop, total at the top
B Built-in names Python gives you for free print, len, sum

It stops at the first place it finds the name. If it's in none of them: NameError.

x = "global"

def outer():
    x = "enclosing"
    def inner():
        print(x)
    inner()

outer()
print(len("chai"))

Output:

enclosing
4
  • inner has no x of its own (L), so Python checks the enclosing function outer (E) and finds "enclosing". It never reaches the global x.
  • len isn't local, enclosing or global, so it's found in the built-ins (B).
  • Yes, a def can sit inside another def: inner exists only while outer runs.

The global keyword, and a better way

One fix for the daily total is the global keyword. global total tells Python: inside sell, total means the fridge note, not a new local.

total = 0

def sell(price):
    global total
    total = total + price

sell(10)
sell(15)
print("Today:", total)

Output:

Today: 25

It works. But now any function anywhere can change total, and when it's wrong you have to search the whole program for who changed it. The cleaner way is what we learned last episode: pass the total in, return the new total, and store it.

def sell(total, price):
    return total + price

total = 0
total = sell(total, 10)
total = sell(total, 15)
print("Today:", total)

Output:

Today: 25

Same answer, no hidden changes. Everything the function uses comes in through the brackets (parameters), and everything it changes goes out through return. Use global rarely.

*args: any number of values

Raju's add function adds two prices. But the next customer orders three things. Or five. Or one.

def add(a, b):
    return a + b

print(add(10, 15))
print(add(10, 15, 20))

Output:

25
Traceback (most recent call last):
  File "main.py", line 5, in <module>
    print(add(10, 15, 20))
          ~~~^^^^^^^^^^^^
TypeError: add() takes 2 positional arguments but 3 were given

Two slots, three values. One workaround is to pass a list:

def add(prices):
    return sum(prices)

print(add([10, 15, 20]))

Output:

45

It works, but every caller now has to remember the square brackets, even for a single item. The real fix is a star before the parameter name. It means: collect all the (remaining) positional arguments into one tuple, like a serving tray that holds however many items come.

def add(*prices):
    print(prices)
    return sum(prices)

print(add(10, 15))
print(add(10, 15, 20, 25))
print(add())

Output:

(10, 15)
25
(10, 15, 20, 25)
70
()
0

Two prices became a tuple of two, four became a tuple of four, and nothing became an empty tuple with sum 0. One function, any number of values. That's *args. The name args is just a habit (short for "arguments"); it's the * that matters, so *prices and *items are fine.

Normal parameters can come first. bill takes a customer, then any number of item prices:

def bill(customer, *items):
    print(customer, "ordered", len(items), "items")
    return sum(items)

print(bill("Asha", 10, 15, 20))

Output:

Asha ordered 3 items
45

The first argument filled customer, and the star collected the rest.

**kwargs: named extras

Every order has a main thing (one chai), and customers add named requests: sugar less, milk extra, no ice. Different customers, different requests, any number of them.

def order(item):
    print("One", item)

order("chai", sugar="less")

Output:

Traceback (most recent call last):
  File "main.py", line 4, in <module>
    order("chai", sugar="less")
    ~~~~~^^^^^^^^^^^^^^^^^^^^^^
TypeError: order() got an unexpected keyword argument 'sugar'

There's no parameter called sugar to receive it. Raju writes requests as name → detail, and we know that shape: a dictionary. Two stars collect every extra keyword argument into a dict:

def order(item, **options):
    print(options)
    print("One", item)
    for name, value in options.items():
        print(" ", name, "=", value)

order("chai", sugar="less", milk="extra")
order("lassi")

Output:

{'sugar': 'less', 'milk': 'extra'}
One chai
  sugar = less
  milk = extra
{}
One lassi

Sugar and milk arrived as a dictionary (keyword names become string keys), and lassi with no requests got an empty one. That's **kwargs, short for keyword arguments.

*args **kwargs
Collects extra positional arguments extra keyword (named) arguments
Arrives as a tuple a dict
Call example add(10, 15, 20) order("chai", sugar="less")
Nothing passed () {}

Unpacking with * and ** in a call

The stars also work the other way, when calling. *prices spreads a list into separate positional arguments; **extras spreads a dictionary into keyword arguments.

def bill(a, b, c):
    return a + b + c

prices = [10, 15, 20]
print(bill(*prices))

extras = {"sugar": "less", "milk": "extra"}
def order(item, **options):
    print(item, options)
order("chai", **extras)

Output:

45
chai {'sugar': 'less', 'milk': 'extra'}

10, 15 and 20 went into a, b and c. And the dictionary became sugar="less", milk="extra". Same symbols, opposite directions:

  • In a def, * and ** collect (packing).
  • In a call, * and ** spread (unpacking).

Keyword-only parameters (and a silent trap)

bill takes any number of items, then gst defaulting to 5. Three calls: default GST, gst=12 by name, and 12 without a name.

def bill(*items, gst=5):
    total = sum(items)
    return total + total * gst / 100

print(bill(10, 15, 20))
print(bill(10, 15, 20, gst=12))
print(bill(10, 15, 20, 12))

Output:

47.25
50.4
59.85

The first two are right. The third is 59.85: the 12 was swallowed by *items as a fourth price (57 + 5% GST). No error, just a wrong bill.

Any parameter after *args can only be set by name. It's called a keyword-only parameter. That's a feature: always write gst=12, and it can never be mixed up with a price.

The full parameter order

The order of parameters in a def is fixed:

def f(a, b=1, *args, k=5, **kwargs):
a, b=1 *args k=5 **kwargs
normal (positional) and defaults a tuple of extra positionals keyword-only a dict of extra keywords, always last

Put ** first and * after?

def f(**options, *items):
    pass

Output:

  File "main.py", line 1
    def f(**options, *items):
                     ^
SyntaxError: arguments cannot follow var-keyword argument

**kwargs ("var-keyword argument") always comes last. Nothing may follow it.

Common mistakes

Mistake What you see Why Fix
print(sale) where sale was made in a function NameError: name 'sale' is not defined locals vanish when the function ends return it
total = total + price inside a function, total is global UnboundLocalError: cannot access local variable 'total' where it is not associated with a value assigning makes total local for the whole function pass it in and return it
total = price inside, expecting the global to change no error, global unchanged the local shadows the global return the value
global everywhere no error, hard-to-find bugs any function can change the value parameters in, return out
add(10, 15, 20) with def add(a, b) TypeError: add() takes 2 positional arguments but 3 were given fixed number of slots def add(*prices)
order("chai", sugar="less") with def order(item) TypeError: order() got an unexpected keyword argument 'sugar' no parameter named sugar def order(item, **options)
bill(10, 15, 20, 12) meaning GST 12 no error, 59.85 (wrong bill) 12 was collected by *items bill(10, 15, 20, gst=12)
def f(**options, *items) SyntaxError: arguments cannot follow var-keyword argument **kwargs must be last def f(*items, **options)
order(sugar="less", "chai") SyntaxError: positional argument follows keyword argument in a call, positionals come first order("chai", sugar="less")
sum = 10 then sum([1, 2]) TypeError: 'int' object is not callable your global sum shadows the built-in (G before B) never name variables sum, len, list, print

Mini project: a flexible order slip

slip(customer, *items, gst=5, **notes): a customer name, any number of items as (name, price) tuples, a keyword-only gst, and any number of special-request notes. Print the slip and return the amount to pay, with GST.

# Mini project: flexible order slip
def slip(customer, *items, gst=5, **notes):
    total = 0
    print("Customer:", customer)
    for name, price in items:
        print(f"  {name:10} Rs {price}")
        total += price
    for k, v in notes.items():
        print(f"  note: {k} = {v}")
    return total + total * gst / 100

pay = slip("Asha", ("chai", 10), ("samosa", 15), sugar="less")
print("Pay: Rs", pay)

Output:

Customer: Asha
  chai       Rs 10
  samosa     Rs 15
  note: sugar = less
Pay: Rs 26.25
  • total is a local variable: a fresh 0 for every slip, and no global needed because the answer goes out by return.
  • items is a tuple of tuples, so for name, price in items unpacks each pair (episode 11).
  • notes is a dict, looped with .items() (episode 12).

Extend it: a second customer with three items, GST 12 and two notes. The function doesn't change at all.

Solution
def slip(customer, *items, gst=5, **notes):
    total = 0
    print("Customer:", customer)
    for name, price in items:
        print(f"  {name:10} Rs {price}")
        total += price
    for k, v in notes.items():
        print(f"  note: {k} = {v}")
    return total + total * gst / 100

pay = slip("Ravi", ("vada pav", 20), ("lassi", 25), ("chai", 10), gst=12, sugar="none", parcel="yes")
print("Pay: Rs", pay)

Output:

Customer: Ravi
  vada pav   Rs 20
  lassi      Rs 25
  chai       Rs 10
  note: sugar = none
  note: parcel = yes
Pay: Rs 61.6

Practice

1. Write average(*marks) that works for any number of marks, and returns 0 when no marks are given.

Solution
def average(*marks):
    if len(marks) == 0:
        return 0
    return sum(marks) / len(marks)

print(average(80, 90, 70))
print(average(55))
print(average())

Output:

80.0
55.0
0

Without the len(marks) == 0 check, average() would divide by zero.

2. Write profile(name, **details) that prints every detail on its own line.

Solution
def profile(name, **details):
    print("Name:", name)
    for key, value in details.items():
        print(f"  {key}: {value}")

profile("Asha", city="Pune", age=21, course="Python")
profile("Ravi")

Output:

Name: Asha
  city: Pune
  age: 21
  course: Python
Name: Ravi

3. Find the bug, then fix it without global:

count = 0

def visit():
    count = count + 1

visit()
print(count)
Solution

Output of the buggy version:

Traceback (most recent call last):
  File "main.py", line 6, in <module>
    visit()
    ~~~~~^^
  File "main.py", line 4, in visit
    count = count + 1
            ^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

count = ... inside visit makes count local, and the right side reads it before it has a value. Pass it in and return it:

def visit(count):
    return count + 1

count = 0
count = visit(count)
count = visit(count)
print(count)

Output:

2

4. Call a 3-parameter function with a list using *. What happens if the list has only two items?

Solution
def bill(a, b, c):
    return a + b + c

prices = [10, 15, 20]
print(bill(*prices))
print(bill(*[10, 15]))

Output:

45
Traceback (most recent call last):
  File "main.py", line 6, in <module>
    print(bill(*[10, 15]))
          ~~~~^^^^^^^^^^^
TypeError: bill() missing 1 required positional argument: 'c'

Unpacking only spreads the values; the function still needs exactly three.

5. Write biggest(*numbers) with a loop (no max).

Solution
def biggest(*numbers):
    best = numbers[0]
    for n in numbers:
        if n > best:
            best = n
    return best

print(biggest(4, 19, 7))
print(biggest(-3, -8))

Output:

19
-3

Starting best at numbers[0] (not 0) makes it work for negative numbers too.

6. Write ticket(*names, seat="any") that prints a ticket line for every passenger, all with the same seat type.

Solution
def ticket(*names, seat="any"):
    for n in names:
        print(n, "-", seat)

ticket("Asha", "Ravi", seat="window")

Output:

Asha - window
Ravi - window

seat comes after *names, so it's keyword-only: ticket("Asha", "Ravi", "window") would print three passengers with seat any.

7. Write describe(*args, **kwargs) that shows exactly what it received.

Solution
def describe(*args, **kwargs):
    print("positional:", args)
    print("keyword:", kwargs)

describe(1, "two", 3.0, mode="fast", debug=True)

Output:

positional: (1, 'two', 3.0)
keyword: {'mode': 'fast', 'debug': True}

Quick quiz

1. From the video:

def f(a, *b, **c):
    return len(b) + len(c)

print(f(1, 2, 3, x=4))

What does it print? 4, 3, 2, or TypeError?

Answer

3. a = 1, b = (2, 3), c = {'x': 4}. len(b) + len(c) = 2 + 1 = 3.

2.

x = 5

def show():
    x = 10
    print(x)

show()
print(x)
Answer
10
5

The x = 10 inside show is a new local that shadows the global; the global stays 5.

3.

def f(*args):
    return args

print(f([1, 2, 3]))
print(f(*[1, 2, 3]))
Answer
([1, 2, 3],)
(1, 2, 3)

Without *, the whole list is one argument, so args is a tuple holding one list. With *, the list is spread into three arguments.

4.

def f(a, b=2, *args, c=3, **kw):
    print(a, b, args, c, kw)

f(1, 4, 5, 6, d=7)
Answer
1 4 (5, 6) 3 {'d': 7}

1 and 4 fill a and b, 5, 6 go to args, c keeps its default because it's keyword-only, and d=7 lands in kw.

Interview questions

  1. What is scope? The region of a program where a name can be seen. Python has local (function), enclosing (outer function), global (file) and built-in scopes.
  2. What is the LEGB rule? The order Python searches for a name: Local, Enclosing, Global, Built-in. It uses the first match; if none, NameError.
  3. Why does UnboundLocalError happen? If a function assigns to a name anywhere in its body, that name is local for the whole function. Reading it before the assignment gives UnboundLocalError, even if a global of the same name exists.
  4. Why avoid global? Any function can change the value, so bugs are hard to trace, and functions become harder to test and reuse. Pass values in as parameters and send results out with return.
  5. Difference between *args and **kwargs? *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict. The names are conventions; the stars matter.
  6. What do * and ** do in a function call? They unpack: * spreads a list or tuple into positional arguments, ** spreads a dict into keyword arguments.
  7. What is a keyword-only parameter? A parameter after *args (in a def); it can only be passed by name, like gst=12, so it can't be swallowed as an extra positional value.
  8. What is the correct parameter order? Normal/positional, defaults, *args, keyword-only, **kwargs last. **kwargs anywhere but last is a SyntaxError.

Bonus (beyond the video): nonlocal

global reaches the file's scope. To assign to a variable of the enclosing function, use nonlocal. Without it, the inner function hits the same UnboundLocalError:

def counter():
    count = 0
    def add_one():
        count = count + 1
    add_one()

counter()

Output:

Traceback (most recent call last):
  File "main.py", line 7, in <module>
    counter()
    ~~~~~~~^^
  File "main.py", line 5, in counter
    add_one()
    ~~~~~~~^^
  File "main.py", line 4, in add_one
    count = count + 1
            ^^^^^
UnboundLocalError: cannot access local variable 'count' where it is not associated with a value

With nonlocal:

def counter():
    count = 0
    def add_one():
        nonlocal count
        count = count + 1
        print("count is", count)
    add_one()
    add_one()

counter()

Output:

count is 1
count is 2

Like global, use it sparingly; returning values is usually clearer.

Glossary

Term Meaning Example
Scope The part of a program where a name can be seen locals only inside their function
Local variable Made inside a function; gone when the function ends sale in sell
Global variable Made outside all functions; readable from every function shop = "Raju's Chai"
Enclosing scope The scope of a function that contains another function outer's x, seen by inner
Built-in scope Names Python provides for free print, len, sum
LEGB rule The lookup order: Local → Enclosing → Global → Built-in inner finds "enclosing"
Nested function A def inside another def inner inside outer
Shadowing A name in an inner scope hiding the same name in an outer one local total = price
global keyword Makes a name inside a function refer to the global variable global total
nonlocal keyword (bonus) Makes a name refer to the enclosing function's variable nonlocal count
NameError Using a name that isn't found in any scope print(sale) outside sell
UnboundLocalError Reading a local variable before it has a value total = total + price
Unbound Not tied to any value yet the local total
Parameter A name in the def that receives a value price in def sell(price)
Argument The value passed in a call 10 in sell(10)
Positional argument An argument matched by its position add(10, 15)
Keyword argument An argument passed by name gst=12
*args Collects extra positional arguments into a tuple def add(*prices)
**kwargs Collects extra keyword arguments into a dict def order(item, **options)
Var-keyword argument Python's name for the **kwargs parameter in the SyntaxError message
Packing * / ** in a def collecting many values into one tuple / dict *prices → (10, 15)
Unpacking * / ** in a call spreading a list / dict into arguments bill(*prices)
Keyword-only parameter A parameter after *args; can only be passed by name gst in def bill(*items, gst=5)
Default value The value a parameter uses when none is passed gst=5
Parameter order normal, defaults, *args, keyword-only, **kwargs def f(a, b=1, *args, k=5, **kwargs)

Summary

  • Variables made inside a function are local: they vanish when it ends (NameError outside). Variables made outside all functions are global.
  • Python finds names in LEGB order: Local, Enclosing, Global, Built-in.
  • Reading a global inside a function works; assigning makes a new local for the whole function, which shadows the global or causes UnboundLocalError.
  • global works but hides changes; prefer parameters in, return out.
  • *args collects extra positional arguments into a tuple; **kwargs collects extra keyword arguments into a dict.
  • In a call, * and ** spread a list and a dict into arguments.
  • Parameters after *args are keyword-only; bill(10, 15, 20, 12) silently treats 12 as a price.
  • Order: normal, defaults, *args, keyword-only, **kwargs last (otherwise SyntaxError).

Next episode: recursion. What if a function calls itself? Folders inside folders inside folders, and loops can't tell how deep they go.