Как проверить наличие python на windows 10

3 способа как узнать и проверить версию интерпретатора Python на компьютере: функция python_version(), команда python -V, метод sys.version - пошагово на примерах.

Интерпретатор Python используется во многих коммерческих отраслях для кодирования исходного кода, компьютерного программирования и тестирования. Он принимает команды от пользователя и выполняет их после их интерпретации. Следовательно, очень важно знать о версии интерпретатора Python, которую мы в настоящее время используем.

Как мы знаем, интерпретатор  берет код от пользователя и выполняет его построчно. Предположим, что у нас есть более старая версия интерпретатора Python. В этом случае команда не выполняется должным образом из-за более старой версии интерпретатора и его несовместимости с новыми функциями, используемыми в команде.

В данном руководстве разберем как пользователь может проверить используемую версию Python.

Python – это язык программирования, который поставляется с регулярным обновлением, которое добавляет вместе с ним некоторые новые функции и возможности; поэтому, как пользователь, мы также должны регулярно обновлять наш интерпретатор Python до последней выпущенной версии.

Примечание. Последней версией интерпретатора Python на данный момент является «3.9.6» со стабильной версией.

Ниже приведены некоторые основные преимущества проверки используемой версии интерпретатора Python:

  • Мы будем знать, если нам не хватает каких-либо обновлений для интерпретатора или обновления функции идут вместе с ним.
  • Можем выяснить, возникает ли синтаксическая ошибка из-за более старой версии интерпретатора Python.
  • У нас может быть доступ ко всем последним функциям и обновлениям, которые поставляются с последней версией интерпретатора.

Проверка версии Python

В этом разделе мы узнаем о методах, с помощью которых мы можем быстро проверить версию интерпретатора Python, которую мы используем. Мы даже можем проверить версию с помощью программы Python, а также будем использовать метод командной строки.

Ниже приведены методы проверки версии интерпретатора Python:

  • с функцией python_version();
  • с помощью команды python -V;
  • с помощью метода sys.version.

Давайте разберемся, как мы можем использовать эти методы в Python, а также в терминале командной строки для проверки версии интерпретатора Python.

Метод 1: Использование функции python_version()

Чтобы использовать эту функцию для проверки версии интерпретатора Python, мы сначала должны импортировать библиотеку платформы. Функция python_version() всегда возвращает версию интерпретатора в строковом формате. Чтобы лучше понять, как это работает, давайте воспользуемся этим в нашей программе Python.

Взгляните на следующую программу:

 
# Importing platform library 
from platform import python_version  
# Getting Python interpreter version as a result 
print("Current Version of Python interpreter we are using-", python_version()) 

Выход:

Current Version of Python interpreter we are using- 3.9.0 

Объяснение:

Как видно из вышеприведенного вывода, мы используем версию интерпретатора Python 3.9.0.

Мы также можем использовать эту функцию в терминале командной строки и проверить версию интерпретатора. Для использования функции python_version() в терминале мы должны придерживаться следующих шагов:

  • Шаг 1: Откройте терминальную оболочку cmd системы.
  • Шаг 2: Напишите «python» и нажмите клавишу ввода, чтобы войти в оболочку Python.
  • Шаг 3: Теперь напишите приведенный выше код построчно внутри терминала и нажмите клавишу ввода.

Терминал покажет версию интерпретатора как результат кода, как показано ниже:

Результат кода

Метод 2: Использование команды python -V

Использование команды python -V считается самым простым и легким методом проверки версии интерпретатора Python. Это встроенная команда оболочки командной строки, и этот метод специально создан для проверки версии Python.

В этом методе нужно выполнить только следующие два шага:

Шаг 1: Откройте оболочку терминала устройства.

Шаг 2: Напишите в оболочке следующую команду и нажмите Enter:

 
'python -V' 

Теперь мы получим версию интерпретатора Python, которую мы используем, в строковом формате.

Как проверить версию Python

Метод 3: С помощью метода sys.version

Чтобы использовать метод sys.version для проверки версии интерпретатора Python, мы сначала должны импортировать библиотеку платформы. Как и метод функции python_version(), мы можем использовать этот метод как в оболочке командной строки, так и в программе Python в оболочке.

Здесь мы будем использовать этот метод только как программу Python и получим версию интерпретатора Python в качестве выходных данных программы.

Пример –

 
# Importing sys library 
import sys  
# Getting interpreter version as a result 
print("Current Version of Python interpreter we are using-" sys.version) 

Выход:

Current Version of Python interpreter we are using- 3.9.0(tags/v3.9.0:9cf6752, Oct  5 2020, 15:34:40) [MSC v.1927 64 bit(AMD64)] 

Итак, как мы видим в выводе, у нас есть версия интерпретатора, которую мы используем в строковом формате, мы также получили тег и дату выпуска версии интерпретатора в этом методе sys.version.

Изучаю Python вместе с вами, читаю, собираю и записываю информацию опытных программистов.

Как проверить установлен ли Python?

На чтение 3 мин Просмотров 5.4к. Опубликовано 16.09.2020

Подробная статья рассматривающая способы проверки установки Python в операционных системах Windows, Linux и MacOS.

Содержание

  1. Введение
  2. Как найти python в Microsoft Windows?
  3. Как найти python в Unix подобных ОС (Linux и MacOS)
  4. Заключение

Введение

Не редкий случай, когда начинающие программисты определились с выбором языка программирования и решили написать свою первую программу, чаще всего — hello world. Но где найти и как открыть python?

Подход для каждой операционной системы различается, приведу примеры для Windows и Linux.

Как найти python в Microsoft Windows?

Большинство программ в этой операционной системе устанавливаются в папку Program Files расположенную на вашем системном диске. Но искать среди кучи установленных программ не самый простой вариант. Можно открыть меню Пуск и воспользоваться поисковой строкой для обнаружения установленной версии Python.

Как найти python в Microsoft Windows?
Как найти python в Microsoft Windows?

В Windows 10 по умолчанию поисковая строка — отсутствует, но до тех пор, пока вы не начнете вводить текст. Введите — python и если в вашей системе он установлен windows найдет это приложение. 

На моей тестовой системе установленные 2 версии python.

Как найти python в Unix подобных ОС (Linux и MacOS)

В большинстве дистрибутивов Unix python установлен по умолчанию. Более того, он поставляется в двух версия, python2.7 и python3. 

Чтобы найти исполняемый файл python — запустите эмулятор терминала и введите в него команду which python

Как найти python в Unix подобных ОС (Linux и MacOS)
Как найти python в Unix подобных ОС (Linux и MacOS)

Результатом выполнения команды будет путь до исполняемого файла. Но как узнать какой версии python? Для этого необходимо выполнить еще одну команду в терминале — /usr/bin/python —version

Как найти python в Unix подобных ОС (Linux и MacOS)
Как найти python в Unix подобных ОС (Linux и MacOS)

Как видим, данный исполняемый файл версии 2.7.16.

Но наверняка вам нужна более актуальная и поддерживаемая версия Python 3. Её тоже не составит труда найти и достаточно выполнить команду which python3

Как найти python в Unix подобных ОС (Linux и MacOS)
Как найти python в Unix подобных ОС (Linux и MacOS)

Как видим — результат выполнения команды путь до исполняемого файла ( пути до исполняемых файлов могут отличаться из за разных структур файловой системы операционных систем). 

Осталось проверить версию интерпретатора python3.

Как найти python в Unix подобных ОС (Linux и MacOS)
Как найти python в Unix подобных ОС (Linux и MacOS)

У нас установлена версия Python 3.8.0.

Так же большинство дистрибутивов создают символические ссылки на исполняемые файлы, для их быстрого запуска без указания полного пути к исполняемому файлу. Например запустить версию python2.7 можно командой python2.7, а версию 3 командой python3

Как найти python в Unix подобных ОС (Linux и MacOS)
Как найти python в Unix подобных ОС (Linux и MacOS)

Заключение

Теперь вы знаете как найти python на вашем компьютере вне зависимости от вашей операционной системы. 

Егор Егоров

Программирую на Python с 2017 года. Люблю создавать контент, который помогает людям понять сложные вещи. Не представляю жизнь без непрерывного цикла обучения, спорта и чувства юмора.

Ссылка на мой github есть в шапке. Залетай.


Download Article

A step-by-step guide on checking your Python version


Download Article

This wikiHow teaches you how to find which version of Python is installed on your Windows or macOS computer.

  1. Image titled Check Python

    1

    Open Windows Search. If you don’t already see a search box in the taskbar, click the magnifying glass or circle next to

    Image titled Windowsstart.png

    , or press Win+S.

  2. Image titled Check Python

    2

    Type python into the search bar. A list of matching results will appear.

    Advertisement

  3. Image titled Check Python

    3

    Click Python [command line]. This opens a black terminal window to a Python prompt.

  4. Image titled Check Python

    4

    Find the version in first line. It’s the number right after the word “Python” at the top-left corner of the window (e.g. 2.7.14).

  5. Advertisement

  1. Image titled Check Python

    1

    Open a Terminal window on your Mac. To do this, open the Applications folder in Finder, double-click the Utilities folder, then double-click Terminal.

  2. Image titled Check Python

    2

    Type python -V at the prompt (V uppercase).

  3. Image titled Check Python

    3

    Press Return. The version number will appear on the next line after the word “Python” (e.g. 2.7.3).

  4. Advertisement

Add New Question

  • Question

    I downloaded Python 3.7 but when I check it says that the version is 2.7. What should I do ? (I tried reinstalling it.)

    faith daniel

    faith daniel

    Community Answer

    To prevent further hassle, just download the 3.x version or the latest version from the Python website (python.org).

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

About This Article

Article SummaryX

To check which version of Python is installed on your Windows PC, start by opening the Windows Search and typing “Python” into the search bar. When the list of matching results comes up, click “Python” to open a black terminal window to a Python prompt. In the top-left corner of the window, you’ll see a number right after the word “Python,” which is the version that you’re currently running. To learn how to find the version of Python on your Mac, keep reading!

Did this summary help you?

Thanks to all authors for creating a page that has been read 367,479 times.

Is this article up to date?


Download Article

A step-by-step guide on checking your Python version


Download Article

This wikiHow teaches you how to find which version of Python is installed on your Windows or macOS computer.

  1. Image titled Check Python

    1

    Open Windows Search. If you don’t already see a search box in the taskbar, click the magnifying glass or circle next to

    Image titled Windowsstart.png

    , or press Win+S.

  2. Image titled Check Python

    2

    Type python into the search bar. A list of matching results will appear.

    Advertisement

  3. Image titled Check Python

    3

    Click Python [command line]. This opens a black terminal window to a Python prompt.

  4. Image titled Check Python

    4

    Find the version in first line. It’s the number right after the word “Python” at the top-left corner of the window (e.g. 2.7.14).

  5. Advertisement

  1. Image titled Check Python

    1

    Open a Terminal window on your Mac. To do this, open the Applications folder in Finder, double-click the Utilities folder, then double-click Terminal.

  2. Image titled Check Python

    2

    Type python -V at the prompt (V uppercase).

  3. Image titled Check Python

    3

    Press Return. The version number will appear on the next line after the word “Python” (e.g. 2.7.3).

  4. Advertisement

Add New Question

  • Question

    I downloaded Python 3.7 but when I check it says that the version is 2.7. What should I do ? (I tried reinstalling it.)

    faith daniel

    faith daniel

    Community Answer

    To prevent further hassle, just download the 3.x version or the latest version from the Python website (python.org).

Ask a Question

200 characters left

Include your email address to get a message when this question is answered.

Submit

Advertisement

Thanks for submitting a tip for review!

About This Article

Article SummaryX

To check which version of Python is installed on your Windows PC, start by opening the Windows Search and typing “Python” into the search bar. When the list of matching results comes up, click “Python” to open a black terminal window to a Python prompt. In the top-left corner of the window, you’ll see a number right after the word “Python,” which is the version that you’re currently running. To learn how to find the version of Python on your Mac, keep reading!

Did this summary help you?

Thanks to all authors for creating a page that has been read 367,479 times.

Is this article up to date?

Как проверить версию Python

How to Check Python Version


В этом руководстве объясняется, как проверить, какая версия Python установлена ​​в вашей операционной системе с помощью командной строки. Это может быть полезно при установке приложений, которым требуется определенная версия Python.

Как проверить версию Python

Python — один из самых популярных языков программирования в мире. Он используется для разработки веб-сайтов,
написания сценариев, машинного обучения, анализа данных и многого другого.

Мы также покажем вам, как программно определить, какая версия Python установлена ​​в системе, где выполняется
скрипт Python. Например, при написании сценариев Python вам необходимо определить, поддерживает ли сценарий
версию Python, установленную на компьютере пользователя.

Версии Python

Готовые к выпуску версии Python имеют следующую версию:

Например, в Python 3.6.8 это основная версия, дополнительная версия и
микро версия.

  • MAJOR— Python имеет две основные версии, которые не полностью совместимы: Python 2 и Python 3.
    Например, 3.5.7, 3.7.2, и 3.8.0 являются частью в Python 3
    основные версии.
  • MINOR— Эти релизы приносят новые функции и возможности. Так , например, 3.6.6,
    3.6.7 и 3.6.8 являются частью минорной версии Python 3.6.
  • MICRO — Как правило, новые микро-версии содержат различные исправления ошибок и улучшения.

Разрабатываемые релизы имеют дополнительные классификаторы. Для получения дополнительной информации прочитайте
документацию Python «Цикл разработки» .

Проверка версии Python

Python предустановлен в большинстве дистрибутивов Linux и
macOS.

Чтобы узнать, какая версия Python установлена в вашей системе, введите команду python
--version 
или python -V:

python --version

    Команда выведет версию Python по умолчанию, в данном случае, то есть 2.7.15. Версия,
установленная в вашей системе, может отличаться.

Python 2.7.15+


    Версия Python по умолчанию будет использоваться всеми сценариями, которые /usr/bin/python установлены
в качестве интерпретатора в строке сценария shebang .

В некоторых дистрибутивах Linux установлено несколько версий Python одновременно. Как правило, двоичный файл
Python 3 называется python3, а двоичный файл Python 2 — python или
python2, но это не всегда так.

Вы можете проверить, установлен ли Python 3, набрав:

python3 --version
Python 3.6.8


    Поддержка Python 2 заканчивается в 2020 году. Python 3 — это настоящее и будущее языка.

На момент написания этой статьи последний основной выпуск Python — это версия 3.8.x. Скорее всего, в вашей
системе установлена ​​более старая версия Python 3.

Если вы хотите установить последнюю версию Python, процедура зависит от операционной системы, которую вы
используете.

Программная проверка версии Python

Python 2 и Python 3 принципиально разные. Код, написанный на Python 2.x, может не работать в Python 3.x.

sys модуль, который доступен во всех
версиях Python предоставляет параметры и функции системы конкретных. sys.version_info позволяет
определить версию Python, установленную в системе. Это кортеж , который содержит пять номеров версий: major,
minor, micro, releaselevel, и serial.

Допустим, у вас есть скрипт, который требует как минимум Python версии 3.5, и вы хотите проверить, соответствует
ли система требованиям. Вы можете сделать это, просто проверив major и
minor версии:

import sys

if not (sys.version_info.major == 3 and sys.version_info.minor >= 5):
    print("This script requires Python 3.5 or higher!")
    print("You are using Python {}.{}.".format(sys.version_info.major, sys.version_info.minor))
    sys.exit(1)

Если вы запустите скрипт, используя версию Python менее 3.5, он выдаст следующий вывод:

This script requires Python 3.5 or higher!
You are using Python 2.7.

    Чтобы написать код Python, который работает под Python 3 и 2, используйте future модуль. Это позволяет запускать Python
3.x-совместимый код под Python 2.

Вывод

Узнать, какая версия Python установлена в вашей системе, очень просто, просто введите python
--version
.

I have to run a Python script on a Windows server. How can I know which version of Python I have, and does it even really matter?

I was thinking of updating to the latest version of Python.

Peter Mortensen's user avatar

asked Jan 18, 2012 at 21:43

Ali_IT's user avatar

6

In a Python IDE, just copy and paste in the following code and run it (the version will come up in the output area):

import sys
print(sys.version)

Peter Mortensen's user avatar

answered Jan 3, 2014 at 4:47

pzp's user avatar

pzppzp

6,1811 gold badge27 silver badges38 bronze badges

6

Python 2.5+:

python --version

Python 2.4-:

python -c 'import sys; print(sys.version)'

mcandre's user avatar

mcandre

22k19 gold badges87 silver badges145 bronze badges

answered Jan 18, 2012 at 21:45

Abbas's user avatar

AbbasAbbas

6,6704 gold badges35 silver badges49 bronze badges

5

At a command prompt type:

python -V

Or if you have pyenv:

pyenv versions

Eric Leschinski's user avatar

answered Jan 18, 2012 at 21:45

Brian Willis's user avatar

Brian WillisBrian Willis

22.1k9 gold badges46 silver badges50 bronze badges

0

Although the question is «which version am I using?», this may not actually be everything you need to know. You may have other versions installed and this can cause problems, particularly when installing additional modules. This is my rough-and-ready approach to finding out what versions are installed:

updatedb                  # Be in root for this
locate site.py            # All installations I've ever seen have this

The output for a single Python installation should look something like this:

/usr/lib64/python2.7/site.py
/usr/lib64/python2.7/site.pyc
/usr/lib64/python2.7/site.pyo

Multiple installations will have output something like this:

/root/Python-2.7.6/Lib/site.py
/root/Python-2.7.6/Lib/site.pyc
/root/Python-2.7.6/Lib/site.pyo
/root/Python-2.7.6/Lib/test/test_site.py
/usr/lib/python2.6/site-packages/site.py
/usr/lib/python2.6/site-packages/site.pyc
/usr/lib/python2.6/site-packages/site.pyo
/usr/lib64/python2.6/site.py
/usr/lib64/python2.6/site.pyc
/usr/lib64/python2.6/site.pyo
/usr/local/lib/python2.7/site.py
/usr/local/lib/python2.7/site.pyc
/usr/local/lib/python2.7/site.pyo
/usr/local/lib/python2.7/test/test_site.py
/usr/local/lib/python2.7/test/test_site.pyc
/usr/local/lib/python2.7/test/test_site.pyo

Peter Mortensen's user avatar

answered May 31, 2015 at 11:17

user2099484's user avatar

user2099484user2099484

4,3092 gold badges20 silver badges9 bronze badges

1

When I open Python (command line) the first thing it tells me is the version.

answered Jan 18, 2012 at 21:47

poy's user avatar

poypoy

9,8339 gold badges45 silver badges72 bronze badges

2

In [1]: import sys

In [2]: sys.version
2.7.11 |Anaconda 2.5.0 (64-bit)| (default, Dec  6 2015, 18:08:32) 
[GCC 4.4.7 20120313 (Red Hat 4.4.7-1)]

In [3]: sys.version_info
sys.version_info(major=2, minor=7, micro=11, releaselevel='final', serial=0)

In [4]: sys.version_info >= (2,7)
Out[4]: True

In [5]: sys.version_info >= (3,)
Out[5]: False

answered May 26, 2016 at 13:34

wsdzbm's user avatar

wsdzbmwsdzbm

2,8093 gold badges23 silver badges26 bronze badges

In short:

Type python in a command prompt

Simply open the command prompt (Win + R) and type cmd and in the command prompt then typing python will give you all necessary information regarding versions:

Python version

mar10's user avatar

mar10

13.9k5 gold badges38 silver badges64 bronze badges

answered Dec 15, 2016 at 9:48

Dastagir Husain Yasin's user avatar

2

I have Python 3.7.0 on Windows 10.

This is what worked for me in the command prompt and Git Bash:

To run Python and check the version:

py

To only check which version you have:

py --version

or

py -V    # Make sure it is a capital V

Note: python, python --version, python -V,Python, Python --version, Python -V did not work for me.

Peter Mortensen's user avatar

answered Dec 23, 2018 at 3:24

dahiana's user avatar

dahianadahiana

1,1212 gold badges9 silver badges10 bronze badges

1

>>> import sys; print('{0[0]}.{0[1]}'.format(sys.version_info))
3.5

so from the command line:

python -c "import sys; print('{0[0]}.{0[1]}'.format(sys.version_info))"

answered Jul 22, 2016 at 7:28

Baczek's user avatar

BaczekBaczek

1,1391 gold badge13 silver badges22 bronze badges

Use

python -V

or

python --version

NOTE: Please note that the «V» in the python -V command is capital V. python -v (small «v») will launch Python in verbose mode.

Peter Mortensen's user avatar

answered Nov 21, 2015 at 0:47

Yogesh Yadav's user avatar

Yogesh YadavYogesh Yadav

4,3496 gold badges32 silver badges38 bronze badges

0

You can get the version of Python by using the following command

python --version

You can even get the version of any package installed in venv using pip freeze as:

pip freeze | grep "package name"

Or using the Python interpreter as:

In [1]: import django
In [2]: django.VERSION
Out[2]: (1, 6, 1, 'final', 0)

Peter Mortensen's user avatar

answered May 17, 2015 at 6:13

Pooja's user avatar

PoojaPooja

1,23414 silver badges17 bronze badges

To check the Python version in a Jupyter notebook, you can use:

from platform import python_version
print(python_version())

to get version number, as:

3.7.3

or:

import sys
print(sys.version)

to get more information, as

3.7.3 (default, Apr 24 2019, 13:20:13) [MSC v.1915 32 bit (Intel)]

or:

sys.version_info

to get major, minor and micro versions, as

sys.version_info(major=3, minor=7, micro=3, releaselevel='final', serial=0)

answered Jan 9, 2020 at 19:25

nucsit026's user avatar

nucsit026nucsit026

6327 silver badges16 bronze badges

On Windows 10 with Python 3.9.1, using the command line:

    py -V

Python 3.9.1

    py --version

Python 3.9.1

    py -VV

Python 3.9.1 (tags/v3.9.1:1e5d33e, Dec  7 2020, 17:08:21) [MSC v.1927 64 bit 
(AMD64)]

answered Sep 12, 2016 at 15:04

Sam's user avatar

SamSam

2133 silver badges7 bronze badges

2

If you are already in a REPL window and don’t see the welcome message with the version number, you can use help() to see the major and minor version:

>>>help()
Welcome to Python 3.6's help utility!
...

Peter Mortensen's user avatar

answered Feb 15, 2019 at 12:41

OrigamiEye's user avatar

OrigamiEyeOrigamiEye

7501 gold badge8 silver badges27 bronze badges

Typing where python on Windows into a Command Prompt may tell you where multiple different versions of python are installed, assuming they have been added to your path.

Typing python -V into the Command Prompt should display the version.

answered Feb 8, 2020 at 5:07

Pro Q's user avatar

Pro QPro Q

4,1144 gold badges39 silver badges86 bronze badges

If you have Python installed then the easiest way you can check the version number is by typing «python» in your command prompt. It will show you the version number and if it is running on 32 bit or 64 bit and some other information. For some applications you would want to have a latest version and sometimes not. It depends on what packages you want to install or use.

answered Aug 13, 2017 at 22:45

Sagar_c_k's user avatar

1

To verify the Python version for commands on Windows, run the following commands in a command prompt and verify the output:

c:> python -V
Python 2.7.16

c:> py -2 -V
Python 2.7.16

c:> py -3 -V
Python 3.7.3

Also, to see the folder configuration for each Python version, run the following commands:

For Python 2, 'py -2 -m site'
For Python 3, 'py -3 -m site'

Peter Mortensen's user avatar

answered Apr 2, 2019 at 17:16

Aamir M Meman's user avatar

For me, opening CMD and running

py

will show something like

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32

Type "help", "copyright", "credits" or "license" for more information.

Peter Mortensen's user avatar

answered Dec 29, 2015 at 12:42

Joginder Sharma's user avatar

1

Just create a file ending with .py and paste the code below into and run it.

#!/usr/bin/python3.6

import platform
import sys

def linux_dist():
  try:
    return platform.linux_distribution()
  except:
    return "N/A"

print("""Python version: %s
dist: %s
linux_distribution: %s
system: %s
machine: %s
platform: %s
uname: %s
version: %s
""" % (
sys.version.split('n'),
str(platform.dist()),
linux_dist(),
platform.system(),
platform.machine(),
platform.platform(),
platform.uname(),
platform.version(),
))

If several Python interpreter versions are installed on a system, run the following commands.

On Linux, run in a terminal:

ll /usr/bin/python*

On Windows, run in a command prompt:

dir %LOCALAPPDATA%ProgramsPython

Peter Mortensen's user avatar

answered Mar 19, 2018 at 13:24

Don Matteo's user avatar

1

There are two simple ways to check for the version of Python installed.

Run any of the codes on the command prompt:

python -v

or

python --version

answered Jul 28, 2022 at 4:43

Happy N. Monday's user avatar

Happy N. MondayHappy N. Monday

1931 gold badge2 silver badges6 bronze badges

For the latest versions please use the below command for the python version

py -V

answered Aug 1, 2022 at 3:56

Jb-99's user avatar

Jb-99Jb-99

1359 bronze badges

Mostly usage commands:

python -version

Or

python -V

answered Jun 8, 2020 at 12:23

KittoMi's user avatar

KittoMiKittoMi

4135 silver badges18 bronze badges

The default Python version and the paths of all installed versions on Windows:

py -0p

One-Liners:

❯❯  python -V | cut -c8-
3.11.0

❯❯ ~ python -VV
Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)]

❯❯ ~ python --version
Python 3.11.0

❯❯ ~ py --list
-V:3.11 *        Python 3.11 (64-bit)
-V:3.10          Python 3.10 (64-bit)
-V:3.9           Python 3.9 (64-bit)

❯❯ ~ py -V
Python 3.11.0

❯❯ ~ py -VV
Python 3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)]

❯❯ ~ py --version
Python 3.11.0

❯❯ ~ py -0p
-V:3.11 *        W:Windows 10Python311python.exe
-V:3.10          W:Windows 10Python310python.exe
-V:3.9           C:Program FilesPython39python.exe

❯❯ ~ python -c 'import sys; print(".".join(sys.version.split(".")[0:2]))'
3.11

❯❯ ~ python -c 'import sys; print(sys.version)'
3.11.0 (main, Oct 24 2022, 18:26:48) [MSC v.1933 64 bit (AMD64)]

❯❯ ~ python -c 'import sys; print((str(sys.version_info.major) +"."+ str(sys.version_info.minor)))'
3.11

❯❯ ~ python -c 'import sys; print(sys.version_info)' sys.version_info(major=3, minor=11, micro=0, releaselevel='final', serial=0)

❯❯ ~ python -c 'import platform; print(platform.python_version()[:-2])'
3.11

❯❯ ~ python -c 'import platform; print(platform.python_version())'
3.11.0

❯❯ ~ python -c 'import platform; print("{0[0]}.{0[1]}".format(platform.python_version_tuple()))'
3.11

❯❯ ~ python -c 'import platform; print(platform.python_version_tuple())'
('3', '11', '0')

answered Dec 5, 2021 at 11:44

Szczerski's user avatar

SzczerskiSzczerski

7099 silver badges9 bronze badges

For bash scripts this would be the easiest way:

# In the form major.minor.micro e.g. '3.6.8'
# The second part excludes the 'Python ' prefix 
PYTHON_VERSION=`python3 --version | awk '{print $2}'`
echo "python3 version: ${PYTHON_VERSION}"
python3 version: 3.6.8

And if you just need the major.minor version (e.g. 3.6) you can either use the above and then pick the first 3 characters:

PYTHON_VERSION=`python3 --version | awk '{print $2}'`
echo "python3 major.minor: ${PYTHON_VERSION:0:3}"
python3 major.minor: 3.6

or

PYTHON_VERSION=`python3 -c 'import sys; print(str(sys.version_info[0])+"."+str(sys.version_info[1]))'`
echo "python3 major.minor: ${PYTHON_VERSION}"
python3 major.minor: 3.6

answered Jan 8, 2021 at 12:31

Giorgos Myrianthous's user avatar

as of 2022, to check what version you’re on you can do python --version

answered Jul 31, 2022 at 0:11

orangey's user avatar

Open a command prompt window (press Windows + R, type in cmd, and hit Enter).

Type python.exe

Peter Mortensen's user avatar

answered Jun 29, 2017 at 7:28

Erina's user avatar

ErinaErina

811 gold badge2 silver badges13 bronze badges

1

Introduction

Which version of Python do I have installed?

Python is a popular programming language. Like many other programming languages, there can be several different versions organized by release date. Certain applications may require a specific version of Python.

In this tutorial, learn how to check the Python version on Windows, Linux, or macOS systems.

tutorial on how to check Python version.

Prerequisites  

Access to a command-line/terminal window:

  • Linux:  Ctrl-Alt-T, Ctrl-Alt-F2
  • Windows:  Win+R > type powershell > Enter/OK
  • MacOS:  Finder > Applications > Utilities > Terminal

There are different versions of Python, but the two most popular ones are Python 2.7.x and Python 3.7.x. The x stands for the revision level and could change as new releases come out.

When looking at the version number, there are usually three digits to read:

  1. the major version
  2. the minor version
  3. the micro version

While major releases are not fully compatible, minor releases generally are. Version 3.6.1 should be compatible with 3.7.1 for example. The final digit signifies the latest patches and updates.

Python 2.7 and 3.7 are different applications. Software that’s written in one version often will not work correctly in another version. When using Python, it is essential to know which version an application requires, and which version you have.

Python 2 will stop publishing security updates and patches after 2020. They extended the deadline because of the large number of developers using Python 2.7. Python 3 includes a 2 to 3 utility that helps translate Python 2 code into Python 3.

How to Check Python Version in Linux

Most modern Linux distributions come with Python pre-installed.

To check the version installed, open a terminal window and entering the following:

python --version
python version linux

How to Check Python Version in Windows

Most out-of-the-box Windows installations do not come with Python pre-installed. However, it is always a good idea to check.

Open Windows Powershell, and enter the following:

python --version

If you have Python installed, it will report the version number.

check python version windows

Alternately, use the Windows Search function to see which version of Python you have:

Press the Windows key to start a search, then type Python. The system will return any results that match. Most likely a match will show something similar to:

Python 3.7 (32-bit)

app

Or,

Python 2.7 (32-bit)

app

This defines which major and minor revision (3.x or 2.x) you are using.

How to Check Python Version in MacOS

If using a MacOS, check the Python version by entering the following command in the terminal:

python -version

The system will report the version.

check python version macos

Note: In some cases, this will return a screen full of information. If that happens, just scan through the file locations for the word python with a number after it. That number is the version.

Checking a System with Multiple Versions of Python

Python2 and Python3 are different programs. Many programs upgrade from the older version to the newer one. However, Python 2.7.x installations can be run separately from the Python 3.7.x version on the same system.

Python 3 is not entirely backward compatible.

To check for Python 2.7.x:

python --version

To check the version of Python 3 software:

python3 --version

Most systems differentiate Python 2 as python and Python 3 as python3. If you do not have Python 2, your system may use the python command in place of python3.

Note: Python does not have a built-in upgrade system. You’ll need to download the latest version and install it.

How to Check Python Version in Script

When writing an application, it is helpful to have the software check the version of Python before it runs to prevent crashes and incompatibilities.

Use the following code snippet to check for the correct version of Python:

import sys
if not sys.version_info.major == 3 and sys.version_info.minor >= 6:

    print("Python 3.6 or higher is required.")

    print("You are using Python {}.{}.".format(sys.version_info.major, sys.version_info.minor))

    sys.exit(1)

When this script runs, it will test to see if Python 3.6 is installed on the system. If not, it will send a notification and displays the current Python version.

Conclusion

You should now have a solid understanding of how to check for the version of Python installed in several different operating systems. Python is a powerful programming language, thus it’s important to understand its different versions.

If you want to learn how to upgrade Python to a newer version on Wondows, macOs, and Linux, check our article how to upgrade Python to 3.9.

Windows не содержит Python в списке предустановленных программ. Вы можете скачать его и установить дополнительно. Во время первой установки Python 3 на Windows могут возникнуть трудности, поэтому мы создали этот туториал. Просто следуйте инструкции и у вас все получится.

Какую версию Python скачать — 2 или 3?

Больше 10 лет назад вышла новая версия python, которая разделила сообщество на 2 части. Сразу это вызывало много споров, новичкам приходилось выбирать: python 2 или python 3. Сегодня большая часть обучается третей версии. На этой версии мы и покажем как установить язык программирования python на Windows.

На этой странице вы можете скачать python для Windows.
В вверху разработчики предлагают выбрать версию.
Скачать Python на WindowsНажмите на ссылку которая начинается словами “Последний выпуск Python 3…” и попадете на страницу последней версии Python 3. Сейчас это 3.7.2.

Если вы не планируете работать с проектом, который написан на Python 2, а таких довольно много. Скачайте python 2+. Для веб разработки, анализа данных и многих других целей лучшим вариантом будет python 3 версии.

Внизу страницы версии ссылки на скачивание установщиков. Есть возможность скачать python под 64-битную и 32-битную Windows.

скачать python под 64-битную и 32-битную Windows

Вне зависимости от версии и страны, python на английском языке. Вы не сможете скачать python на русском с официального сайта (и с любого другого).

Скачайте и запустите установщик Python 3, он называется “python-3.****.exe”.

Если на компьютере уже установлена python 2, нет необходимости удалять его. На установку Python 3 она не повлияет.

На первом экране отметьте пункт “Add Python 3.7 to PATH” и нажмите “Install Now”.

Установка python 3 на WindowsПосле установки появится возможность отключить ограничение длины MAX_PATH. В системах Linux этих ограничений нет. Проигнорировав этот пункт, вы можете столкнуться с проблемой совместимости в будущем. Код созданный на Linux не запустится на Windows.

отключить ограничение длины MAX_PATHСоветуем отключить эту опцию. Если вы точно уверены, что не столкнетесь с проблемой совместимости, нажмите “Close”

Как проверить уставился ли python

Самый быстрый и простой способ узнать, есть ли интерпретатор python на компьютере — через командную строку.

  1. Запустите cmd.exe через диспетчер задач или поиск.
  2. Введите python
    В результате командная строка выведет версию python, которая установлена в системе.
    командная строка выведет версию python

Если версия python 2 или вы получили ошибку:

"python" не является внутренней или внешней
командой, исполняемой программой или пакетным файлом.

Следуйте инструкциям ниже. Это легко исправить.

Как добавить python в переменную PATH (ADD to PATH)

Откройте окно “Система” с помощью поиска.

Как открыть систему на windows

В окне “Система”, нажмите “Дополнительные параметры системы”. Откроется “Свойства системы”. Во вкладке “Дополнительно”, нажимайте “Переменные среды” как на фото ниже.

Как открыть переменные среды на windows

В открывшемся окне выберите Path -> “Изменить”. Откроется новое окно, куда вы должны добавить путь к интерпретатору python.

Как добавить python в переменную PATH

Путь у каждого свой, похож на C:UsersUserNameAppDataLocalProgramsPythonPython37. Где Python37 — папка с python.

Нажмите “Создать” и добавьте 2 пути. К папке python и pythonScripts

Как добавить python в переменную PATH 2

Как создать отдельную команду для python 2 и python 3

Чтобы использовать обе версии python, измените python.exe на python2.exe, в папке с python 2. А в папке с python 3 , python.exe на python3.exe.

Теперь проверьте обе версии:

>python2 -V
Python 2.7.14

>python3 -V
Python 3.7.2

После этих не сложных действий, python установлен на вашем Windows и готов к работе в любом текстовом редакторе.

Попробуйте создать свою первую программу:
Первая программа на Python «Hello world»

Понравилась статья? Поделить с друзьями:
  • Как проверить ноутбук для перехода на windows 11
  • Как проверить наличие net framework на windows 10
  • Как проверить ноут на производительность windows 10
  • Как проверить наличие java на windows 10
  • Как проверить наличие directx 12 на windows 10