Lesson 11 of 19 · 2 min
Docstrings — Documenting Your Functions
A docstring is a string literal placed immediately after the def line. It explains what the function does, its parameters, and what it returns. Python stores it in function.__doc__ and IDEs use it for auto-completion hints.
def calculate_grade(score):
"""
Convert a numeric score (0-100) to a letter grade.
Parameters:
score (int or float): A number between 0 and 100.
Returns:
str: The letter grade — 'A', 'B', 'C', 'D', or 'F'.
Example:
>>> calculate_grade(85)
'B'
>>> calculate_grade(45)
'D'
"""
if score >= 90:
return "A" # 90-100 → Excellent
elif score >= 75:
return "B" # 75-89 → Good
elif score >= 60:
return "C" # 60-74 → Average
elif score >= 45:
return "D" # 45-59 → Below average, but pass
else:
return "F" # 0-44 → Fail
# Access the docstring any time
print(calculate_grade.__doc__) # print the raw docstring text
help(calculate_grade) # display it in a formatted help page
Output:
Convert a numeric score (0-100) to a letter grade.
...Professional rule: Every function you write should have a docstring. IDEs (VSCode, PyCharm) show it as a tooltip when you call the function.
Data structures are ways of organising related data in memory. Python has four core built-in data structures. Choosing the right one matters for both correctness and speed.
