Как узнать версию python на windows

Интерпретатор 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 вместе с вами, читаю, собираю и записываю информацию опытных программистов.

Время чтения 2 мин.

В данном руководстве рассмотрим, как проверить версию Python на Mac и Windows.

Содержание

  1. Проверка версии Python на Mac
  2. Проверка версии Python в Windows
  3. Узнать версию Python с помощью скрипта

Чтобы проверить версию Python на Mac, выполните следующие действия:

  1. Откройте терминал для Mac.
  2. Введите команду Python –version.
  3. Выполните ее, и она вернет установленную версию Python.

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

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

Чтобы проверить версию Python в Windows:

  1. Откройте приложение командной строки(CMD) для Windows.
  2. Введите команду Python –version.
  3. Выполните ее, и она вернет установленную версию Python.

Если вы введете то же самое в оболочке Windows или в командной строке, вы получите установленную версию Python.

Если версия Python не работает в Linux или Windows, вы также можете написать одну из следующих команд.

  1. python -V
  2. python -VV

Установка Python, его обновление, установка пакетов и стороннего программного обеспечения, такого как Anaconda, а также установка и обновление pip — одни из наиболее часто используемых операций, которые пользователи выполняют в своей системе.

Узнать версию Python с помощью скрипта

Вы можете проверить версию Python с помощью скрипта, импортировав модуль sys и используя выражение sys.version, он возвращает установленную версию Python в вашей системе.

import sys

print(sys.version)

Выход

3.10(default, Dec 22 2021, 13:24:00)

[Clang 13.0.0(clang1300.0.29.3)]

  1. Изображение с названием Check Python

    1

    Откройте строку поиска. Если ее нет на панели задач, щелкните по значку лупы у

    Windows Start

    или нажмите Win+S.

  2. Изображение с названием Check Python

    2

    Введите python в строке поиска. Откроются результаты поиска.

  3. Изображение с названием Check Python

    3

    Нажмите Python [командная строка]. Откроется черное окно командной строки с приглашением Python.

  4. Изображение с названием Check Python

    4

    Найдите версию в первой строке. В левом верхнем углу окна отобразится слово «Python», а справа от него — версия Python (например, 2.7.14).

    Реклама

  1. Изображение с названием Check Python

    1

    Откройте терминал. Для этого откройте окно Finder и нажмите «Программы» > «Утилиты» > «Терминал».

  2. Изображение с названием Check Python

    2

    Введите python -V в терминале.

  3. Изображение с названием Check Python

    3

    Нажмите Return. Версия Python отобразится под словом «Python» (например, 2.7.3).

    Реклама

Об этой статье

Эту страницу просматривали 56 916 раз.

Была ли эта статья полезной?

Очень важно знать, какая версия Python установлена на вашем компьютере, особенно если вы работаете над проектом, который требует определенной версии.

Очень важно знать, какая версия Python установлена на вашем компьютере, особенно если вы работаете над проектом, который требует определенной версии. Версия Python может влиять на работу кода, так как разные версии могут иметь различные функции и библиотеки. Например, у вас может быть установлена версия Python 2.7, но вы хотите использовать функции, доступные только в Python 3.6. В этом случае вам нужно будет обновить Python до версии 3.6.

Узнайте свою версию Python

Есть несколько способов узнать версию Python на вашем компьютере. Но самый простой и надежный из них — это использовать командную строку.

Для пользователей Windows

Откройте командную строку, нажав клавиши Windows + R, затем введите cmd и нажмите Enter.

В командной строке введите python --version и нажмите Enter. Система должна показать версию Python, установленную на вашем компьютере.

Для пользователей MacOS и Linux

Откройте Терминал.

В терминале введите python3 --version и нажмите Enter. Система должна показать версию Python, установленную на вашем компьютере.

Обновление Python

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

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


Download Article

Find out which version of Python you have on any computer


Download Article

  • Checking on a Mac
  • |

  • Checking on Windows
  • |

  • Checking on Linux
  • |

  • Installing Python
  • |

  • Expert Interview
  • |

  • Q&A
  • |

  • Tips

Do you need to find out which version of the Python interpreter is installed on your PC or Mac? Whether you’re using Windows, macOS, or Linux, you can easily check your version of Python using the command python —version in PowerShell or Terminal. If you have both Python 2 and Python 3 installed, you can check their versions using the commands python3 —version and python2 —version. This wikiHow article will show you easy ways to see which version of Python is installed on Windows, Mac, and Linux. We’ll also show you what to do if Python is not found, and give you tips on managing multiple Python versions.

Things You Should Know

  • Multiple versions of Python (e.g., Python 2 and Python 3) can be installed on the same system.
  • Use «python —version» to check the system version of Python.
  • Use «python3 —version» to check the version of Python 3, and python2 —version to check the version of Python 2 individually.
  1. Image titled Check Python

    1

    Open a Terminal window. To do so, just open the Launchpad, type terminal, and click Terminal in the search results.[1]

  2. Image titled Check Python

    2

    Type python --version and press Return. This displays the version of Python installed on your computer.

    • If you have Python 3 in addition to Python 2.7 (the version that used to come preinstalled on macOS), you can check the Python versions separately:
      • Check the Python 2 version: python2 --version[2]
      • Check the Python 3 version: python3 --version
    • You can also use the whereis python command to see where Python is installed.

    Advertisement

  3. Image titled Check Python

    3

    If Python is not found, add the path. If you’ve installed Python but see «command not found» or similar when trying to check the version, you’ll just need to add the Python path variable.

    • Type sudo nano /etc/paths and press Return.
    • On the last line of the file, add the full path to Python. This is usually /Library/Frameworks/Python.framework.[3]
    • Save the file by pressing Ctrl + O and then Ctrl + X.
    • Close the Terminal and open a new one. Now, when you type python --version, you’ll see the Python version.
  4. Image titled Check Python

    4

    Change the default python to Python 3 (optional). If you have multiple Python versions installed and want to change the system version to Python 3, it’s easy. You’ll just need to edit your .zshrc or .bashrc file to create an alias. Here’s how:

    • In a Terminal, type nano ~/.zshrc and press Return. If the file does not already exist, use nano ~/.bashrc instead.
    • Paste this line at the bottom of the file: alias python=/usr/local/bin/python3.
    • Save the file by pressing Ctrl + O and then Ctrl + X.
    • Close the Terminal and open a new one. Now, when you type python --version, you’ll see the Python 3 version.
  5. Advertisement

  1. Image titled Check Python

    1

    Open PowerShell. You can do this quickly by pressing Windows key + S, typing powershell, and clicking Windows PowerShell.

    • You can also right-click the Start menu and select PowerShell or Terminal (if either are present). This command to check your Python version will work the same no matter which option you choose.[4]
  2. Image titled Check Python

    2

    Type python --version and press Enter. If Python is installed, this command will display the version number of your primary version of Python.

    • If you have multiple versions of Python installed, you can check each version individually.
      • Check the Python 2 version: python2 --version
      • Check the Python 3 version: python3 --version
      • You can also use the command get-command python* to see all installed versions of Python and their paths.
  3. Image titled Check Python

    3

    If Python is not found, add the path to your environment variables. If you’re sure you’ve installed Python but see a «Python not found» when checking the version, there’s an easy fix:

    • In File Explorer, find the folder in which Python is installed. It’s usually something like C:\Users\yourname\AppData\Local\Programs\Python\Python311.
    • In the Windows Search bar, type sysdm.cpl and press Enter.
    • Click Environment Variables…
    • Under «User Variables,» select the Path variable and click Edit.
    • If the path to Python does not appear, click New, paste the full path (e.g., C:\Users\yourname\AppData\Local\Programs\Python\Python311, and press Enter.
    • Click New again, and paste the path to the scripts directory. It’s the same path, but with \Scripts at the end, e.g., C:\Users\yourname\AppData\Local\Programs\Python\Python311\Scripts.
    • Click OK until you’ve exited out of the app.
    • Close your PowerShell window and open a new one. You should now be able to check the version with python --version.
  4. Image titled Check Python

    4

    Use multiple versions of Python at once (optional). If you had Python 2 installed before installing Python 3, python.exe will always start Python 2 instead of Python 3. Just use python3 when you want to use Python 3, and python when you want to use Python 2.[5]

    • Alternatively, you can rename the python.exe file in your Python 2 directory to python2.exe, and just use python2 when you want to use the Python 2 interpreter. When you installed Python 3, the installer also created a file called python.exe in your Python 3 install directory. This means that once you rename the Python 2 version of python.exe, typing python should automatically launch Python 3 as long as your Python 3 installation path is correct.
      • Double-check your Python 3 installation path to make sure you have a file called python.exe there. If not, copy python3.exe and rename the copy python.exe for the same effect.
  5. Advertisement

  1. Image titled Check Python

    1

    Open a Terminal window. If you’re using Linux, you can usually open a Terminal by pressing Ctrl + Alt + T at the same time.

  2. Image titled Check Python

    2

    Type python --version and press Return. This displays the system version of Python installed on your computer.

    • If you have Python 3 in addition to Python 2.7 (the version that used to come preinstalled on macOS), you can check the Python versions separately:
      • Check the Python 2 version: python2 --version[6]
      • Check the Python 3 version: python3 --version
    • You can also use the whereis python command to see where Python is installed. If you want to check the installation directory of Python 3 specifically, use whereis python3 instead.
  3. Image titled Check Python

    3

    If Python is not found, add the path. If you’ve installed Python but see «command not found» or similar when trying to check the version, you’ll just need to add the Python path variable.

      • Type nano ~/.profile and press Enter.
      • Add the path to the version of Python you’ve installed to the last line of the file like this: PYTHONPATH=/usr/bin/python.
    • Save the file by pressing Ctrl + O and then Ctrl + X.
    • Close your Terminal, then open a new one. Type python --version to see the Python version.
  4. Image titled Check Python

    4

    Change the default python to Python 3 (optional). If you want to use Python 2 and Python 3 at the same time and want to make the python command launch python3, you have a few options:

    • On Ubuntu and Linux Mint, install python-is-python3 using the command sudo apt install python-is-python3.[7]
      This ensures that running the python command always uses the Python 3 interpreter instead of other installed versions.
    • On other versions (or if you don’t want to install a package), just create a symbolic link that makes the python command start python3 instead:
      • Use ls -l /usr/bin/python* to see all symbolic links for python. If /usr/bin/python is linking to anything other than your preferred version, you can change the link.
      • To change the link, use the command sudo ln -fs /usr/bin/python<Version> /usr/bin/python. Replace <version> with the name of the Python binary you want to link to (e.g., sudo ln -fs /usr/bin/python3 /usr/bin/python. In this example, you’d now be able to type python --version and see the Python 3 version number.
  5. Advertisement

  1. Image titled Check Python

    1

    Windows. If you see «Python was not found» when checking the version, see our Python installation guide for Windows, or install using one of these two simple options:

    • Download the latest version of Python from https://www.python.org/downloads. Once downloaded, double-click the installer, and follow the on-screen instructions to install. When installing, make sure to choose the option to add Python to your path.
    • You can also install Python from the Microsoft Store. Just open the Microsoft Store app on your Windows 10 or 11 PC and search for python. Click the latest version of Python (e.g., Python 3.11), click Get, and follow the on-screen instructions.
  2. Image titled Check Python

    2

    Mac. If Python isn’t installed on your Mac, there are two easy ways to install it:

    • You can download the latest Python installer from https://www.python.org/downloads. Once downloaded, double-click the .pkg file and follow the on-screen instructions.
    • Alternatively, you can use Homebrew:
      • In a Terminal window, type xcode-select --install and press Return. This installs Xcode, Apple’s developer tools.[8]
      • Type or paste this command to install Homebrew: ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)". Once you press Return, Homebrew will install.
      • Type brew install python3 and press Return to install Python3.
  3. Image titled Check Python

    3

    Linux. The best way to install Python on Linux is to use your distribution’s repositories. First, you’ll want to find out which version of Python you need:

    • Using Apt on Ubuntu and Linux Mint:

      • Type sudo apt update and press Enter.
      • Type sudo apt install python3 and press Enter.
    • Arch Linux:

      • Type packman -S python and press Enter.
    • Fedora, Red Hat, & CentOS:

      • Type sudo yum -y update and press Enter.
      • Type sudo dnf install python3 and press Enter.
  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

  • If you have Python 3.6 or later, you can also use python --VV to see extended version information, including the release date.

Advertisement

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 400,400 times.

Is this article up to date?

  • Как узнать версию powershell на windows 10
  • Как узнать версию агента обновления windows
  • Как узнать версию windows server
  • Как узнать версию postgresql windows
  • Как узнать адрес сетевого диска windows 10