Skip to Content

Python: Writing a New Program From Scratch

Maybe you say to yourself, “I don’t know where to start!” when thinking about creating a brand new Python program. Hopefully this page will help.

Firstly, you do need to understand the problem you want your program to solve or do. The page on applying computational thinking practically can help here. But this doesn’t completely go into the nitty gritty of starting a program.

Secondly, at the end of my Python Cheatsheet page is a general outline and template for a Python program, and it is also at the bottom of this page. So you can use that as an initial guide, but it doesn’t really tell you anything about how to code your own program.

Break it down into: get data, do something, make output

Your program fundamentally needs to get some input from the user, perform some computation, and produce some output. So start with these three steps and think about what they should look like.

1. Get Input

2. Do the Computation

3. Produce Output

A General Python Program File

A good template for a general Python program is shown below. Remember, lines (and partial end-of-lines) beginning with “#” are comments to be read by humans, not executed as part of the program. This template is mostly comments.

#!/usr/bin/python3
#
# A file header comment at the beginning is a good place to name and describe
# the Python program that is in this file.
# - special notes to someone using this program can be written here, so that
#   the see it right at the top of the program file
#

#
# Library imports: effective programming in any language requires using
# its standard libraries; the Python "import" statement brings in library
# modules: see https://docs.python.org/3/library/index.html for a list of
# the standard libraries. Example imports are below
#
import math
import string
import datetime

#
# Next should come function definitions. Each function should have a
# comment header that describes what the function does
#
def myFunctionOne(param1,param2,...):
    function body goes here, indented

#-------------------------------------------------------------
# Finally, the main program code should be the final part
# - it should have a comment header that clearly separates it
# from the stuff above, like this one does
#-------------------------------------------------------------
Main
Code
Goes 
Here

The first line in the template above is “#!/usr/bin/python3”. Since it begins with “#” it is simply a Python comment line, but when this kind of line is the first line in a python script, it enables the file to be run directly as a command itself, on Linux, Unix, and MacOS systems. Windows is probably different. This line is never absolutely needed, we can always run the program by writing “python3 myprogram.py”, but if we use this line and set the permissions correctly, we can just run “myprogram.py” as a command itself. If you want to know more, go here.