If you are working out how to write a Python script for a first programming module, the blank file is usually less of a problem than knowing what a tidy, markable script is supposed to look like. The approach below builds a short program the way many course handbooks expect, with a description at the top, a function that does the work, clear comments and a main block, and it leans on the official Python documentation and the PEP 8 style guide for the conventions.

Plan the inputs, processing and outputs from the brief

Before typing any code, write three short lists from the assignment brief: what the user or file will supply, what the program must calculate, and exactly what it must print. The running example here is a converter that reads a temperature in Celsius and prints it in Fahrenheit, which is small enough to show every part of a script. If Python is not yet set up on your computer, the guide to installing Python and running your first program covers that first.

Create a .py file and describe it with a docstring

Save a new file such as convert.py in a folder for the assignment, and put a one-line string at the very top that says what the script does. The Python tutorial calls a string literal at the start of a function a docstring and describes it as good practice to include one in code you write (Python Software Foundation, n.d.-c), and markers reading your file benefit from the same summary at the top.

How to write a Python script around a function

Put the actual calculation inside a function, so it has a name, takes the values it needs and returns a result. PEP 8 recommends lowercase function names with words separated by underscores and four spaces per indentation level (van Rossum et al., 2001), which is why the function below is called celsius_to_fahrenheit.

"""Convert a temperature from Celsius to Fahrenheit."""


def celsius_to_fahrenheit(celsius):
    """Return the Fahrenheit value for a Celsius temperature."""
    return celsius * 9 / 5 + 32


def main():
    # Ask for a value and turn the text into a number.
    text = input("Temperature in Celsius: ")
    celsius = float(text)
    fahrenheit = celsius_to_fahrenheit(celsius)
    print(f"{celsius} C is {fahrenheit} F")


if __name__ == "__main__":
    main()

Comments start with the hash character and run to the end of the line (Python Software Foundation, n.d.-a), and PEP 8 asks that block comments be written as complete sentences (van Rossum et al., 2001). A useful comment explains why a line exists, such as the type conversion, since the code already shows what it does.

Read input and convert it to the right type

The built-in input() function writes your prompt, reads a line from the user and returns it as a string (Python Software Foundation, n.d.-b), so "21" typed at the keyboard arrives as text. Arithmetic on that text fails or behaves oddly, which is why the script passes it through float() before doing any calculation, and int() is the equivalent when the brief asks for whole numbers.

Add a main function and the __name__ check

The last two lines run main() only when the file is executed directly, because code inside an if __name__ == '__main__' block does not run when the module is imported from somewhere else, such as a test file (Python Software Foundation, n.d.-d). The same documentation suggests keeping that block short and wrapping the program's main behaviour in a function named main, which also stops variables leaking into the whole module.

Run the script with values you can check by hand

Run python convert.py from the assignment folder and try inputs whose answers you already know, such as 0, which should give 32.0, and 100, which should give 212.0. Then try something the brief may not mention, like a negative number or a word, and decide whether the assignment expects you to handle it, since an unexpected crash during marking costs more than the few lines needed to deal with it.

If a script runs on your machine but you are unsure whether it meets the brief, coding support and assignment support can talk through your own code with you and explain any changes.

Frequently asked questions

Do I need the if __name__ == "__main__" line in a small script?

The script will run without it, but the check lets you import your functions into a test file without the program starting, and many courses expect to see it (Python Software Foundation, n.d.-d).

How many comments should a beginner script have?

You need enough that someone reading the file understands why each section exists, and a docstring at the top, one for each function and short comments on any line that is not obvious are a sensible baseline, and your module guidance may set its own rules.

References

Python Software Foundation. (n.d.-a). An informal introduction to Python. Python documentation.

Python Software Foundation. (n.d.-b). Built-in functions. Python documentation.

Python Software Foundation. (n.d.-c). More control flow tools. Python documentation.

Python Software Foundation. (n.d.-d). __main__: Top-level code environment. Python documentation.

van Rossum, G., Warsaw, B., & Coghlan, N. (2001). PEP 8: Style guide for Python code. Python Enhancement Proposals.