Bitpath

Lesson 2 · Unit 03

Scope and arguments

Local names, defaults and keyword arguments

13 exercisesabout 3 min

What you practise

  • Local names and global names, default and keyword arguments, docstrings, why three small functions beat one long one

Try a question from this lesson

Pick one

The function gives a value to a name that already exists outside it. What does the last line show?

Python
x = 1

def change():
    x = 99

change()
print(x)

The ideas

Concept cards are short on purpose. In the app they appear between questions, after you have met the idea.

Concept

Local and global names

A name made inside a function is local: it exists only while that call is running. Parameters are local too.

A name made outside every function is global.

A function can read a global name. But giving a name a value inside a function makes a new local name, and the global one is left alone.

Python
rate = 2              # global

def cost(n):
    amount = n * rate # amount is local
    return amount

print(cost(5))        # 10

Concept

Defaults and keywords

A parameter can have a default value, written with = in the def line. It is used when the call leaves that argument out.

A call can also name its arguments. Then their order does not matter.

Python
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Ada")         # Hello, Ada!
greet("Ada", "Hi")   # Hi, Ada!
greet(greeting="Hey", name="Bo")
# Hey, Bo!

10 more exercises in the app

  • 3× multiple choice
  • 3× type the answer
  • 1× fill the blanks
  • 1× true or false
  • 1× match the pairs
  • 1× order the lines

Bitpath is an iOS app in development. Join the waitlist and you get one email when it is ready to try.

One email when Bitpath is ready to try. Nothing else. Privacy