Chapter 2 · Decide, repeat, reuse

Functions

You are reading the whole lesson on one page. Back to one step at a time

Step 1 of 22 · Concept

A function names a piece of work

In this lesson you write your own functions, give them values and get answers back.

def greet(name):
    """Print a greeting."""
    print("Hello,", name)
partmeans
def greetmake a function named greet
(name)its parameter: a name for the value it gets
: and the indented blockits body

def binds the name greet to a function object. The body runs later, at each call, such as greet("Ada").

def greet(name):
    """Print a greeting."""
    print("Hello,", name)

greet("Ada")
greet("Alan")
print(type(greet))
def show(n):
    print("n is", n)

result = show(3)
print(result)
def area(w, h):
    print(w * h)

def describe(w, h):
    return f"{w} by {h}: {area(w, h)}"

print(describe(3, 4))
# is_even(n): True when n is even, else False

print(is_even(3))
print(is_even(8))
print(is_even(0))
def bump(n):
    n = n + 1
    print("inside:", n)

n = 5
bump(n)
print("outside:", n)
def grade(score):
    return "?"

print(grade(95))
print(grade(72))
print(grade(40))
def area(w, h):
    return w * h

print(area(3, 4))
print(area(3))
def greet(name, greeting="Hello"):
    print(f"{greeting}, {name}!")

greet("Ada")
greet("Alan", greeting="Hi")
for i in range(5):
    print("*", end="")
print()
print(1, 2, 3, sep=" < ")
count = 0

def show():
    print("count is", count)

def add():
    count += 1

show()
add()
# to_fahrenheit(c) and describe(c, label="Today"),
# then three calls to describe, each printed
def first_divisor(n):
    return n

print(first_divisor(15))
print(first_divisor(49))
print(first_divisor(13))
Terminal
Step 1 of 11Call greet twice

Keyboard shortcuts

The step

ContinueEnter
Previous / next stepAlt+[ · Alt+]
Move along the steps bar← → Home End, then Enter
From a quiz's title to its answers↓
Skip to the stepTab, then Enter (first on the page)
Course outlineAlt+O
These shortcuts?

The workspace

Run the stepCtrl+Enter (⌘↵ on a Mac)
Lesson → editor → consoleF6 (Shift+F6 back)
Output ↔ TerminalCtrl+`
Focus the editorCtrl+. (⌘. on a Mac)
Hide or show the lessonAlt+L
Restore, close a messageEsc (outside the editor and the terminal)

The editor

Leave the editorF6 (Shift+F6 back); or Ctrl+M (⌃⇧M on a Mac), then Tab moves the focus (not in the vim mode)
Open a file by nameCtrl+P (⌘P on a Mac)
All commandsCtrl+Shift+P (⌘⇧P on a Mac) or F1
Go to a lineCtrl+G (⌃G on a Mac)
Show or hide the filesCtrl+B (⌘B on a Mac)
Previous / next file tabCtrl+Shift+[ · Ctrl+Shift+] (⌘⇧[ · ⌘⇧] on a Mac)
The file tabs← → Home End on a tab; Delete closes it
Save the files nowCtrl+S (⌘S on a Mac)
Go to a symbol in the fileCtrl+Shift+O (⌘⇧O on a Mac)
Go to the definitionF12
Format the fileCtrl+Shift+F (⌘⇧F on a Mac), or Shift+Alt+F
Go back / forward after a jumpAlt+← · Alt+→ (⌃- · ⌃⇧- on a Mac)