Shadowing and Parameters

A function can read a global variable. But when it assigns to a name that also exists globally, it creates a new local variable that shadows the global one. The global is untouched.

EXAMPLE
loading editor…
YOUR TURN
Your turn → The global stayed 10. In the JavaScript tab, remove the `let` inside change() and run it: the function now changes the global. In Python, add `global count` as the first line of change() to do the same.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Parameters are local too. When you pass a value into a function, the parameter is a fresh local name holding a copy of that value. Reassigning the parameter inside the function does not touch the caller's variable.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Write a function add_tax(price) that returns the price with 7% tax added. Call it, store the result, and print both the original price and the result.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ The exception worth knowing

Lists and dictionaries behave differently. Passing one in does not copy it, it passes a reference to the same object, so changing its contents inside a function DOES affect the caller. Numbers and strings are copied, collections are shared. Module 18 works through this properly.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Block Scope and Lifetime →
← Back