Module 05 · Lesson 02
Positional & Keyword Arguments
Make functions flexible: pass arguments by position or by name, give parameters default values, avoid the shared default list trap, and accept any number of arguments with *args and **kwargs.
- About 8 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Position or name
- Default values
- Any number of values
- Watch defaults fill gaps
Ways to hand values in
You can pass values by position, by name, rely on defaults, or accept any number of them.
Positional
describe("cat", 3)fills the parameters in order.Keyword
describe(age=3, pet="cat")names each one, so the order does not matter.Defaults
def tea(sugar=0):means sugar is 0 unless the caller says otherwise.Any number
*argscollects extra values into a tuple;**kwargscollects extra names into a dictionary.
You already use these
Built-in functions lean on keyword arguments and defaults all the time.
- print()
sep=andend=are keyword arguments with defaults: a space and a new line. - sorted()
sorted(scores, reverse=True)flips the order with one named setting. - Game settings
start_game(level=1, sound=True)works with no arguments and lets players change one. - max() and min()They take any number of values, just like a function with
*args.
A parameter with a default
This first line has a required parameter and an optional one. Tap each part to see its job.
Part 1 of 4
required:No default, so every call must give a value: greet("Ana").
Pass values every way
Pick an example, change it, then press Run. Say what you expect to see before you press.
Example 1 of 6By name
Keyword arguments can come in any order.
Your turn: Call it once more with the values swapped by position. What goes wrong?
def describe(pet, age):
print(f"A {age} year old {pet}")
describe("cat", 3)
describe(age=5, pet="dog")Press Run to see what it prints.Watch defaults fill the gaps
Press Step to run one line at a time. Watch which values come from the call and which from the defaults.
Ready. Press Step to run the first line.
- def ticket(film, seats=1, snack="none"):
- return f"{film} x{seats}, snack: {snack}"
- first = ticket("Space Cats")
- second = ticket("Robots", 3, snack="popcorn")
- print(first)
- print(second)
Output so far
Nothing printed yet.
What Python does
Python reads the program from the top. Nothing has run yet.
Names
None yet.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Question 1 of 6
1.Using a default: what prints?
def f(a, b=2):
return a * b
print(f(5))0 of 6 answered
Common argument misconceptions
Each card is something beginners often believe. Tap it to see what Python really does.
Misconception 1 of 4
Notes
Everything above, in words. Open it when you want the full explanation.
Read the notesNotesOpenClose
Syntax
The general shape of the statements in this lesson.
f(1, 2) f(a=1, b=2) f(1, b=2) # positional first def f(a, b=10): # default def f(a, items=None): items = [] if items is None else items def f(*args): # args is a tuple def f(**kwargs): # kwargs is a dictionary def f(a, *, flag=False): # keyword-only after * f(*my_list) f(**my_dict) # unpack into a call
Press Run to see what it prints.Worked examples
Read the problem, run the code, then read why it works.
Example 1 of 2
A flexible receipt line
Write a function that formats a receipt line with a default currency and width, then call it in several ways.
def line(item, price, currency="GBP", width=12):
return f"{item:<{width}}{price:>7.2f} {currency}"
print(line("Tea", 2.5))
print(line("Croissant", 3.2, width=14))
print(line(price=9.99, item="Lunch", currency="EUR"))Press Run to see what it prints.Predict first
How it works(open after your guess)
Common pitfalls
Mistakes people make with this topic, and what to write instead.
Pitfall 1 of 3
A list as a default value
Spot the bug
Can you see what is wrong? Run it to watch it go wrong, then open the fix.
def log(msg, history=[]):
history.append(msg)
return history
log("a")
print(log("b"))Press Run to see what it prints.Show what goes wrong and the fixWhat goes wrong and the fix
In the real world
Where this shows up in software people use every day.
- Food delivery
Building a pizza order
A delivery app builds an order summary from a size, any number of toppings and optional extras given by name.
Why Python fits
*toppingstakes any number of toppings,deliveryis keyword-only with a default, and**extrasaccepts options the function does not need to know about in advance.Pythondef order(size, *toppings, delivery=True, **extras): parts = [f"{size} pizza"] if toppings: parts.append("with " + ", ".join(toppings)) for name, value in extras.items(): parts.append(f"{name}={value}") parts.append("delivered" if delivery else "collect") return " | ".join(parts) print(order("Large", "ham", "olives", drinks=2)) print(order("Small", delivery=False))OutputPress Run to see what it prints.
Key takeaways
Tick each one you could explain to a friend.
0 of 5
Common questions
Guess the answer first, then open it.
Do I have to call them args and kwargs?
When should I use keyword-only parameters?
Is a default evaluated every call?
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Check what you learned
12 questions, with an explanation after every answer. A verified attempt counts towards opening the module Lab.
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 7 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each card opens a web search in a new tab.
References
Look things up here whenever you need the exact details.