Skip to content

ይህ ትምህርት ገና ወደ አማርኛ አልተተረጎመም፤ ስለዚህ በእንግሊዝኛ ቀርቧል። የእንግሊዝኛውን ገጽ ክፈቱ

Docstrings and a first look at type hints

3 min read

A function's name says what it's for, but not everything: does vat want the price in birr or santim? Does it add the tax or return only the tax? The next person to read your code (often you, next month) needs to know. By the end of this lesson you'll answer those questions inside the function, where Python and your editor can show them.

Docstrings

A string written as the first line of a function's block is its . Python keeps it with the function, and help() shows it along with the parameters:

def vat(price):
    """Return the price with 15% VAT added."""
    return price * 1.15

help(vat)

In the editor, press Escape then Tab to move on.

Docstrings use triple quotes, """, so they can run over several lines. Write the first line as a short command saying what the function does ("Return the price..."). If there's more to say, leave a blank line and add it below. module __main__ just means "your program". In VS Code, holding the pointer over a call to vat shows the same docstring.

A docstring isn't a comment (lesson 0.5): comments are for someone reading the code itself, and Python throws them away. A docstring is for someone using the function, and Python keeps it.

Type hints

A says what type each parameter expects and what the function returns. Write : type after a parameter and -> type before the colon:

def vat(price: float, rate: float = 0.15) -> float:
    """Return the price with VAT added.

    rate is the VAT rate as a fraction: 0.15 means 15%.
    """
    return price * (1 + rate)

help(vat)

In the editor, press Escape then Tab to move on.

With a default, the hint goes before the =, and there are spaces around it: rate: float = 0.15. An int is fine where a hint says float; vat(250) is a normal call.

Hints look like rules. Are they? Predict:

ውጤቱን ገምቱ

Decide before you look. Guessing wrong is how this sticks.

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

print(double("ab"))
Pick the output

Python prints

abab

Python does not check hints when it runs. "ab" * 2 is a real string operation, so it runs and gives abab. The hint only says what the writer meant.

Python ignores hints when it runs your code. A wrong type goes straight in, and you only find out if some line inside can't handle it, far from the real mistake:

So what are hints for? People, editors, and checkers. VS Code uses them to suggest the right methods as you type, and a type checker (Module 14) reads the whole program and reports every call that doesn't match, before you run it.

ጥያቄ

A function has the hint n: int, and you pass it a string. What happens?

Hints for lists, dicts, and nothing

A list's hint names what's inside it: list[int] is a list of whole numbers. dict[str, str] is a dict with string keys and string values. A function that only prints returns None, so its hint is -> None:

def average(scores: list[int]) -> float:
    """Return the average of the scores."""
    return sum(scores) / len(scores)

def show_contacts(contacts: dict[str, str]) -> None:
    """Print each contact's name and number."""
    for name, number in contacts.items():
        print(f"{name}: {number}")

print(f"Average: {average([80, 90, 67])}")
show_contacts({"Abel": "0900 000 001", "Hana": "0900 000 002"})

In the editor, press Escape then Tab to move on.

Hints are optional, and many programs skip them in small scripts. From here on, lessons use them on functions whose types aren't obvious.

መልመጃ

Document three functions

Add a one-line docstring and type hints to each function. The output doesn't change; check it with help(taxi_fare) if you like, then remove that line.

Output
25.5
135
Selam, Hana!

Your code

def santim_to_birr(santim):
    return santim / 100

def taxi_fare(km, base):
    return base + km * 12

def greeting(name):
    return f"Selam, {name}!"

print(santim_to_birr(2550))
print(taxi_fare(10, 15))
print(greeting("Hana"))

In the editor, press Escape then Tab to move on.

መፍትሄውን አሳይ

This is one way to solve it, not the only one. If yours prints the same thing, it works.

def santim_to_birr(santim: int) -> float:
    """Return the amount in birr."""
    return santim / 100

def taxi_fare(km: float, base: float) -> float:
    """Return the fare in birr: the base fare plus 12 birr per km."""
    return base + km * 12

def greeting(name: str) -> str:
    """Return a greeting for name."""
    return f"Selam, {name}!"

print(santim_to_birr(2550))
print(taxi_fare(10, 15))
print(greeting("Hana"))

ዋና ዋና ነጥቦች

  • A docstring is a triple-quoted string as a function's first line; help() and your editor show it.
  • Start a docstring with a short command: "Return the price with VAT added."
  • Type hints (price: float, -> float) say what a function expects and returns.
  • Python doesn't check hints when running: a wrong type fails later, inside the function, or not at all.
  • list[int], dict[str, str], and -> None describe lists, dicts, and functions that only print.