Skip to content
KALANBLON
Show contents

Chapter 2 of 7 · 20 min

Scope, default parameters and pitfalls

By the end of this chapter, you'll be able to

  • Tell a local variable from a global variable
  • Give a parameter a default value
  • Call a function with keyword arguments
  • Avoid the mutable default value pitfall

Local or global?

A variable created inside a function is local: it only exists during the call. A variable created outside any function is global. A function can read a global variable, but an assignment inside the function creates a new local variable with the same name.

The program displays 10 50.

Step 7 of 7
Text description of the animation
  1. Two variables will be called score. They don't live in the same place.
  2. Line 1: score is 10, in the global space.
  3. Line 7: we call bonus().
  4. Inside the function, score = 50 creates a local variable. The global one isn't touched.
  5. The function returns 50 and its local memory disappears.
  6. Back in the global space: score is still 10, result is 50.
  7. The program displays 10 50.
score = 10

def bonus():
    score = 50
    return score

result = bonus()
print(score, result)
10 50

The right habit: a function receives what it needs through its parameters and passes its result back with return. It avoids depending on global variables, which makes it easy to test and reuse.

Default values and keyword arguments

A parameter can have a default value, used when the argument is left out. When calling, you can also name the arguments, which makes the code readable and lets you change their order:

def greet(name, greeting="Hello", punctuation="!"):
    return f"{greeting} {name}{punctuation}"

print(greet("Leila"))
print(greet("Tomás", greeting="Hola"))
print(greet(punctuation=" :)", name="Yuki"))
Hello Leila!
Hola Tomás!
Hello Yuki :)

f"..." is an f-string: the expressions between curly braces are replaced by their value. It's the most readable way to build a text in Python.

Parameters with a default value come after those without one, otherwise Python raises a SyntaxError.

Your turn

Mini-lab: price with a discountPython 3.13

Output

Click “Run”: Python will load in your browser (about 10 MB the first time).

Your code runs in your browser, isolated from the page. · Ctrl/⌘ + Enter to run · Esc then Tab to leave the editor

Worked exercise

Worked exercise: formatting a duration

Write a function format_duration(minutes, separator=" h ") that turns a number of minutes into text: format_duration(135) returns "2 h 15", and format_duration(135, ":") returns "2:15". The minutes must always be written with two digits ("1 h 05").

Hint 1
minutes // 60 gives the whole hours, minutes % 60 the remainder.
Hint 2
In an f-string, {m:02d} writes an integer with two digits, adding a leading zero if needed.
Show the solution and common mistakes
def format_duration(minutes, separator=" h "):
    h = minutes // 60
    m = minutes % 60
    return f"{h}{separator}{m:02d}"

print(format_duration(135))
print(format_duration(135, ":"))
print(format_duration(65))
2 h 15
2:15
1 h 05

Common mistakes:

  • Using / instead of //: 135 / 60 gives 2.25, not 2.
  • Putting separator=" h " before minutes in the definition: a parameter without a default value can't follow one that has one.

Summary

  1. 1A variable created inside a function is local and disappears when the call ends.
  2. 2An assignment inside a function doesn't change the global variable with the same name.
  3. 3A parameter can have a default value; arguments can be named.
  4. 4Never use a list or a dictionary as a default value: use None instead.

Your progress is saved on this device. Create a free account to keep your progress on all your devices.