Codiqo

Learn Python · lesson 35 of 60 · about 7 minutes

Scope and Clean Design

Sum up the week's sleep with a function that only uses what it's given and returns what it works out.

What you'll learn

  • Explain local and global variables
  • Pass data in and return it out
  • Break a problem into functions

A function that minds its own business

The assistant's sleep checks are spread through the script. sleep_summary(nights) gathers them: it gets the nights as a parameter, counts the good ones in its own local variable, and returns two numbers, the good nights and the average. It doesn't print and doesn't touch anything outside itself, so it works for any list of nights you hand it.

Local variables stay inside

A variable created inside a function is local: it only exists while the function runs, and the rest of the program can't see it. Variables made outside functions are global.

The clean way to share data is to pass it in as an argument and send results out with return.

Inside and outside are separate

score = 10

def bonus():
    score = 99
    return score

print(bonus())
print(score)

Output

99
10

Small functions, big programs

Good programs are built from small functions that each do one job and have a clear name. They're easier to read, test and reuse.

One job per function

def average(nums):
    return sum(nums) / len(nums)

def grade(avg):
    return "pass" if avg >= 50 else "retry"

marks = [40, 70, 65]
print(grade(average(marks)))

Output

pass

Tip

return a, b gives back two values at once, and good, avg = summary(...) unpacks them, just like the alarm's (hour, minute) tuple.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.