← Back Peter

Lesson 1: add(a, b)

Why?

A function is a named trick Peter can do. This one adds two numbers and gives them back.

What to type

  • Write def add(a, b):
  • Return the sum with return a + b
  • Test it: print(add(2, 3))
⭐ Stars: 0
🐞 Bugs: 0

Next Lesson →



    
Hint

def starts a function. return hands back the answer.

from js import document, localStorage, window import sys, io START = '''# Make add(a, b), then print the answer def add(a, b): # return the sum pass print(add(2, 3)) # should show 5 ''' SOLN = '''def add(a, b): return a + b print(add(2, 3)) ''' def gi(k): v = localStorage.getItem(k) try: return int(v) if v is not None else 0 except: return 0 def setb(stars=None, bugs=None): if stars is not None: localStorage.setItem('stars', str(stars)) if bugs is not None: localStorage.setItem('bugs', str(bugs)) document.getElementById('stars').textContent = f'⭐ Stars: {gi("stars")}' document.getElementById('bugs').textContent = f'🐞 Bugs: {gi("bugs")}' def run(evt): src = document.getElementById('editor').value out_el = document.getElementById('out') ns = {} f = io.StringIO() try: old = sys.stdout; sys.stdout = f try: exec(src, ns) finally: sys.stdout = old output = f.getvalue() assert 'add' in ns, "Define a function named add(a, b)." assert ns['add'](2,3) == 5, "add(2,3) should be 5." out_el.textContent = (output or "") + "All checks passed! ⭐" setb(stars=gi('stars')+1) try: window.confetti() except: pass except Exception as e: out_el.textContent = "Bug found: " + str(e) setb(bugs=gi('bugs')+1) document.getElementById('run').addEventListener('click', run) document.getElementById('fill-start').addEventListener('click', lambda e: setattr(document.getElementById('editor'), 'value', START)) document.getElementById('fill-solution').addEventListener('click', lambda e: setattr(document.getElementById('editor'), 'value', SOLN)) if not document.getElementById('editor').value: document.getElementById('editor').value = START setb()