iwantcoding.com
🔥 Daily 👥 Rooms 🏆 Top Log in Sign up

Python Functions

Define a function with def. Call it with parentheses. Functions are first-class — pass them around like any other value.

Basics

PYTHON
def greet(name):
    return f'Hello, {name}!'

print(greet('Ada'))

Default arguments

PYTHON
def greet(name='world'):
    return f'Hello, {name}!'

print(greet())          # Hello, world!
print(greet('Ada'))     # Hello, Ada!

Keyword arguments

PYTHON
def reserve(name, table, time, party=2):
    print(f'{party} for {name} at table {table} at {time}')

reserve(name='Ada', table=7, time='19:00')

*args and **kwargs

PYTHON
def log(level, *args, **kwargs):
    print(level, args, kwargs)

log('INFO', 'something', 'happened', user='ada', code=200)
# INFO ('something', 'happened') {'user': 'ada', 'code': 200}

Return multiple values

PYTHON
def min_max(nums):
    return min(nums), max(nums)

lo, hi = min_max([3, 1, 4, 1, 5])

Functions are values

PYTHON
def double(x): return x * 2
ops = [double, abs, str]
for op in ops:
    print(op(-7))
Tip: Don't use a mutable object (list, dict) as a default argument — the default is shared across calls. Use None as the sentinel and build a fresh one inside the function.

Example

Example
def greet(name='world'):
    return f'Hello, {name}!'

print(greet())
print(greet('Ada'))
Try it Yourself »

Exercise

Define a function called greet.

greet(name): return f'Hello, {name}'

Test yourself

Q1. Functions are defined with…
Q2. Default mutable arguments are…
Q3. *args / **kwargs capture…

Discussion

Loading…