Python files

This post is part of the Python Crash Course series. The chronological order on how to read the articles is to be found on the agenda.

In the previous post (see python-via-command-line) we have interacted with python and wrote our very first python instructions.

However, this stateless way of using python is not very handy as – once the session is over – the lines of code cannot be accessed anymore.

The solution is to write our code in files. Instructions can be saved in python files. A python file is just an ordinary file that ends with the .py extension.

Generic python file

The general template for your python files is as follow:

"""
Few lines describing what your file
is useful for (optional but good practice).
"""

if __name__ == "__main__":
    # your instructions go there
    # these are just inline-comments
    # that are going to be ignored.
    # ...
    # PS. indentations are important.

For instance, here are the content of a file I named first_python_script.py:

"""
Short script containing my very first
Python instructions.
"""

if __name__ == "__main__":
    a = 41
    b = 1
    print(a+b)
    print("foo")

Executing the Python file

You can then tell python to execute your script via a command line instruction in the terminal:

zsh> python path/to/your/file/filename.py

Here is what I obtain after I have run the following command:

zsh> python ./first_python_script.py
42
foo

Note: you can write python files in a text editor – even on Microsoft Word. However, there is some special softwares on the market that help you to write code. They provide autocompletion, coloration and a lot of other useful features. You can check https://code.visualstudio.com/.

What comes next?

You have python installed in your system.

You can interact with python and execute python code; either via command lines via terminal prompts or running python scripts containing your python instructions.

It’s now time to deep-dive into the python syntax and explore the possibilities offered by this programming language.

Leave a Reply

Your email address will not be published. Required fields are marked *