Skip to main content

Chapter 4b - Functions

Why functions​

A function packages a piece of work behind a name. Game code calls the same ideas often β€” damage, healing, formatting a HUD line β€” so you write them once and reuse them.

func double(n: int) -> int:
return n * 2

print(double(7)) # 14
πŸ§ͺ Try it

Anatomy​

func name(param: Type) -> ReturnType:
# body
return value
PieceRole
funcStarts a function
parametersInputs the caller passes in
-> TypeOptional return type (recommended in lessons)
returnSends a result back to the caller

Call a function with parentheses: double(7). Without (), you only mention the function β€” you do not run it.

Mini quiz β€” functions​

Quiz

Functions

1 / 3

What does return do?

Pick an answer to see if you are right.

Multiple parameters and defaults​

Pass several values, separated by commas. Default arguments fill in when the caller omits them.

func heal(hp: int, amount: int = 5, max_hp: int = 100) -> int:
return mini(max_hp, hp + amount)

print(heal(90)) # 95 β€” amount defaults to 5
print(heal(90, 20)) # 100 β€” capped by max_hp
πŸ§ͺ Try defaults

Functions calling functions​

Small helpers compose. Keep each function focused β€” one job is easier to test.

func armor_block(dmg: int, armor: int) -> int:
return maxi(0, dmg - armor)

func apply_hit(hp: int, dmg: int, armor: int) -> int:
return maxi(0, hp - armor_block(dmg, armor))
πŸ§ͺ Try composition

Challenge: apply hit​

Write apply_hit(hp, dmg, armor) so it:

  1. Reduces damage by armor (damage cannot go below 0)
  2. Subtracts that from hp (hp cannot go below 0)
  3. Returns the new HP

Example: hp=20, dmg=8, armor=3 β†’ blocked damage is 5 β†’ result 15.

Indentation

Indent with 4 spaces. Click Reset if an old draft looks flat.

Exercises​

Warm up with a pure return, format a status string, then clamp a value into a range.

Activity: Triple

Write triple(n) so it returns n * 3.

21