Lesson 6
Functions
A function is a command you make yourself. You give it a name, tell it what it needs, and say what it should give back. Then you can use it as many times as you like.
def greet(name: str) -> str:
return f"Ahoy, {name}!"
message = greet("Ada")
print(message)defstarts a function.greetis its name.name: stris a parameter: something the function needs. The: strsays it should be text.-> strsays the function returns text.returnsends the answer back to whoever called the function.- Calling
greet("Ada")runs the function withnameset to"Ada".
Lesson 6 · Try it
Play with functions
Press Run, then try to:
- Call
greetwith your own name. - Write a function
double(number: int) -> intthat returns the number times two. - What does
print(cheer())print, and why? (Hint:-> None)
Press ▶ Run to see what happens.
Lesson 6 · Exercise
Two small functions
Finish the two functions. is_even should return True for even
numbers. biggest should return the bigger of two numbers.
Press ▶ Run to see what happens.
💡 Need a hint?
A number is even when number % 2 == 0, and that comparison is already True or False, so you can return it directly. For biggest, use if a > b: return a, else return b.
Lesson 6
Add it to your project and test it
Put is_even and biggest into main.py in your project. Then
add tests:
from main import biggest, greet, is_even
def test_greet():
assert greet("Ada") == "Hello, Ada!"
def test_is_even():
assert is_even(4) is True
assert is_even(7) is False
def test_biggest():
assert biggest(3, 9) == 9uv run pytestThat is exactly what the exercise checker on this page does: it calls your functions and checks the answers.