Local Variable Shadowing a Global One

Medium ⏱ 12 min 51% acceptance ★★★★★ 4.8
A module-level variable tax_rate = 0.05 already exists. Write a function price_with_local_tax(amount, tax_rate) that takes its OWN tax_rate parameter (shadowing the global one inside the function body) and returns amount + amount * tax_rate, using only the local parameter, never the global. Then write a second function price_with_global_tax(amount) that has no tax_rate parameter and instead reads the module-level tax_rate directly, returning the same formula. This demonstrates that a local parameter of the same name shadows an outer/global variable within its own function.

Examples

Example 1
Input
price_with_local_tax(100, 0.2)
Output
120.0
Explanation

Uses the passed-in tax_rate 0.2, ignoring the global 0.05.

Example 2
Input
price_with_global_tax(100)
Output
105.0
Explanation

No local tax_rate parameter exists, so it falls back to the global 0.05.

Constraints

  • price_with_local_tax must not reference the module-level tax_rate at all.
  • price_with_global_tax must not declare a tax_rate parameter.

Topics

Functionsvariable scope

Companies

WiproTCS

Hints

Hint 1

A parameter name automatically becomes a local variable that shadows any same-named global for the duration of the function.

Hint 2

price_with_global_tax can read the global directly since it is only reading, not reassigning, so no global keyword is needed.

Loading the Python runtime… Run executes your code and shows printed output; Submit checks your function against this problem's examples.