Program structure

Published

2023-07-31

Program structure

There is an order to things, and programs are no different. Your Python code should follow this general layout:

  1. docstring
  2. imports (if any)
  3. constants (if any)
  4. 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)

MEGACYCLES_PER_FROMBULATION = 133   # constants (if any)

# 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__':
    x = float(input("Enter a real number: "))
    print(f"Answer: {f(g(x)) 
            / MEGACYCLES_PER_FROMBULATION} megacycles!")

Original author: Clayton Cafiero < [given name] DOT [surname] AT uvm DOT edu >

No generative AI was used in producing this material. This was written the old-fashioned way.

This material is for free use under either the GNU Free Documentation License or the Creative Commons Attribution-ShareAlike 3.0 United States License (take your pick).