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

#статьи


  • 0

Python — самый популярный язык программирования, на котором разрабатывают ИИ, игры и сложные системы. Разбираемся с его установкой.

Иллюстрация: Skillbox Media

Дмитрий Зверев

Любитель научной фантастики и технологического прогресса. Хорошо сочетает в себе заумного технаря и утончённого гуманитария. Пишет про IT и радуется этому.

Python — это высокоуровневый язык программирования общего назначения с минималистичным и простым в освоении синтаксисом. Он был создан под влиянием языка ABC, который изначально задумывался как обучающий и над которым ранее работал автор Python Гвидо ван Россум.

К сожалению, не все ОС содержат Python по умолчанию. В таких случаях, чтобы начать программировать на языке, его придётся установить. В этой статье мы расскажем, как это сделать.

Гайд по установке Python:

  • Какую версию выбрать
  • Как установить
  • Как начать работать
  • Как подключить к VS Code

Вообще, для решения простых задач или знакомства с языком хватит и онлайн-интерпретатора. Это сервис, который позволяет писать и запускать код прямо в браузере, ничего не скачивая. Самые популярные онлайн-интерпретаторы — Replit, Programiz и Online Python.

Интерфейс Replit
Скриншот: Skillbox Media

Интерфейс Programiz
Скриншот: Skillbox Media

Интерфейс Online Python
Скриншот: Skillbox Media

Это хороший инструмент, но только для написания простых программ. Там сложно тестировать приложения, полноценно работать с файлами и использовать продвинутые возможности языка.

Для полноценной разработки всё-таки нужно будет установить Python на компьютер. Но, поверьте, оно того стоит: вы сможете легко подключать сторонние библиотеки, использовать утилиты и создавать сложные проекты.

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

Однако для поддержки старых проектов, которые не могут переехать на Python 3, придётся скачивать Python 2 и разбираться в различиях версий. Поэтому даже в 2023 году в вакансиях среди требований можно найти «уверенное знание Python 2.7».

В состав базовой версии Python входят следующие компоненты:

  • IDLE — простая среда разработки Python-программ;
  • документация — инструкция по использованию Python;
  • стандартная библиотека — набор функций, которые упрощают работу с числами, файлами, API сторонних сервисов и так далее;
  • пакетный менеджер PIP — утилита для скачивания и установки библиотек, фреймворков и других пакетов, расширяющих функциональность Python;
  • стандартный набор тестов — чтобы проверять надёжность программы;
  • Python Launcher — приложение для запуска программ с расширением .py.

Этого набора вполне хватит, чтобы начать изучение языка и писать простые программы.

Вы читаете эту статью, потому что хотите освоить «змеиный» язык? Присмотритесь к этому курсу Skillbox — он подойдёт тем, кто хочет начать работать с Python программирования с нуля.

Перед установкой убедитесь, что ваш компьютер удовлетворяет системным требованиям:

  • 64- или 32-разрядный процессор на архитектуре Intel или AMD;
  • 2 ГБ оперативной памяти, желательно 4 ГБ;
  • 5 ГБ свободного места в памяти компьютера;
  • версия операционной системы: не ниже Windows 7, macOS X 10.11, Red Hat Enterprise Linux 6/7.

Дистрибутивы Python есть для всех популярных операционных систем, они перечислены на официальном сайте python.org. По большому счёту, не так важно, какую конкретно версию Python вы скачаете, — главное, чтобы её номер начинался с цифры 3.

Скриншот: Python Software Foundation / Skillbox Media

Скачайте установочный файл, нажав на жёлтую кнопку Download Python, и запустите его.

Выберите путь установки и поставьте обе галочки: во втором пункте мы указываем, что нужно добавить Python в переменную окружения PATH — это позволит вызывать его из любой директории. Затем выбираем «Установка для всех пользователей» (Install for all users), нажимаем Install Now и разрешаем приложению вносить изменения:

Скриншот: Skillbox Media

Когда всё установится, вы увидите окно завершения инсталляции:

Скриншот: Skillbox Media

Теперь проверим, что Python действительно установлен. Для этого откроем окно «Выполнить» сочетанием клавиш Win + R и введём cmd:

Скриншот: Skillbox Media

Откроется командная строка. Введите в ней команду py или python, чтобы запустить интерпретатор. На экране появится примерно такое сообщение:

Microsoft Windows [Version 10.0.19043.1889]
(c) Корпорация Майкрософт (Microsoft Corporation). Все права защищены.

C:\Users\User>py
Python 3.11.2 (tags/v3.11.2:9c7b4bd, Feb 2 2023, 18:38:48) [MSC v.1932 64 bit (AMD64)] on win 32
Type "help", "copyright", "credits" or "license" for more information.
>>>

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

Если у вас более ранняя версия Windows, процесс установки Python ничем не отличается, кроме того, что некоторые версии языка не поддерживаются на старых операционных системах. Узнать, подходит ли версия Python вашей ОС, можно в примечаниях на странице скачивания:

Последние версии языка не поддерживаются Windows 7 и более старыми ОС
Скриншот: Skillbox Media

Python входит в состав большинства дистрибутивов Linux. Чтобы это проверить, введите в терминале следующую команду:

$ python3 --version

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

В Ubuntu 16.10 это делается так:

$ sudo apt-get update
$ sudo apt-get install python3.6

Утилита попросит вас ввести пароль и после ввода начнёт установку.

Однако, если вы хотите поставить более свежую версию Python, для установки нужно использовать репозиторий deadsnakes PPA:

$ sudo apt-get install software-properties-common
$ sudo add-apt-repository ppa:deadsnakes/ppa
$ sudo apt-get update
$ sudo apt-get install python3.8

В Fedora Linux процесс установки похожий, но используется другая команда:

$ sudo dnf install python3.9

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

С давних времён MacBook и iMac выпускались с предустановленным Python 2.7. Правда, начиная с версии 12.3 разработчики «яблочной» ОС отказались от этой традиции.

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

python --version

Вместо версии 3.9.12 у вас может быть версия, например, 2.7.18
Скриншот: Skillbox Media

В любом случае лучше установить последнюю версию Python — найти её можно на официальном сайте.

Последняя версия на момент написания статьи — 3.11.2
Скриншот: Python Software Foundation / Skillbox Media

Нажмите жёлтую кнопку Download Python 3.11.2, и пакет начнёт скачиваться:

Скриншот: Skillbox Media

Когда загрузка завершится, откройте его:

Скриншот: Skillbox Media

Согласитесь со всеми пунктами и переходите к установке. Вас попросят ввести пароль, а после — начнётся установка, по окончании которой вы увидите такое окно:

Скриншот: Skillbox Media

Нажмите Close и откройте терминал, чтобы проверить версию Python:

python --version

Должно быть выведено сообщение Python 3.11.2.

Дата-сайентисты используют свои библиотеки для работы — например, NumPy и Pandas. Их можно устанавливать по отдельности, а можно скачать готовую сборку со всеми библиотеками.

Самый популярный способ — использовать дистрибутив Anaconda. Он бесплатный и легко устанавливаемый, а также доступен для всех операционных систем. Мы покажем, как установить его на macOS.

Нажмите на кнопку Download, чтобы начать скачивание:

Нажимаем огромную зелёную кнопку «Скачать»
Скриншот: Anaconda Inc. / Skillbox Media

Затем откройте установщик, согласитесь со всеми пунктами и выберите место для установки.

Так выглядит сообщение об успешной установке Anaconda
Скриншот: Skillbox Media

Чтобы убедиться, что Python установлен, откройте консоль и введите команду python3 — должен запуститься интерпретатор Python, в котором можно писать код. Выглядит это примерно так:

Если можем писать код, значит, всё работает как нужно
Скриншот: Skillbox Media

Теперь, чтобы использовать одну из библиотек для data science, нужно всего лишь импортировать её в Python-файле:

import numpy

А чтобы проверить, работает ли библиотека, достаточно запустить файл, в котором вы её подключили. Если библиотека не подключилась, то интерпретатор выдаст сообщение об ошибке.

После того как мы установили Python, пора написать пару строк кода. Вы можете использовать любую IDE (в том числе IDLE), редактор кода или даже «Блокнот».

Создадим файл program.py на рабочем столе. В нём мы вызовем всего одну функцию, которая выведет на экран текстовое сообщение:

print("Привет, мир!")

Запустим программу командой py или python в командной строке, прописав полный путь до файла program.py. Например, если он лежит на рабочем столе, запустить его можно так:

Microsoft Windows [Version 10.0.19043.1889]
(c) Корпорация Майкрософт (Microsoft Corporation). Все права защищены.

C:\Users\User>py C:\Users\User\Desktop\program.py
Привет, мир!

Мы передали код интерпретатору, который обработал его и вывел сообщение на экран. Всё получилось!

VS Code — это удобный редактор кода, который поддерживает десятки языков программирования и плагинов. По популярности VS Code сильно опережает аналоги, поэтому будет полезно разобраться, как установить Python туда.

Сначала нужно найти плагин для языка. Откройте вкладку Extensions («Расширения») и введите в поиске следующую строку:

tag:debuggers @sort:installs

В появившемся списке найдите Python и нажмите Install.

Скриншот: Skillbox Media

Теперь нужно включить подсветку кода. Для этого установите плагин MagicPython — найти его можно в том же поиске, введя команду ext: py3. Чтобы всё заработало, перезапустите VS Code и создайте файл с расширением .py. Когда редактор спросит, на каком языке вы собираетесь программировать, — выберите Python. Готово!

В Skillbox есть полноценный курс по Python. Опытные менторы помогут освоить язык быстро и на реальных задачах. Это обучение с упором на практику и помощью в трудоустройстве, без расписаний и жёстких дедлайнов.

Хоть VS Code является самым популярным редактором кода, многие программисты предпочитают специализированные IDE, заточенные именно под разработку на Python. Абсолютный фаворит здесь — PyCharm, в состав которой уже входит Python.

Чтобы установить PyCharm, зайдите на сайт JetBrains и нажмите кнопку Download:

Скриншот: JetBrains / Skillbox Media

Вам предложат выбрать операционную систему и версию среды разработки: Professional и Community. Community — это бесплатная версия, в которой отсутствует поддержка некоторых функций и фреймворков, например Django. Но на первых порах её вполне хватит, поэтому выбираем её:

Скриншот: Skillbox Media

Дальше начнётся загрузка файла. Ждём, а затем открываем его:

Скриншот: Skillbox Media

Перетаскиваем в папку Applications — готово.

Скриншот: Skillbox Media

PyCharm установлена, можно создавать проекты и начинать программировать.

Вместо компилятора/интерпретатора CPython иногда используют альтернативные, написанные на других языках и лучше стыкующиеся с другими технологиями. Например, Jython и виртуальную машину JVM (для платформы Java). Или IronPython, написанный полностью на C# и предназначенный для .NET.

Бесплатный курс: «Быстрый старт в Python»
Начать учиться

  1. Use the py Command to Check if Python Is Installed on Windows

  2. Use the py --version Command to Check if Python Is Installed on Windows

  3. Use the where Command to Check if Python Is Installed on Windows

  4. Use Python IDLE to Check if Python Is Installed on Windows

  5. Use the Control Panel to Check if Python Is Installed on Windows

  6. Check Python Installation in Visual Studio Code

  7. Conclusion

How to Check if Python Is Installed on Windows

Python is one of the most popular programming languages in the world and can be installed on most operating systems, be it Mac, Linux, or Windows. The discussion for this article is restricted to only Windows devices, though.

Before diving into Python programming on a Windows system, it is essential to ensure that Python is properly installed. This tutorial will explore multiple ways to check if Python is installed on Windows.

Use the py Command to Check if Python Is Installed on Windows

When we execute the py command in the Windows Command Prompt, it first displays the details of the latest version installed on the computer and then runs/starts the installed version.

If we need to check if some version of Python, i.e., Python 2 or 3, is installed, we can do so using the following command.

For Python 2.x:

For Python 3.7:

If the specified version of Python is not installed, the command will first return the not found error and then return all the installed versions of Python by the py launcher.

check if python is installed - not found

And if the py launcher is not installed, the following error will be returned.

check if python is installed - not recognized

Use the py --version Command to Check if Python Is Installed on Windows

We can also check what version of Python 2 or 3 is installed using the following command.

The above command will return the latest version installed on the computer and will not start it. We can also check if some specific version of Python is installed in the following way.

check if python is installed using py version 2

It will return the latest version of Python 2 installed on the computer. If the Python version specified in the command is not installed, like the py command, it will return all the versions installed on the computer.

check if python is installed - not recognized

Use the where Command to Check if Python Is Installed on Windows

The Windows where command searches and displays files in a directory tree. This command searches for the given pattern in the current directory and the paths specified in the PATH environment variable.

The where command is handy for locating the multiple versions of the same command in the PATH environment variable. So, if we look for python using the where command, it will return the paths of all the copies of python.exe.

check if python is installed using where

The where command will return the following error if Python is not installed on the computer.

check if python is installed using where 2

Use Python IDLE to Check if Python Is Installed on Windows

Python IDLE (Integrated Development and Learning Environment) is a user-friendly Python shell that comes bundled with the Python installation package.

Follow these steps:

  • Open Python IDLE: Press the Windows key, type IDLE, and select the Python IDLE option from the search results.
  • Check Python Version: In the Python IDLE shell, click on the Help menu and select About IDLE. A window will appear, displaying the installed Python version.

  • Verify Python Interpreter: In the Python IDLE shell, you can directly run Python code by typing print('Hello, World!') and pressing Enter. If Python is installed correctly, it will display Hello, World! as the output.

    check if python is installed using idle 2

Use the Control Panel to Check if Python Is Installed on Windows

Windows provides a convenient way to check installed programs through the Control Panel.

Follow these steps:

  • Open the Control Panel: Press the Windows key, type Control Panel, and select the Control Panel option from the search results.

    check if python is installed using control panel

  • Navigate to Programs or Programs and Features: You may find the desired option under different names depending on your Windows version.

    check if python is installed using control panel 2

  • Locate Python: Look for Python or Python X.X in the list of installed programs. If Python is present, it means it is installed on your system.

    check if python is installed using control panel 3

Check Python Installation in Visual Studio Code

Visual Studio Code (VS Code) is a popular code editor that supports Python development. You can also check if Python is installed within the VS Code environment.

Follow these steps:

  • Launch the VS Code editor on your Windows system.
  • If you haven’t already, install the Python extension for Visual Studio Code by going to the Extensions view (Ctrl+Shift+X) and searching for Python.
  • With a Python file open in Visual Studio Code, click on the bottom left corner where it displays the selected interpreter. It will show the installed Python versions. If you see a valid Python interpreter, it indicates that Python is installed.

    check if python is installed using vscode

Conclusion

Ensuring the correct installation of Python is necessary before proceeding with the coding journey. This article provided a step-by-step guide on how to check if Python is installed using various methods, including the Command Prompt, Python IDLE, Control Panel, and Visual Studio Code.

By following these steps, you can confidently verify the presence of Python on your Windows machine, enabling you to harness the power of Python and embark on your coding journey.

Enjoying our tutorials? Subscribe to DelftStack on YouTube to support us in creating more high-quality video guides. Subscribe

How to Install Python on Windows

Before trying to run any Python program in your Windows operating system, you’ll need to check if you have Python installed and added to the environment’s path variable correctly.

In this article, I will show you how you can check whether you have Python installed successfully in your operating system or not. If not, then I will also show you how you can install it properly for Windows.

In this article, I am going to use Windows 11 as that’s the latest version of Microsoft Windows. But the same method is also applicable for the other versions of Windows as well. So without further ado let’s get started.

How to Check if You Have Python Installed in Your Windows Operating System

Open the CMD or PowerShell and check the version of Python by using this command:

python --version

Image

If you get the version of Python in the output like you see above, then your computer is perfectly okay for running any Python program. In your case, the version of Python might be different.

Image

But if you get this type of output that you see above, then it can mean any of the following:

  1. You did not have Python installed on your computer, or
  2. Python’s directory has not been added to the path of the Environment Variables.

For now let me assume that you do not have Python installed in your computer. Then I will also introduce you how you can add Python’s directory to the path of the Environment Variables later in this article.

First of all, we need to go to the official website of Python.

Image

Click on the Downloads section.

Image

Here you will get the latest version. Just click on the Download Python 3.10.2. By the time you are reading this article, Python might have been updated, in which case the version would be different. Simply download the version it shows you.

Keep in mind that here it will always show you the latest version of Python at the top.

Image

After downloading the file, we will get an executable file like this. Simply double click on that file and the installation wizard will open.

Image

Click on Customize installation.

Image

Make sure to check all of the boxes, like above. Then click Next.

Then you’ll see the below screen. If you want, then you can check all of the boxes. I do not need the debugging symbols and the debug binaries. So, I will not check the last two boxes.

Image

I would also recommend that you not change the location of the installation. Remember the install location as you might need that later. We are adding Python to the environment variables here directly.

Then click Install.

Image

Let the installation process finish up…

Image

If you get this type of prompt to disable the path length limit, then simply click on that box. It disables the path length limit by removing the limitation on the MAX_PATH variable.

Image

This change will not break anything, or make any negative changes. It will just allow Python to use long path names. It is recommended to disable the path length limit.

Image

The installation has been finished successfully.

How to Check the Python Version

Now we need to check again whether Python has been successfully installed and added to the path of the environment variables or not.

To check that, we need to open the CMD or the PowerShell. Then we need to apply the following command:

python --version

Image

Python has been installed and the path has also been added in the environment variables successfully!

How to Check the Path of the Environment Variables

If you want to check the path variables manually, then you have to open the Advanced System Settings. You can either search for Advanced System Settings, or you can open that from the Control Panel as well.

Image

If you search using the keyword Advanced system settings, you will get that directly here like this.

If you want to open that from the Control Panel, then, first of all, you need to open the control panel.

Image

Go to System and Security.

Image

Click on System.

Image

From here, click on Advanced System Settings.

Image

Click on Environment Variables.

Image

Click on Path and then click Edit.

Image

You will see that the root directory of Python310 and the scripts directory of Python310 have already been added in the installation process, as we checked the box to do these during the installation.

Image

If you wanted to do that manually, then you would need to copy and paste the two directories here by clicking New and pasting the two directories into two blank boxes (one box appears each time you click New). Then simply click on OK to all of the opened boxes and close all the opened windows.

I have also made a video where I show all of the processes mentioned above. If you want, then you can check the video here.

Conclusion

Thanks for reading the entire article. If it helps you then you can also check out other articles of mine at freeCodeCamp.

If you want to get in touch with me, then you can do so using Twitter, LinkedIn, and GitHub.

You can also SUBSCRIBE to my YouTube channel (Code With FahimFBA) if you want to learn various kinds of programming languages with a lot of practical examples regularly.

If you want to check out my highlights, then you can do so at my Polywork timeline.

You can also visit my website to learn more about me and what I’m working on.

Thanks a bunch!



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Перейти к содержанию

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

Содержание

  1. Введение
  2. Проверяем, установлен ли Python в Windows
  3. 1 способ
  4. 2 способ
  5. Заключение

Введение

В статье рассмотрим способы определить, установлен ли язык программирования Python на Операционной Системе Windows.

Проверяем, установлен ли Python в Windows

1 способ

Вне зависимости от того, выбирали ли Вы при установке путь, по которому будет установлен Python, определить его достаточно просто. Для этого можно открыть меню «Пуск» и ввести «python». Если же он есть на Вашем компьютере, то Windows найдёт его и покажет в списке.

Установлен ли Python в Windows

2 способ

Проверить присутствие Python в Windows также можно при помощи командной строки/PowerShell. Для этого можно нажать комбинацию клавиш win + R и в появившемся окне вписать «cmd».

Диалоговое окно «Выполнить»

После нажатия на «ОК»появится командная строка.

Командная строка

В ней нужно прописать python —version. Если Python присутствует в Вашей системе, то выведется его версия, если нет — то нет.

Проверка присутствия Python в Windows

Заключение

В ходе статьи мы с Вами научились определять, установлен ли язык программирования Python в Windows, а также узнавать его версию. Надеюсь Вам понравилась статья, желаю удачи и успехов! 🙂

In this tutorial, you’ll learn how to check your Python version in Windows, macOS, and Linux. You’ll learn how to check the version of Python using the command line and within a Python script itself. You’ll learn how to get the version number of the interpreter that your scripts will use.

Knowing how to do this is an important skill for any Python developer. For example, it can be an important skill in order to better troubleshoot your code. If your interpreter is set to a different version than you’re expecting (say, Python 2 versus Python 3), being able to identify the version of the interpreter can help troubleshoot your problems.

By the end of this tutorial, you’ll have learned:

  • How to check the Python version of your interpreter in Windows, Mac OS, and Linux
  • How the check the Python version while running your script
  • How to access the major, minor and micro versions of your Python version programmatically

Let’s get started!

Table of Contents

To check the version that your Python interpreter is running we can use a version command on the python command. Because accessing the command line prompt or terminal varies from system to system, this part of the tutorial is split across the different operating systems available to you.

Over the following sections, you’ll learn how to check your Python version using Windows 10, Windows 7, macOS, and Linux.

How to Check Your Python Version on Windows 10

In Windows 10, we can use the PowerShell to check the version of Python that we are running. In order to access the PowerShell, simply use the following steps:

  1. Press Windows + R
  2. Type powershell
  3. Press OK or hit enter

Once the PowerShell is open you can access the Python version your interpreter is running by writing the commands shown below.

Command Description Sample Output
python --version Shortened information about Python version Python 3.8.5
python -V Shortened information about Python version Python 3.8.5
python -VV Extended information about the Python version Python 3.8.5 (default, Sep  4 2020, 02:22:02) 
[Clang 10.0.0 ]
Different commands to check your Python version on Windows 10

How to Check Your Python Version on Windows 7

On Windows 7 and earlier, you can use the command prompt to check your Python version. In order to do this, you can run the following steps:

  1. Press Windows + R
  2. Type cmd
  3. Press OK or hit enter

Check the table below for the different types of commands you can run in order to check your version of Pyhton on Windows 7:

Command Description Sample Output
python --version Shortened information about Python version Python 3.8.5
python -V Shortened information about Python version Python 3.8.5
python -VV Extended information about the Python version Python 3.8.5 (default, Sep  4 2020, 02:22:02) 
[Clang 10.0.0 ]
Different commands to check your Python version on Windows 7

In the next section, you’ll learn how to check your Python version on macOS or Linux.

How to Check Your Python Version on macOS / Linux

In macOS and Linux you can use the Terminal application to check your version of Python. On macOS, this can be accomplished by following the steps below:

  1. Open Spotlight by hitting command + space
  2. Type in Terminal and hit enter

Because some versions of macOS come with Python 2 installed by default, it’s likely that the python command may refer to Python 2. Because of this, you may need to run python3 instead, to refer to that version of Python.

The table below breaks down the different commands to run on macOS and Linux to get the version of Python:

Command Description Sample Output
python3 --version Shortened information about Python version Python 3.8.5
python3 -V Shortened information about Python version Python 3.8.5
python3 -VV Extended information about the Python version Python 3.8.5 (default, Sep  4 2020, 02:22:02) 
[Clang 10.0.0 ]
python --version Shortened information about Python version Python 2.7.18
python -V Shortened information about Python version Python 2.7.18
Different commands to check your Python version on macOS and Linux

In the next sections, you’ll learn how to check the version of Python your code is running in your script using the sys and platform libraries.

How to Check Your Python Version in a Script Using sys

The sys library provides a number of different ways in which you can access the version of Python you’re running.

One of the simplest ways is to simply print out the .version attribute. This returns the same information as the -VV command shown above. Let’s take a look:

# Checking the Python Version Using the sys library
import sys
print(sys.version)

# Returns:
# 3.8.5 (default, Sep  4 2020, 02:22:02) 
# [Clang 10.0.0 ]

Because this returns a multi-line string, it’s not immediately accessible. For example, if you wanted to check whether or not a script is running in Python 3.6 or later (to make use of f-strings, for example), you’d have a hard time parsing this.

Instead of using the .version attribute, we can use the .python_version attribute to make this process better. It returns a named tuple that provides all the information in an easy to access manner.

The tuple returned has the following attributes: (major, minor, micro, releaselevel, serial). Let’s see how we can check the major and minor version to see if we can use Python f-strings:

# Checking the Python Version Number Programatically
import sys

if sys.version_info.major == 3 and sys.version_info.minor >= 6:
    print(f'You are running Python {sys.version_info.major}.{sys.version_info.minor}!')
else:
    print('Sadly, no f-strings!')

# Returns:
# You are running Python 3.8!

In the code above we checked if our system was capable of running Python f-strings. In the next section, you’ll learn how to use the platform library to check your Python version.

How to Check Your Python Version in a Script Using platform

The Python platform library provides a number of helpful methods that are very similar to the ones provided by the sys library. For example, the python_version() function can be used to return a string that contains the Python version.

Let’s see how we can import the library and return a string containing our current Python version:

# Checking Your Python Version with platform
import platform
print(platform.python_version())

# Returns: 3.8.5

Similar to the sys library, the platform library provides a way to extract a tuple. Unlike the sys library, the tuple that’s returned is not a named tuple and each item in the tuple is a string, not an integer. Let’s take a look at an example:

# Checking Your Python Version with platform
import platform
print(platform.python_version_tuple())

# Returns: ('3', '8', '5')

Conclusion

In this tutorial, you learned how to check your version of Python on Windows, macOS and Linux. You also learned how to check the version your code is running in your script using both the sys and platform library. Being able to check the version of Python you’re using allows you to better troubleshoot your code and identify any problems that are caused by versions.

Additional Resources

To learn more about related topics, check out the tutorials below:

  • Use Python to List Files in a Directory (Folder) with os and glob
  • How to Read a Text File in Python (Python open)
  • Python: Check if a File or Directory Exists
  • Python: Copy a File (4 Different Ways)
  • Python sys Official Documentation

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Журнал обновлений windows 10 2004
  • Не выключается монитор при бездействии windows 11
  • Canon mf4890dw драйвера windows 10
  • Как поставить gif на заставку windows 10
  • Windows 10 для офиса torrent