Ravindra BagaleCourses & study guides मराठी Track your progress

Python Functions Tutorial: def, return, Arguments and lambda with Examples

P7.4 Return Multiple Values and Local Variables in Python

Why. You often want several results at once: total and average, min and max.

What. return a, b returns a tuple. You unpack it: x, y = f(). Variables made inside a function are local — they do not exist outside.

How.

Return two values

  1. Calculate both values.
  2. Write return first, second.
  3. Unpack into two names when calling.

Worked example A — Total and average.

Step 1 — What we do. Weekly sales for a pharmacy in Cape Town.

Step 2 — Type and run this code.

def summary(values):
    total = sum(values)
    avg = total / len(values)
    return total, round(avg, 2)

t, a = summary([4200, 3900, 5100, 4800])
print(t, a)

Step 3 — Output you should see.

18000 4500.0

Step 4 — What it means. One call, two answers.

Worked example B — Local variables stay inside.

Step 1 — What we do. We try to use a variable from inside a function, outside it.

Step 2 — Type and run this code.

def calc():
    inside = 10
    return inside

calc()
print(inside)

Step 3 — Output you should see.

NameError: name 'inside' is not defined

Step 4 — What it means. inside lived only during the call. To use it, store the returned value: x = calc().

Ravindra Bagale's Tip

Pass data in through parameters and get it out through return. Avoid changing global variables inside functions.