Docstrings and Type Hints
Two small touches turn a working function into a professional one: a docstring and type hints.
A docstring is a string literal placed as the very first line of the function body. It explains what the function does. Tools and help() read it, and Python stores it on function.__doc__:
def add(a, b):
"""Return the sum of a and b."""
return a + b
print(add.__doc__) # Return the sum of a and b.Triple quotes let a docstring span multiple lines, which is handy for longer explanations.
Type hints annotate what types the parameters and the return value are expected to be. You write name: type for each parameter and -> type for the return:
def add(a: int, b: int) -> int:
"""Return the sum of a and b."""
return a + bHints do not force anything at run time. Python will not stop you from passing a string. They are documentation that editors and checkers use to catch mistakes early, and they make your signatures self-explanatory. Common hint types include int, float, str, and bool.
From here on, write functions with both: a clear docstring and honest type hints.
Define a function multiply with type hints def multiply(a: int, b: int) -> int: and a docstring (its first line) reading exactly Return the product of a and b.. The body should return a * b.
This lesson is locked
Lessons open one at a time. Finish the previous lesson to unlock this one.