return supplies a value to the caller. print sends text to an output stream.
def name(parameters):
return expression
Example
def add_fee(subtotal):
return subtotal + 20
bill = add_fee(100)
print(bill - 10)
Watch for: Falling off the end returns None. A printed value cannot be used as the function result.
Practise this topic →Parameters bind caller inputs; / and * restrict how arguments can be supplied.
def f(positional_only, /, normal, *, keyword_only): ...
Example
def quote(amount, /, tax=0, *, currency="INR"):
return amount + tax, currency
print(quote(100, 18, currency="INR"))
Watch for: A default is evaluated when def executes. Use None and create a fresh container inside for a per-call mutable default.
Practise this topic →A tuple can carry several results. *args packs extra positional arguments and **kwargs packs keyword arguments.
a, b = pair
f(*values, **options)
Example
def summarize(*values, **options):
return sum(values), options.get("unit", "items")
amount, unit = summarize(*[2, 3], unit="kg")
print(amount, unit)
Watch for: Unpacking must match the expected shape unless a starred target collects the remainder.
Practise this topic →