🐍 Python series:
Python is a scripting language that gained in popularity in recent years.
Official site here.
Python was created in the late 1980s by Guido van Rossum as a Christmas project. Heh like this newsletter :P
The language was then officially released for the first time to the public in 1991.
Python is a scripting language that is interpreted, rather than compiled into the machine code, which is one of the major reasons why
python is by design slower than
Sure there's the option of converting
python to "C" with
Cython to achieve speedups. But pure
C++ will always be faster than the snake 🐍 .
There are two major versions of
python out there at the moment:
python 2which you should use only if you have to work with legacy code.
python 3with the latest version 3.9.1. You can find the docs here.
Side note. macOS still ships with
python2 but is finally switching from
python2 so if you run:
> python2 WARNING: Python 2.7 is not recommended. This version is included in macOS for compatibility with legacy software. Future versions of macOS will not include Python 2.7. Instead, it is recommended that you transition to using 'python3' from within Terminal.
python3 from the command line simply run:
This will open the following command line interpreter:
> python3 Python 3.9.0 (default, Nov 21 2020, 14:01:50) [Clang 12.0.0 (clang-122.214.171.124)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>>
in which you can run commands.
To run the classical hello world type into the terminal:
>>> print("Hello, world!")
and press enter. That's it.
That's one way of using python, but I'm personally not a big fan of it. The alternative is to write scripts, which is a way to go if you indent to write more then five lines of code.
You can write scripts and run them directly from the terminal.
Create a file called
hello_world.py and write to it the following line:
Close the file.
Now run in the command line:
> python3 hello_world.py
You should see:
> python3 hello_world.py Hello, world!
Before we wrap up, there's something else I want to cover. Above example has one slight issue. It works fine in our simple case, but the moment our software grows into multiple scripts such "direct" commands become an issue.
If we imported the
hello_world.py file to another
python program, the
python3 hello_world.py and not when we import our script.
To solve the issue, we can use something called
To achieve the desired behaviour we correct our
hello_world.py example into:
if __name__ == "__main__": print("Hello, world!")
__name__ will be equal to
"__main__" only if we run our
hello_world.py script directly. If we import our script to another
__name__ will be different.
Now once we run the script
python will check if global variable
__name__ is set to
"__main__" and then execute our code.