How to Switch Between Python 2 and 3

Olorunfemi Akinlua Feb 02, 2024
How to Switch Between Python 2 and 3

Python has different versions across different OS environments (Windows, macOS, Linux, and Android). Since 1991, it has had three major versions (1, 2, and 3).

Python 3.x is preferable more in use than 2.x and 1.x, rightly so. However, certain people, including you, might want to use Python 2.x to access some legacy code or work on certain things.

This article will showcase how to switch between Python 2 and 3 to run your Python code.

Switch Between Python 2 and 3

For different OS, the switch will be different; Linux and macOS work quite the same, but Windows is largely different. The assumption is that you have both versions installed on your PC.

Switch Between Python 2 and 3 in Linux and macOS

You can use the below command for Linux and macOS to switch to Python 2.x.

python2

The output of the command:

Python 2.7.18 (default, Jul  1 2022, 12:27:04)
[GCC 9.4.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.

And if you need to run a Python 2 file:

python2 version.py

And for Python 3, we can use the below command:

python

The output of the command:

Python 3.8.10 (default, Jun 22 2022, 20:18:18)
[GCC 9.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.

And to run a Python 3 file:

python version.py

Switch Between Python 2 and 3 in Windows

For Windows, you can use the below command to switch to Python 2.x.

py -2

The output of the command:

Python 2.6.2 (r262:71605, Apr 14 2009, 22:46:50) [MSC v.1500 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.

If you need to execute a Python 2 file:

py -2 index.py

To switch to Python 3.x and use its interpreter, you can use the command below:

py -3

The output of the command:

Python 3.10.5 (tags/v3.10.5:f377153, Jun  6 2022, 16:14:13) [MSC v.1929 64 bit (AMD64)] on win32
Type "help", "copyright", "credits" or "license" for more information.
Olorunfemi Akinlua avatar Olorunfemi Akinlua avatar

Olorunfemi is a lover of technology and computers. In addition, I write technology and coding content for developers and hobbyists. When not working, I learn to design, among other things.

LinkedIn

Related Article - Python Version