Program structure
Program structure
There is an order to things, and programs are no different. Your Python code should follow this general layout:
- docstring
- imports (if any)
- constants (if any)
- function definitions (if any)
\ldots and then, nested under if __name__ == '__main__':
, all the rest of your code. Here’s an example:
"""
A docstring, delimited by triple double-quotes,
which includes your name and a brief description
of your program.
"""
import foo # imports (if any)
= 133 # constants (if any)
MEGACYCLES_PER_FROMBULATION
# Functions which you define...
def f(x_):
return 2 * x_ + 1
def g(x_):
return (x_ - 1) ** 2
# The rest of your code...
if __name__ == '__main__':
= float(input("Enter a real number: "))
x print(f"Answer: {f(g(x))
/ MEGACYCLES_PER_FROMBULATION} megacycles!")
Copyright © 2023–2025 Clayton Cafiero
No generative AI was used in producing this material. This was written the old-fashioned way.