♦ 🐆 1 min, 🐌 3 min
python
is by design slower than C++
. Sure there's the option of converting python
to "C" with Cython
to achieve speedups. But pure C
and C++
will always be faster than the snake 🐍 .python
out there at the moment:python 2
which you should use only if you have to work with legacy code.python 3
with the latest version 3.9.1. You can find the docs here .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:> python3
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-1200.0.32.27)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>>
in which you can run commands.>>> 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 the way to go if you indent to write more then five lines of code.hello_world.py
and write the following line:print("Hello world!")
Save and close the file.Now in the command line run:> 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. The 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 print
statement would be executed. But we want to execute the print
command only if we directly run the program directly python3 hello_world.py
and not when we import our script. To solve the issue, we can use something called __main__
.__main__
hello_world.py
example into:if __name__ == "__main__":
print("Hello, world!")
Where __name__
will be equal to "__main__"
only if we run our hello_world.py
script directly. If we import our script into another python
program, the variable __name__
will be different.Now when we run the script, python
will check if global variable __name__
is set to "__main__"
and then execute our code.🐍 Python series:Get notified & read regularly 👇