Chapter 2 · Decide, repeat, reuse

Modules and programs

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

Step 1 of 21 · Concept

Some functions are always there

In this lesson you use Python's ready-made functions and modules, and split a program into files.

These built-in functions are always there:

callgives
len("Ada")3
abs(-3)3
round(2.7)3
min(4, 9)4
max(4, 9)9
type(2.5)<class 'float'>

round(3.14159, 2) keeps two decimals: 3.14. But round(5.0, 2) shows 5.0, not 5.00; :.2f always shows two (lesson 4).

print(round(2.5), round(3.5), abs(-3), max(4, 9))
print(round(3.14159, 2), round(5.0, 2))
import maths

print(math.sqrt(16))
print(sqrt(9))
print(math.floor(2.7))
print(math.pi)
import random

random.seed(42)
for i in range(8):
    print(random.randint(1, 6), end=" ")
print()
import math

def ladder(out, up):
    return 0

print(ladder(3, 4))
print(ladder(2, 5))
import shapes
import shapes

print("Area:", shapes.area(3, 4))
print("Start")
import shapes
print(shapes.area(3, 4))
import random
random.seed(1)
print(random.randint(1, 6))
import shapes

print("Area:", shapes.area(3, 4))
import money

print(money.price_label(3.5))
print(money.price_label(12))
from app.prices import total

print(f"Total: {total(2.5, 4):.2f}")
# seed random with 42, then five rounds
# of dice.roll_two() and the total
import random

def beats(a, b):
    """True when move a beats move b."""
    if a == "rock":
        return b == "scissors"
    elif a == "paper":
        return b == "rock"
    else:
        return b == "paper"

moves = ["rock", "paper", "scissors"]  # a list: lesson 10
random.seed(7)
Terminal
Step 1 of 12Built-in functions

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)