Function Arguments Examples
Short, runnable programs that show python function arguments in action. Read the explanation, press Run, then change the code and try your own ideas. New to the topic? Start with the Python Function Arguments lesson.
1One function, four ways to call it
Positional, keyword and mixed calls all reach the same parameters. Keyword arguments let you skip an optional parameter in the middle.
def book_room(guest, nights, breakfast=False, floor=1):
meal = "with breakfast" if breakfast else "room only"
return f"{guest}: {nights} nights, {meal}, floor {floor}"
print(book_room("Asha", 3))
print(book_room("Asha", 3, True))
print(book_room("Asha", 3, floor=4))
print(book_room(nights=2, guest="Ben", breakfast=True))Expected outputAsha: 3 nights, room only, floor 1
Asha: 3 nights, with breakfast, floor 1
Asha: 3 nights, room only, floor 4
Ben: 2 nights, with breakfast, floor 1
2Keyword-only flags and the error they prevent
dry_run can only be passed by name, so nobody can write a mysterious bare True at the end of the call. The try block prints the message Python raises when someone tries anyway.
def delete_files(folder, *, dry_run=True):
mode = "Would delete" if dry_run else "Deleting"
return f"{mode} everything in {folder}"
print(delete_files("/tmp/cache"))
print(delete_files("/tmp/cache", dry_run=False))
try:
delete_files("/tmp/cache", False)
except TypeError as error:
print("Error:", error)Expected outputWould delete everything in /tmp/cache
Deleting everything in /tmp/cache
Error: delete_files() takes 1 positional argument but 2 were given
3Positional-only parameters
clamp(value, /, low, high) keeps a value inside a range. The first argument is just "the value", so it is positional-only, and the range limits can be given by name.
def clamp(value, /, low=0, high=100):
return max(low, min(value, high))
print(clamp(140))
print(clamp(-8))
print(clamp(15, low=20, high=30))
print(clamp(25, high=10))Expected output100
0
20
10
4The None default in an audit log
history defaults to None, so each call that does not pass a list gets its own. The caller can still pass one list to collect several messages together.
def log(message, history=None):
if history is None:
history = []
history.append(message.upper())
return history
print(log("started"))
print(log("finished"))
trail = []
log("login", trail)
log("logout", trail)
print(trail)Expected output['STARTED']
['FINISHED']
['LOGIN', 'LOGOUT']
5Change in place or return a new list
curve_in_place changes the caller's list, while curved builds a new one. Both give the same marks, but only one touches the original.
def curve_in_place(marks, bonus):
for i in range(len(marks)):
marks[i] = min(marks[i] + bonus, 100)
def curved(marks, bonus):
return [min(m + bonus, 100) for m in marks]
exam = [58, 95, 70]
print(curved(exam, 10), exam)
curve_in_place(exam, 10)
print(exam)Expected output[68, 100, 80] [58, 95, 70]
[68, 100, 80]
6Returning several values from one function
stats returns a tuple of three numbers. The caller can unpack all three, or use _ for a value it does not need.
def stats(scores):
low = min(scores)
high = max(scores)
average = sum(scores) / len(scores)
return low, high, average
low, high, average = stats([72, 90, 85, 61])
print(low, high, average)
_, best, _ = stats([40, 55, 48])
print("Best:", best)Expected output61 90 77.0
Best: 55
Practise next
Python Function Arguments exercises → Back to the lesson
Copying Lists and Dicts examplesPython Functions examplesPython *args and **kwargs examplesPython Variable Scope examples