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
- Calculate both values.
- Write
return first, second. - 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.
Ravindra Bagale's Tip – मराठी
Data parameters मधून आत द्या आणि return मधून बाहेर घ्या. Functions मध्ये global variables बदलणं टाळा.
Ravindra Bagale's Tip – हिंदी
Data parameters से अंदर दो और return से बाहर लो. Functions के अंदर global variables बदलने से बचो.