Как установить питон на windows 10 wing

Installing Wing

Installing Wing

Index of All Documentation
»
Wing Pro Reference Manual
»
Introduction
»

Before installing Wing, be sure that you have installed the necessary
prerequisites.
If you are upgrading from a previous version, see Upgrading first.

Note: The installation location for Wing is referred to as WINGHOME.
On macOS this is the name of Wing’s .app folder.

Windows

Install Wing by running the downloaded executable. Wing’s files are
installed by default in C:Program Files (x86)Wing Pro
9, but this location may be modified
during installation. Wing will also create a Settings Directory
in the location appropriate for your version of Windows. This is used to
store preferences and other settings.

The Windows installer supports a /silent command line option that uses
the default options, including removing any prior install of
Wing 9. If a prior install is
removed, a dialog with a progress bar will appear. You can also use a
/dir=<dir name> option to specify an alternate installation directory.

The /verysilent command line option has the same effect as /silent but also
prevents display of a progress bar.

For Wing Personal the default install directory is instead named
Wing Personal 9 and for Wing 101 it is
named Wing 101 9.

Linux

Use the RPM, Debian package, or tar file installer as appropriate for your
system type. Installation from packages is at
/usr/lib/wingpro9 or at the
selected location when installing from the tar file. Wing will also create a
Settings Directory in ~/.wingpro9, which
is used to store preferences and other settings.

Wing Pro, Wing Personal, and Wing 101 are also available in the Snapcraft Store.

For more information, see the Linux installation details.

For Wing Personal the install directory is instead named
wing-personal6 and for Wing 101 it is named wing-101-6.

macOS

On macOS, Wing is installed simply by opening the distributed disk image and dragging
to the Applications folder, and optionally from there to the task bar.

Установка интерпретатора Python

Windows

Скачайте инсталлятор по этой ссылке.

Запустите инсталлятор.

Mac OS

Скачайте инсталлятор по этой ссылке.

Установку необходимо производить в стандартную папку (не на диск C).

Для запуска инсталлятора наберите в консоли «python3».

Процесс установки аналогичен установке в Windows.

После запуска инсталлятора в первом окне выберите пункт меню Customize installation.

На следующем шаге нажмите Next.

На следующем экране изменить путь к программе на: «C:Python35».

Нажмите кнопку Install.

В последнем окне нажмите кнопку Close.

Интерпретатор Python 3 успешно установлен!

Установка Wing IDE

Windows

Скачайте инсталлятор по этой ссылке.

Запустите инсталлятор.

Mac OS

Скачайте инсталлятор по этой ссылке.

Для установки перетащите файл в папку «Программы».


Установка и настройка Wing IDE в Windows

При установке Wing IDE рекомендуем согласиться со всеми параметрами установки. Ничего изменять не требуется.

После установки рекомендуем вывести ярлык Wing IDE на рабочий стол.

Далее необходимо запустить Wing IDE и произвести настройки параметров.

При первом запуске необходимо согласиться с лицензионным соглашением, нажав на кнопку Accept:

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

  • Нажмите на пункт меню Edit -> Configure Python…

  • Произведите настройки так, как показано на рисунке.

    Выберите вариант Custom в первых 2-х настройках.

    Задайте пусть к интерпретатору Python, который вы установили.

    Нажмите на кнопку Insert. Задайте путь к папке с Python.

    Примените настройки, нажав на кноку OK.

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

  • Нажмите на пункт меню Edit -> Preferences…

  • Перейдите в раздел Files и задайте кодировку utf-8 как показано на рисунке:

  • Перейдите в раздел I/O и задайте кодировку utf-8:

  • Примените настройки, нажав на кнопку OK.

Настройка Wing IDE в Mac OS

При первом запуске Wing IDE необходимо согласиться с лицензионным соглашением, нажав на кнопку Accept.

Нажмите на пункт меню Edit -> Configure Python…

Произведите настройки так, как показано на рисунке.

Выберите вариант Custom в первой настройке.

Задайте пусть к интерпретатору Python, который вы установили.

Примените настройки, нажав на кноку OK.

Поздравляем, все готово для программирования на Python!

Начало работы в Python 3 и Wing IDE 101

О версиях Python

Сейчас существуют две основных ветки (версии) развития языка Python
(питон): Python 2 и Python 3. Версия 2 официально считается устаревшей
(поддержка версии 2 заканчивается в 2020 году), версия 3
— более новой и современной. Мы будем изучать именно версию 3. Версия 2
существенно отличается от версии 3, мы не будем обсуждать эти отличия.

В пределах как версии 2, так и версии 3 есть «подверсии», например,
последняя версия из третьей ветки сейчас (2020 г.) — версия 3.8.2 (не считая тех
версий, которые находятся еще в разработке). В принципе, для наших занятий можно
использовать более-менее любую версию питона из третьей ветки, лучше как
минимум 3.3, но если нет особенных причин, то устанавливайте последнюю
доступную вам версию.

Установка Python

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

Чтобы установить Python под Windows, скачайте программу установки со
странички курса или с официального сайта (http://python.org, через
пункт Downloads; убедитесь, что вы скачиваете питон третьей версии для
Windows). Установите Python с помощью этой программы, ничего сложного в
установщике нет. Полезно установить питон куда-нибудь в корень диска,
типа в C:Python3, а не в тот путь, который предлагается
установщиком по умолчанию. Для этого при установке надо выбрать пункт
типа Customize install и на одном из следующих экранов указать
конкретный путь.

Если вы работаете в другой операционной системе, то разберитесь, как
установить питон, самостоятельно. В Linux, например, питон есть в
репозиториях всех ведущих дистрибутивов, пакет обычно называется
python3 (а просто python — это питон второй версии).

Установка Wing IDE

Сам по себе питон — это только интерпретатор кода. Он запускает ваши программы,
но не содержит удобного редактора. Поэтому для написания программ
я советую вам использовать среду разработки (по сути, продвинутый редактор)
Wing IDE.

Wing IDE — это, к сожалению, не свободное ПО, но у него существует
официально бесплатная версия для образовательных целей, называется Wing
IDE 101. Она доступна как для Windows, так и для Linux и macOS.

Все программы для установки можно скачать с официального сайта Wing IDE
(http://wingware.com/, через пункт Download — Wing IDE 101);
установщик под Windows также можно скачать со странички курса.
Обратите внимание, что вам нужна именно версия 101, а не какая-нибудь другая!
Установите Wing IDE с помощью этого установщика, ничего сложного в нем
нет.

Wing IDE — это просто среда разработки (IDE) для Python, т.е. удобный
редактор программ, позволяющий легко запускать программы с помощью
питона (именно поэтому надо отдельно устанавливать сам Python — Wing IDE
его не включает в себя). В принципе, вы можете использовать и
какую-нибудь другую среду разработки, но тогда разбирайтесь с ней сами.
В частности, сам Python включает простенькую среду разработки Python
IDLE, ее описание вы можете встретить во многих книжках по Python, но
она слишком простая и потому не очень удобная. Так же есть популярная среда
PyCharm, но на мой вкус она слишком сложная.

Проверка установки

Запустите Wing IDE. Появится следующее окошко:

0_quick_start/wing_ide_0.png

Во-первых, убедитесь, что в правом нижнем углу, на панели, озаглавленной
Python Shell, появился текст, похожий на приведенный на рисунке; в
частности, там должна быть указана версия питона, которую вы
устанавливали. Убедитесь, что это версия 3 (на рисунке это версия
3.5.2). Если это не так, то попробуйте через меню Edit — Configure
Python указать путь к питону вручную (см. рисунок ниже) — в
пункте Python Executable надо указать что-нибудь типа
C:Python3python.exe, если вы установили питон в каталог
C:Python3, возможно, также в список Python Path надо добавить
C:Python3. Возможно, вам придется поэкспериментировать, чтобы найти
правильные настройки. Если у вас на компьютере установлены обе версии
питона (и 2, и 3), то, возможно, Wing IDE по умолчанию «подцепит» версию
2, тогда тоже вручную укажите, что вам надо работать с версией 3.

0_quick_start/wing_ide_config.png

Если у вас не получается, напишите мне [1], указав, куда вы установили
питон, и прислав скриншоты основного окна Wing IDE и диалога Edit —
Configure Python.

Первая программа

В основном меню Wing IDE выберите пункт File — New. Появится окно для
редактирования текста программы. В этом окне наберите следующий текст:

(Здесь " — это символ кавычек.)

Должно получиться так:

0_quick_start/wing_ide_1.png

Убедитесь, что опечаток нет. Сохраните программу: нажмите Ctrl-S или
выберите пункт меню File — Save As. Wing IDE предложит выбрать имя файла
для сохранения, для первой программы можно выбрать любое имя.

Note

Обратите внимание, что Wing IDE раскрашивает вашу программу.
Это делается для того, чтобы ее было удобнее читать; на самом деле
для питона цвет не важен, он сделан только для того, чтобы вам было
удобнее читать. Аналогично, в этом тексте код тоже раскрашен,
причем раскраска может быть немного другой (это просто обусловлено
системой, которую я использую для написания текста). Но еще раз:
цвета только для удобства чтения, никакой больше нагрузки они не несут,
в частности, Wing может раскрашивать не так, как вы видите в этом тексте,
это не страшно.

После этого запустите программу, нажав на кнопку с зеленым
треугольничком—стрелочкой на панели инструментов над текстом программы.
Результат выполнения программы появляется в правой нижней части экрана,
в панели «Python Shell» А именно, там вы можете увидеть один из двух
возможных результатов, показанных на двух рисунках ниже.

Если там появилась надпись «Test 4»:

0_quick_start/wing_ide_2.png

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

Если же там появился длинный текст со словами «Traceback» (в начале) и
«Error» (в конце):

0_quick_start/wing_ide_3.png

значит, в вашей программе есть ошибки. Подробнее про
ошибки ниже (раздел :ref:`sec:ce`), а пока, если вы увидели ошибку,
то просто внимательно проверьте, не ошиблись ли вы где-нибудь в наборе
программы.

Добейтесь того, чтобы ваша программа отработала успешно (внимательно
проверив, не допустили ли вы ошибок), и посмотрите, что же именно
пишется в этом окошке «Python Shell». Там, во-первых, виден заголовок
питона (включающий номер версии), дальше строка >>> [evaluate tmp.py]
(вместо tmp.py здесь будет имя файла, куда вы сохранили программу).
Эта строка была выведена в тот момент, когда Wing IDE начал запускать
вашу программу. И, наконец, есть строка Test 4, которую и
напечатала наша программа. Почему она напечатала именно это, обсудим
чуть ниже.

Позапускайте программу (зеленой стрелочкой) ещё несколько раз и
посмотрите на результаты. Вы увидите что, Wing IDE каждый раз печатает
строку evaluate... перед запуском программы, потом программа
печатает свою строку. Вывод программы перемешивается с выводом Wing IDE
— ничего страшного, это нормально.

Можно также запускать программу нажатием на кнопку с картинкой типа
красного жучка. Это немного другой режим запуска, более удобный для
поиска ошибок. Попробуйте позапускать и так, и так, посмотрите на
отличия (основное отличие пока — при запуске через «красного жучка»
вывод предыдущих программ затирается).

Ошибки в программе

В вашей программе могут быть серьёзные ошибки —
такие, что питон «не понимает», что вы от него хотите (а могут быть и не
столь серьёзные — программа отработает как бы нормально, но выдаст
неверный результат). В случае таких серьезных ошибок питон выдаст
сообщение, похожее на сообщение, показанное на рисунке выше. Оно обычно
начинается со слова Traceback, а ближе к концу в нем есть слово Error.

С ошибками удобнее разбираться, запуская программу в режиме «красного
жучка». В таком случае Wing IDE подсвечивает строку около ошибки
красным, а подробную информацию пишет в особом окошке справа.

Пока для вас важным будет то, какую строку Wing IDE подсветила красным —
примерно в том месте и ошибка. Важен также текст («сообщение об
ошибке»), обычно содержащий слово «Error» (в примере на рисунке
Syntax Error ...), там же рядом указан и номер строки с
ошибкой (line 1). Поначалу сообщения об ошибке сложно понимать,
но со временем вы выучите наиболее часто встречающиеся и будете сразу
понимать, что не так.

А пока посмотрите внимательно на строчку с ошибкой (при запуске через жучка
питон подсвечивает ее красным, при запуске через стрелочку — только пишет номер строки),
и на строчки рядом — и попробуйте
понять, что там не так. В примере на рисунке я забыл вторую цифру 2 (в
результате чего питону стало непонятно, на что надо умножать). (В
примере на рисунке я запускал программу через зеленую стрелочку, а не
через «красного жучка», поэтому там нет подсвеченной красным строки.)

Имейте в виду, что питон не телепат и не может точно определить, где вы
допустили ошибку. Он подсвечивает красным ту строку, где текст программы
впервые разошёлся с правилами языка. Поэтому бывает, что на самом деле
ваша ошибка чуть выше, чем подсвеченная строка (а иногда — и намного
выше). Но тем не менее место, которое выделил питон, обычно бывает
полезно при поиске ошибки.

Попробуйте в своей программе поделать разные ошибки и посмотрите, как на
них отреагирует питон.

Как работает эта программа

Давайте разберём, как эта программа работает. Напомню её текст:

Вообще, любая программа — это, в первую очередь, последовательность
команд, которые программист даёт компьютеру, а компьютер будет
последовательно их выполнять.

В нашей программе одна команда — print("Test", 2*2). Команда
print обозначает «вывести на экран» (английское слово «print»
обозначает «печатать»). В скобках после слова print указываются, как
говорят, аргументы команды. Они разделяются запятыми, в данном случае
у команды два аргумента: первый — "Test", и второй — 2*2.

Если аргументом команды print является некоторая строка, заключённая
в кавычки (символы "), то команда print выводит эту строку на
экран как есть (без кавычек). Поэтому первым делом наша команда выводит
на экран текст Test.

Вторым аргументом команды print в нашем примере является
арифметическое выражение 2*2. Если аргументом команды (любой
команды, не обязательно именно print, просто других мы пока не
знаем) является арифметические выражение, то компьютер сначала вычислит
его, а потом передаст команде. Поэтому в данном случае сначала компьютер
вычислит 2cdot 2, получит 4, а потом передаст результат команде
print, которая выведет его на экран.

Команда print разделяет выводимые элементы пробелами, поэтому между
Test и 4 выведен пробел.

В итоге получается, что наша программа выводит Test 4.

Использование питона как калькулятора

Таким образом можно использовать питон как калькулятор. Например, если
надо посчитать значение выражения 7+3cdot(8-2), то можно
написать команду print(7+3*(8-2)), после чего запустить программу —
и на экран будет выведен результат. Обратите внимание, что скобки
учтутся корректно и порядок действий будет правильный. Две скобки в
конце команды — это одна является частью выражения, а вторая заканчивает
список аргументов команды print.

В выражениях можно использовать следующие операторы:

  • + и - — сложение и вычитание (в том числе то, что называется
    унарный минус для записи отрицательных чисел: чтобы написать
    2cdot(-4), надо написать 2*(-4));
  • * — умножение;
  • / — деление («честное», например, 5/2=2.5);
  • // (это два символа / подряд) — неполное частное (см. ниже);
  • % ­— остаток (см. ниже).
  • Скобки (только круглые) работают для группировки операций, можно
    использовать вложенные скобки, например, 2*(3-(4+6)).

Чуть подробнее про деления. Есть три оператора, связанных с делением:
один оператор для честного деления (/), и два оператора для деления с остатком
(// и %). Вспомните младшие классы и деление с остатком: 16 разделить
на 3 будет 5 («неполное частное») и в остатке 1. Вот // вычисляет
неполное частное, а % — остаток. Пишется так: 16 // 3 и
16 % 3, как будто // и % — это символ операции, а-ля плюс
или звёздочка. (Пробелы вокруг // и % не обязательны, но на
питоне так принято.) (При работе с отрицательными числами результат
может показаться вам неожиданным, но это мы обсудим потом.)

Кроме того, есть так называемые функции:

  • Запись abs(-3) обозначает взятие числа по модулю: |{-}3|.
    Обратите внимание: пишется сначала имя функции (в данном случае
    abs), а потом в скобках — от чего взять эту функцию (от чего
    взять модуль в данном случае). То, что в скобках, аналогично командам
    называется аргументом функции.

  • Аналогично, запись sqrt(4) обозначает взятие квадратного корня
    (если не знаете, что это такое, то пока пропустите этот пункт), но,
    поскольку эта операция бывает нужна несколько реже, то чтобы ее
    использовать, в начале программы надо написать магическую строку
    from math import *. Программа получается, например, такая:

    from math import *
    print(sqrt(4))

Все эти операции можно комбинировать. Например, команда
print( (20 * 3) + sqrt( 2 + abs(5 - 7) ) ) выведет на экран значение
выражения 20cdot 3 + sqrt{2+|5-7|}. Пробелы в команде
поставлены, чтобы проще было читать; вообще, в питоне пробелы можно
ставить в любом разумном месте (внутри названий команд и чисел нельзя,
но около скобок, знаков препинания и прочих символов можно), но
рекомендуется ставить их как минимум вокруг знаков действий.

В одной программе можно вычислять несколько выражений. Например,
программа

print(2 * 2, 2 + 2)
print(3 * 3)

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

Можно также, как мы видели раньше, смешивать текст (в кавычках) и выражения:

print("Дважды два равно", 2 * 2, ".")

Простейший ввод и вывод. Переменные

Но не очень интересно писать программы, которые всегда выводят одно и то
же. Хочется, чтобы программа что-нибудь запрашивала у пользователя, и
работала с учётом того, что пользователь ввёл. Давайте, например,
напишем программу, которая будет спрашивать у пользователя два числа и
выводить на экран их сумму.

Но для этого нам придётся научиться ещё одной важной вещи. Когда
пользователь вводит два числа, программе надо их как-то запомнить, чтобы
потом сложить между собой и результат вывести на экран. Для этого у
компьютера есть память (оперативная память). Программа может
использовать эту память и положить туда числа, введённые пользователем.
А потом посмотреть, что там лежит, сложить эти два числа, и вывести на
экран.

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

a = input()
print("Вы ввели ", a, "!")

Прежде чем мы разберем, что обозначают все эти команды, наберите эту
программу и попробуйте ее запустить. Сначала запустите «зеленой
стрелочкой». В окошке Python Shell появится надпись
[evaluate ...], после чего будет моргать курсор, а наверху
этого окошка будет надпись «Waiting for keyboard input», что обозначает
«Ожидаем ввод с клавиатуры». Введите что-нибудь в этом окошке и нажмите
Enter. Вы тут же увидите, что то, что вы ввели, вывелось еще одной
строчкой на экран, с дополнительными словами («Вы ввели»), с дополнительными
пробелами и восклицательным знаком. Именно это и делает программа: она выводит на экран то, что
вы ей вводите, добавив еще текст.

Если вы запустите программу «красным жучком», то все будет аналогично,
только текст вам надо будет вводить в пустом окошке «Debug I/O», которое
появится на месте окошка «Python Shell».

Теперь разберем, как эта программа работает.

Команда input() обозначает «подожди, пока пользователь введет
что-нибудь с клавиатуры, и запомни то, что он ввел». Но просто так
попросить «запомнить» довольно бессмысленно, нам ведь потом надо будет
как-то сказать компьютеру, чтобы он вспомнил то, что он запомнил.
Поэтому мы пишем a = input(). Это обозначает «запомни то, что ввел
пользователь, в памяти, и дальше это место в памяти мы будем называть
буквой a». Соответственно, команда print(a) обозначает
«посмотри, что лежит в памяти, называемой буквой a, и выведи это на
экран», а команда print("Вы ввели ", a, "!") обозначает «выведи сначала
фразу Вы ввели, потом то, что лежит в a, потом восклицательный знак,
и раздели это все пробелами».

Обратите внимание, что a написано без кавычек.
Если бы мы написали print("Вы ввели ", "a", "!"), то питон бы
вывел просто букву a (ну и весь остальной текст), он не понял бы,
что надо вывести то, что лежит в памяти a.

Вот такие «места в памяти» называются переменные. Т.е. говорят:
«переменная a». Говорят: в первой строке мы считали, что ввел
пользователь с клавиатуры, и записали это в переменную a, а во
второй строке мы прочитали, что записано в переменной a, и вывели
это на экран.

В программе можно заводить несколько переменных. Простейший вариант
может выглядеть так:

a = input()
b = input()
print(b, a)

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

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

a = input()
b = input()
print(a + b)

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

Чтобы объяснить, что вы имеете в виду числа, надо написать так:

a = int(input())
b = int(input())
print(a + b)

Мы используем новую команду (точнее, функцию) — int. Она обозначает:
возьми то, что получилось у команды input() (т.е. ту строку, которую
вводит пользователь), и преврати это в число. Пока это не надо до конца
осознавать, просто запомните, что, чтобы считать одно число, надо
написать ... = int(input()), где на место многоточия надо подставить
имя той переменной, куда надо записать результат.

Запустите эту программу. В окошке ввода наберите какое-нибудь число,
нажмите Enter, наберите второе число и еще раз нажмите Enter. Вы
увидете, что программа вывела их сумму.

Если вы этой программе попытаетесь ввести два числа на одной строке
(т.е. введете «2 пробел 3 Enter»), то программа выдаст ошибку. Еще бы:
вы пропросили строку «2 3» превратить в число (в одно!) и
записать в переменную a, но ведь это не есть верная запись одного
числа.

Чтобы вводить числа через пробел, надо использовать другую конструкцию:

a, b = map(int, input().split())

Это пока магия, ее придется запомнить наизусть. Потом вы поймете, что
здесь что значит. Обратите внимание, что после слова int тут нет
скобок, а вот после input и split есть.

Так можно вводить сколько угодно чисел; например, чтобы считать четыре
числа, вводимые в одной строке, надо написать

a, b, c, d = map(int, input().split())

Переменные не обязательно называть a и b, можно использовать
более-менее любые строки из английских букв и цифр (есть некоторые исключения,
но пока это не так важно); например, можно было назвать переменные
first и second, или x1 и x2 и т.п. Конечно, переменных можно делать столько,
сколько вам понадобится; вообще, переменные — это основная вещь, с
которой работают программы.

Ещё несколько замечаний по нашей программе. Во-первых, программа не
вывела на экран никаких «приглашений» типа «Введите a и b». Питон ничего
за вас делать не будет; если вы хотите, чтобы программа вывела это на
экран, то так и сделайте: print("Введите a и b"). Но мы не будем
выводить такие приглашения в наших программах, мы будем считать, что
пользователь сам знает, что от него требуется. В задачах, которые вы
будете решать, будет чётко написано, что надо вывести на экран — и
ничего лишнего выводиться не должно.

Присваивания

Пока мы умеем записывать в переменные только то, что пользователь ввел с
клавиатуры. На самом деле, намного чаще приходится записывать в
переменные значения, которые программа сама вычисляет. Для этого есть
специальная команда, которая называется присваивание (и на самом деле
мы ее уже видели):

обозначает «в переменную a записать 10».

Справа от знака «равно» можно писать любые выражения (например,
a = 10 + abs(5 - 9)). Более того, там же можно использовать другие
переменные, в которые уже что-то записано. Например, программа

a = 20
b = a + 10
print(b)

выведет на экран 30, потому что сначала в a записывается 20, потом
компьютер смотрит, что записано в a, прибавляет 10, и результат
записывает в b, потом смотрит, что записано в b, и выводит на
экран.

Если в переменной уже было что-то записано, то после присваивания старое
значение затирается:

в результате в a лежит 30, а про 20 все забыли.

Особый интересный вариант — справа можно упоминать ту же переменную,
которая стоит слева — тогда будет использоваться ее предыдущее значение:

обозначает «в a запиши 20. Потом посмотри, что записано в a,
прибавь к этому 10 и то, что получится, запиши обратно в a». В
итоге в a будет записано 30.

Та команда a = input(), которую мы раньше видели, на самом деле тоже
является присваиванием: она говорит: «прочитай то, что пользователь ввел
с клавиатуры, и запиши это в a».

Слева от знака «равно» можно указывать несколько переменных через
запятую. Тогда справа тоже должно быть несколько значений через запятую
(или специальные функции типа уже упоминавшейся map, но их мы
подробнее пока обсуждать не будем):

обозначает «в a записать 10, а в b — 20».

Запись a = 10 читается «переменной a присвоить 10», или кратко «a присвоить 10».
Не надо говорить «a равно 10», т.к. «равно» — это не глагол, и не понятно,
какое действие совершается. Более того, если запись a = a + 1
прочитать с «равно», то получается «a равно a плюс один», что
никак не похоже на команду, а скорее на уравнение, которое не имеет
решений. Поэтому говорите «присвоить», а не «равно».

Есть еще ряд полезных команд, которые совмещают арифметическое действие
и присваивание. Например, запись a += 10 обозначает a = a + 10
(«увеличить a на 10»). Аналогично можно поступать с остальными
арифметическими действиями: a /= 5 обозначает a = a / 5,
a %= 5 обозначает a = a % 5, и т.п.

Комментарии

(Эта информация вам прямо сейчас не нужна, но будет полезна при чтении дальнейших разделов.)

В программе можно оставлять так называемые комментарии. А именно, если где-то в программе
встречается символ «решетка» (#), то этот символ и все, что идет за ним до конца строки,
полностью игнорируется питоном. Таким образом можно в программе оставлять пометки для себя,
или для других программистов, которые будут читать вашу программу. Например

a = int(input())  # считали число

Здесь запись # считали число полностью игнорируется питоном, как будто этих символов нет вообще,
а запись a = int(input()) работает как и должна.

В частности, решетка может стоять в начале строки, тогда вся эта строка будет игнорироваться:

# для начала, считаем число
a = int(input())

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

Язык программирования как конструктор

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

Примеры решения задач

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

.. task::
    Вася купил :math:`N` булочек, а Маша — на :math:`K` булочек больше.
    Сколько всего булочек купили ребята?

    **Входные данные**: На первой строке входных данных вводится одно число :math:`N`, на второй — одно число :math:`K`.

    **Входные данные**: Выведите одно число — ответ на задачу.

    **Пример**:

    Входные данные::

        4
        2

    Выходные данные::

        10
    |
    |
    |

Ну, во-первых, надо считать данные. Два числа вводятся на двух отдельных строчках, поэтому
они считываются так:

n = int(input())
k = int(input())

Дальше надо понять, по какой формуле вычисляется ответ. В этой задаче несложно догадаться, что ответ равен 2cdot N + K.
Так и выводим:

Полная программа получается такая:

n = int(input())
k = int(input())
print(2 * n + k)

Можно было поступить и по-другому: можно было, считав данные, сначала отдельно посчитать, сколько булочек купила Маша:

после чего вывести ответ как сумму n и m:

n = int(input())
k = int(input())
m = n + k
print(n + m)

Еще один альтернативный вариант — сохранить ответ в переменную, и только потом ее выводить, например, так:

n = int(input())
k = int(input())
ans = 2 * n + k
print(ans)

Все эти варианты правильные, и несложно придумать еще ряд правильных вариантов.

.. task::
    С начала суток прошло :math:`N` минут. Определите, сколько часов и минут будут показывать электронные часы в этот момент.
    Гарантируется, что :math:`N` меньше 1440, т.е. что прошло меньше полных суток.

    **Входные данные**: Вводится целое число :math:`N`.

    **Входные данные**: Выведите ответ на задачу.

    **Пример**:

    Входные данные::

        150

    Выходные данные::

        2 30
    |
    |
    |

Тут, опять-таки, надо придумать, какой математической формулой решается задача.
Если с ходу не очевидно, то подумайте: как бы вы сами решали задачу для конкретного ввода?
Вот прошло с начала суток, например, 150 минут — как понять, сколько это часов и сколько минут?

Если немного подумать, то становится понятно, что надо N разделить с остатком на 60 (количество минут в часе),
после чего неполное частное будет как раз количеством часов, а остаток — количеством минут.
Соответственно пишем программу:

n = int(input())
print(n // 60, n % 60)

Также, как и в прошлой задаче, можно было ответы сохранить в переменные при желании.

.. task::
    Маше надо купить :math:`A` больших бусин, :math:`B` средних и :math:`C` маленьких.
    Одна большая бусина стоит :math:`X` рублей, средняя — :math:`Y` рублей, маленькая — :math:`Z` рублей.
    Сколько всего рублей придется потратить Маше?

    **Входные данные**: На первой строке вводятся три числа :math:`A`, :math:`B` и :math:`C`.
    На второй строке вводятся три числа :math:`X`, :math:`Y` и :math:`Z`.

    **Входные данные**: Выведите одно число — сколько рублей придется потратить Маше.

    **Пример**:

    Входные данные::

        3 2 1
        6 5 4

    Выходные данные::

        32
    |
    |
    |

Очевидно, что ответ на задачу равен Acdot X + Bcdot Y + Ccdot Z.
Осталось аккуратно ввести и вывести данные. Тут задаются две строки по три числа,
поэтому вводить данные надо два раза через map(int(...:

a, b, c = map(int, input().split())
x, y, z = map(int, input().split())
print(a * x + b * y + c * z)
.. task::
   Машина едет со скоростью :math:`N` километров в час. Выведите эту информацию по-английский
   по образцу: «The speed is :math:`N` kmph.», подставив вместо :math:`N` введенное число (см. пример).

    **Входные данные**: Вводится одно число :math:`N`.

    **Входные данные**: Выведите строку.

    **Пример**:

    Входные данные::

        55

    Выходные данные:

    .. code-block:: text

        The speed is 55 kmph.
    |
    |
    |

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

n = int(input())
print("The speed is", n, "kmph.")

Что дальше?

(Естественно, это раздел только для учеников моего курса.)

Во-первых, если вы еще этого не сделали, прочитайте на страничке курса
все тексты в «шапке» курса, особенно раздел «Работа с сайтом…», после
чего начинайте решать «Задачи на арифметические операторы». И двигайтесь
дальше.

Внимание! Не надо прямо сейчас читать следующие разделы этого текста,
не надо нажимать кнопку «Next» ниже. Дальше идет теория для следующих тем,
поэтому сначала прорешайте задачи на арифметические операции на сайте,
потом уже переходите к следующим темам (по ссылкам на сайте).

И по любым вопросам пишите мне.

[1] Конечно, предложения «написать мне» относятся только к ученикам моего курса.

Wing Pro Quick Start Guide

Index of All Documentation
»

Wing Pro Screenshot

«The best Python IDE. And I have tried them all!»
— Ahmed Ali

This is a minimalist guide for getting started quickly with Wing Pro. For a more
in-depth introduction, try the Tutorial.

Wing Pro is a light-weight yet powerful integrated development environment that was
designed from the ground up for Python. Once you’re up to speed with Wing you should find
that:

  • Wing speeds up your development of new code
  • Wing makes it easier to understand and work with existing code
  • Wing reveals errors earlier in the development process
  • Wing makes it easier to find and fix bugs
  • Wing adapts to your needs and style

This is made possible through deep code analysis (both static and runtime), a focus
on interactive development in the live runtime, high-level editing operations and
refactoring, continuous early error detection, support for test-driven development,
powerful always-on debugger, seamless support for remote and containerized development,
and extreme configurability.

Let’s get started with Wing Pro!

Install Python

If you don’t already have Python on your system, install it now. Two good options are:

  • Obtain the standard Python distribution from python.org
  • Use Anaconda for seamless access to many third party
    Python libraries. See Anaconda package lists for a list of the available
    libraries.

See Supported Python Versions for other
options.

Start Wing

Wing can be launched from the start menu on Windows, by double clicking on the application
on macOS, or with wing9.0 on Linux. In Wing Personal the executable is
instead named wing-personal9 and in Wing 101 it is
named wing-101-9.

For more information, see Running Wing.

Wing Pro requires a license to run. If you don’t have a license, you can obtain a 30-day
trial the first time you start it. Wing Personal and Wing 101 are free to run without
a license.

Once Wing is running, you should switch to using the

Quick Start Guide

listed in
Wing’s

Help

menu because it contains links directly into the IDE’s functionality.
That copy also omits features not available in your selected product level.

Set up a Project

After Wing is running, select New Project from the Project menu to create a new
project. This dialog lets you choose or create the source directory and choose or create
the Python environment you want to use for your new project. When creating a new
source directory, you can optionally pull a revision control repository into it. Wing Pro can
also create and install packages into new virtualenv, pipenv, Anaconda env, and Docker container
environments.

If you choose Create Blank Project, you can configure your project later with the
following steps:

  • Use Add Existing Directory in the Project menu to add your sources to the
    project. It’s best to constrain this to the directories you are actively working with
    and let Wing find the libraries you use through the Python Path.
  • Use Project Properties in the Project menu to set Python Executable to the
    python.exe or other interpreter executable you want to use with your project. If
    Python is not on the PATH, set this to the the full path that is in
    sys.executable in the desired Python installation.
  • If your code alters sys.path or loads modules in a non-standard way then you may
    need to set Python Path in Project Properties so that Wing can find your
    modules for auto-completion, refactoring, debugging, testing, and other features.
  • You may want to right-click on your main entry point in the Project tool and select
    Set As Main Entry Point so that debugging always starts there.
  • Use Save Project As in the Project menu to save your project to disk.
  • Use the Packages tool in the Tools menu to manage Python packages in
    your selected Python environment.

See Project-Wide Properties and Per-File
Properties for a description of all available
properties.

Notice that Wing also offers other project types in the New Project dialog, including
one for connecting to a remote host via SSH, running with
Docker or other containers, accessing a
Vagrant instance, working with Windows Subsystem for Linux, and a project type for each of the frameworks, tools, and libraries
listed in How-Tos.

Wing may consume significant CPU time when it first analyzes your code base. Progress is
indicated in the lower left of the IDE window. Once this is done, the results are cached
across sessions and Wing should run with a snappy and responsive interface. See Source
Code Analysis to learn how Wing’s source analysis
system works.

Wing 101 does not have projects. Configuring the Python environment is instead
done with Configure Python in the Edit menu.

Basic Configuration

You are now ready to start working with code, but may want to make a few
configuration changes first:

Display Colors — The User Interface > Display Mode preference selects whether Wing
runs with a light or dark display style. This is also available in the high-level
configuration menu in the top right of Wing’s window. The specific styles used are
selected with the User Interface > Light Theme and User Interface >
Dark Theme preferences.
The editor’s colors can be configured separately with the User Interface > Light Editor and User Interface >
Dark Editor preference.

Key Bindings — Wing can emulate VI/Vim, Visual Studio, Emacs, Eclipse, XCode, MATLAB,
and Brief editors, as selected from Keyboard Personality in the Edit menu or with
the User Interface > Keyboard > Personality preference.

Tab Key — The default tab key action depends on the selected keyboard personality and
in some cases file type, context, and whether or not there is a selection in the editor.
This can be changed from the User Interface > Keyboard > Tab Key Action preference.

Completion Keys — By default, the auto-completer uses the Tab key for completion,
but other keys can be added using the Editor > Auto-completion > Completion Keys preference.

There are many other options in Preferences.

Navigating Code

Wing Pro provides a number of different ways to navigate the structure of your
code, and several methods for quickly finding symbols or files by name:

Source Index menus at the top of the editor provide quick access to other parts of a
source file.

Goto-definition is available from the Source menu, and by right-clicking on
symbols in the
editor, Python Shell and Debug Console.
Use the forward/back history buttons at the top left of the editor to return from the
point of definition.

Find Points of Use in Wing Pro’s Source menu shows where the current symbol is
being used. This distinguishes between separate but like-named symbols.

Find Symbol in the Source menu in Wing Pro and Wing Personal jumps to a symbol
defined in the current file when you type a fragment of its name.

Find Symbol in Project in the Source menu in Wing Pro works the same way but
searches all files in the project.

Open From Project in the File menu in Wing Pro and Wing Personal provides a
similar interface for quickly opening project files.

See Navigating Source for details on the above.

Source Browser in the Tools menu in Wing Pro and Wing Personal provides module or
class oriented display of the structure of your code. Details

Source Assistant in the Tools menu shows detailed information about symbols
selected in the editor, auto-completer, Source Browser,
Python Shell, Project,
and other tools. Details

Searching

Wing Pro provides several different interfaces for searching your code. Which you
use depends on what you want to search and how you prefer to interact with the search and
replace functionality:

Toolbar search is a quick way to search the current file. Details

Search in the Tools menu shows the Search tool, which provides incremental text, wildcard,
and regular expression search and replace in selections and the current file or
documentation page. Details

Mini-search in Wing Pro and Wing Personal provides powerful keyboard-driven search
and replace. The key bindings listed in the Mini-search area of the Edit menu
display the search entry area at the bottom of the window. Details

Search in Files in the Tools menu in Wing Pro and Wing Personal shows the
Search in Files tool, which provides wildcard
and regular expression search and replace in filtered sets of files, directories, named
file sets, and within the project and documentation. Details.

Editing Code

Wing Pro’s editor is designed to speed up the process of writing and modifying
Python code, and to reduce the incidence of coding errors. Its features include:

Auto-completion in Wing’s
editor, Python Shell and Debug Console
speeds up typing and reduces coding errors. The auto-completer uses Tab by default for
completion, but this can be changed in the Editor > Auto-completion > Completion Keys preference. This
feature is disabled by default in Wing 101. Details

Auto-indent in Wing Pro and Wing Personal matches the file’s existing indentation.
When multiple lines are pasted, they are re-indented according to context. A single
Undo reverts an unwanted indentation change. A selected range of code may be
re-indented as a block using Indentation in the Source menu or the indentation
toolbar group. The Indentation tool may be used to convert
a whole file’s indentation style. Details

Auto-Editing in Wing Pro implements a range of operations such as auto-entering
closing parentheses, brackets, braces, and quotes. Among other things, Wing also
auto-enters invocation arguments, manages new blocks with the : key, and corrects
out-of-order typing. Auto-editing operations can be enabled and disabled in the Editor >
Auto-editing
preferences group. The default set includes those operations that don’t affect finger
memory. The others are well worth learning. Details

Refactoring operations in Wing Pro, accessed from the Refactoring menu, implement
automated renaming and moving of symbols, creating functions or methods out of existing
code, and introducing variables much more quickly than by manually editing code. Details

Multiple Selections can be made with Multiple Selections in the Edit menu, the
multiple selections toolbar item, and by pressing Ctrl+Alt (or Command+Option on
macOS) while making a selection with the mouse. Once multiple selections have been made,
edits made will be applied to all the selections at once. Details

Code Warnings are shown in Wing Pro for syntax errors, indentation problems,
unreachable code, use of undefined variables and attributes, unresolvable imports, and
some other problems. External checkers like flake8, mypy, pep8, and pylint may also be configured
as sources for the code warnings. Warnings are shown on the editor with details shown
in a tooltip when the mouse hovers over the warning indicator. Warnings can be navigated
from the warnings menu in the top right of the editor and managed from the Code Warnings tool. Details

Snippets in Wing Pro are included in Wing’s auto-completer as a quick way to enter
commonly repeated patterns for coding standards, documentation, testing, and so forth.
Data entry for snippet arguments is inline in the editor. Use the Tab key to move
between the fields. Edit or add snippets in the Snippets
tool. Details

Turbo Completion in Wing Pro is an optional auto-completion mode for Python, made
possible by Wing’s powerful source analysis engine. When the Editor > Auto-completion >
Python Turbo Mode
preference is enabled, Wing turns every non-symbol key into a completion key in contexts
where a new symbol name is not being typed. Details

Quick Selection operations in the Edit > Select menu allow selecting whole
statements, blocks, or scopes before copying, editing, or searching through them. Details

Debugging Code

Wing’s debugger is a powerful tool for finding and fixing bugs, understanding unfamiliar
code, and writing new code interactively. You can launch code from the Debug menu or
toolbar, from the Python Shell, or from outside of the IDE
either on the same machine or on
another host. Wing also supports working with code running
on containers like those provided by Docker.

Breakpoints can be set by clicking on the breakpoint
margin to the left of the editor. Stepping operations are in
the Debug menu and toolbar.

The Stack Data tool is used to inspect or change
program data.
Right-click on items to display the item as an array or in textual form.
Hovering the mouse over a symbol in the editor shows the value
for that symbol in a tooltip, if available on the active debug stack.
Pressing Shift-Space shows tooltips for all symbols visible in the editor.

Debug process I/O is shown in the Debug I/O tool, or
optionally in an external console.

Other debugger features include:

Interactive Debugging is supported by Wing Pro’s Debug Console, which provides a Python prompt that executes code in
the current debug stack frame. When the debugger is paused, Wing also uses the live
runtime state to populate the auto-completer in the editor, Source Assistant, goto-definition, and other tools. Details

Conditional Breakpoints can be used in Wing Pro to isolate and understand complex bugs
by stopping before they occur. Using a conditional breakpoint to isolate a broken case and
the Debug Console to design a fix is far more productive
than relaunching code repeatedly. Details

Move Program Counter is supported by Wing Pro, by right-clicking in the editor and
selecting Move Program Counter Here. Because of how Python is implemented, this
feature works only in the innermost stack frame and it does not work when the debugger is
stopped on an exception.

Watching Values in Wing Pro by right-clicking on the editor or any of the data views
tracks values over time by symbolic name or object reference in the Watch tool. Expressions can be also be watched.
Details

Launch Configurations in the Project menu in Wing Pro and Wing Personal
define different runtime environments for debugging, executing, and unit testing your
code. Details.

Named Entry Points in the Debug menu in Wing Pro and Wing Personal provide a way
to launch the same file with different debug environments. Details

Other Features

Wing Pro includes a number of other features designed to make Python coding
easier and more productive:

Python Shell — Wing’s Python Shell lets you try
out code in an independent sandbox process. To enable debugging, click the bug icon in the
top right of the Python Shell.
In Wing Pro and Wing Personal, the shell provides auto-completion, goto-definition, and is
integrated with the Source Assistant.
Details

Unit Testing in Wing Pro’s Testing tool works with
unittest, doctest, pytest, nose, and Django unit tests. You can run tests suites, view the
results, and debug tests. Details

Version Control in Wing Pro supports revision control with Mercurial, Git, Subversion,
Perforce, Bazaar, and CVS. Wing auto-detects which systems are used in your project and
shows the appropriate additional menus and tools in the Tools menu. Details.

Difference and Merge in the Source menu can be used to compare and merge files and
directories on disk, files open in the IDE, an unsaved buffer with disk, and a working
copy with its revision control repository. Details

Remote Development is easy in Wing Pro, to remote hosts, virtual machines, or
containers that are accessible via SSH. In this model of
remote development, Wing works seamlessly and securely with files stored entirely on the
remote host. Use the Remote Hosts item in the Project menu to configure a remote
host, then set the Python Executable in Project Properties to that remote host,
and use Add Existing Directory in the Project menu to add your remote directories
to the project. Wing can edit, debug, test, search, inspect, and manage files, run the
Python Shell, and execute OS Commands on the remote host in the same way as it does when
working locally. Details

Package management is available for virtualenv and pipenv, using the Packages
tool in the Tools menu. This can be used to install, remove, and manage the
packages that are installed into your project’s Python environment. Details.

Containers like those provided by Docker are also supported.
In this development model, files are stored locally but code is run inside a
containerized environment. Details
OS Commands in the Tools menu in Wing Pro and Wing Personal’s displays the OS
Commands tool, which execute external tools for build,
code generation, and other purposes. Details.

Preferences in the Edit menu (or WingPro menu on macOS) gives you
control of the overall layout and color of the IDE, among many other options. Right click
on tool and editor tabs for layout options, or drag tabs to move them or create new
splits. Right-click on the toolbar to configure which tools are visible or to add your
own. See Customization for details.

Perspectives in Wing Pro and Wing Personal let you save named tool panel layouts.
Details.

Other Features like bookmarks, code folding, keyboard macros are also available,
and you can extend Wing by writing Python scripts.

Further Reading

As you work with Wing Pro on your own software development projects, the following
resources may be useful:

  • Wing Support Website which includes a Q&A support
    forum, mailing lists, documentation, links to social media, and other information
    for Wing users.
  • Wing Reference Manual which documents all the features in detail.
  • How-Tos with instructions for using Wing with third party
    frameworks, applications, and tool, like Django, Jupyter, matplotlib, Autodesk Maya,
    Raspberry Pi, pygame, and many others.
  • A collection of Wing Tips, available on our website and
    by weekly email subscription, provides additional tips and tricks for using Wing
    productively.

Thanks for using Wing Pro!

Как запустить wing 101 на пк

Windows
Скачайте инсталлятор по этой ссылке.
Запустите инсталлятор.

Mac OS
Скачайте инсталлятор по этой ссылке.
Установку необходимо производить в стандартную папку (не на диск C).
Для запуска инсталлятора наберите в консоли «python3».
Процесс установки аналогичен установке в Windows.

После запуска инсталлятора в первом окне выберите пункт меню Customize installation.

На следующем шаге нажмите Next.

На следующем экране изменить путь к программе на: «C:Python35».
Нажмите кнопку Install.

В последнем окне нажмите кнопку Close.

Интерпретатор Python 3 успешно установлен!

Установка Wing IDE

Windows
Скачайте инсталлятор по этой ссылке.
Запустите инсталлятор.

Mac OS
Скачайте инсталлятор по этой ссылке.
Для установки перетащите файл в папку «Программы».

Установка и настройка Wing IDE в Windows

При установке Wing IDE рекомендуем согласиться со всеми параметрами установки. Ничего изменять не требуется.

После установки рекомендуем вывести ярлык Wing IDE на рабочий стол.

Далее необходимо запустить Wing IDE и произвести настройки параметров.

При первом запуске необходимо согласиться с лицензионным соглашением, нажав на кнопку Accept:

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

    Нажмите на пункт меню Edit -> Configure Python.

Произведите настройки так, как показано на рисунке.
Выберите вариант Custom в первых 2-х настройках.
Задайте пусть к интерпретатору Python, который вы установили.
Нажмите на кнопку Insert. Задайте путь к папке с Python.
Примените настройки, нажав на кноку OK.

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

    Нажмите на пункт меню Edit -> Preferences.

    Перейдите в раздел Files и задайте кодировку utf-8 как показано на рисунке:

    Перейдите в раздел I/O и задайте кодировку utf-8:

  • Примените настройки, нажав на кнопку OK.

Настройка Wing IDE в Mac OS

При первом запуске Wing IDE необходимо согласиться с лицензионным соглашением, нажав на кнопку Accept.

Нажмите на пункт меню Edit -> Configure Python.

Произведите настройки так, как показано на рисунке.
Выберите вариант Custom в первой настройке.
Задайте пусть к интерпретатору Python, который вы установили.
Примените настройки, нажав на кноку OK.

Поздравляем, все готово для программирования на Python!

Источник

Wing Python IDE

The Intelligent Development Environment for Python

Navigation

Installing Wing

Before installing Wing, be sure that you have installed the necessary prerequisites. If you are upgrading from a previous version, see Upgrading first.

Note: The installation location for Wing is referred to as WINGHOME . On macOS this is the name of Wing’s .app folder.

Windows

Install Wing by running the downloaded executable. Wing’s files are installed by default in C:Program Files (x86)Wing Pro 8 , but this location may be modified during installation. Wing will also create a Settings Directory in the location appropriate for your version of Windows. This is used to store preferences and other settings.

The Windows installer supports a /silent command line option that uses the default options, including removing any prior install of Wing 8. If a prior install is removed, a dialog with a progress bar will appear. You can also use a /dir= name> option to specify an alternate installation directory.

The /verysilent command line option has the same effect as /silent but also prevents display of a progress bar.

For Wing Personal the default install directory is instead named Wing Personal 8 and for Wing 101 it is named Wing 101 8 .

Linux

Use the RPM, Debian package, or tar file installer as appropriate for your system type. Installation from packages is at /usr/lib/wingpro8 or at the selected location when installing from the tar file. Wing will also create a Settings Directory in

/.wingpro8 , which is used to store preferences and other settings.

Wing Pro, Wing Personal, and Wing 101 are also available in the Snapcraft Store.

For Wing Personal the install directory is instead named wing-personal6 and for Wing 101 it is named wing-101-6 .

macOS

On macOS, Wing is installed simply by opening the distributed disk image and dragging to the Applications folder, and optionally from there to the task bar.

Источник

Wing Python IDE

The Intelligent Development Environment for Python

Navigation

Wing Pro Quick Start Guide

This is a minimalist guide for getting started quickly with Wing Pro. For a more in-depth introduction, try the Tutorial.

Wing Pro is a light-weight yet powerful integrated development environment that was designed from the ground up for Python. Once you’re up to speed with Wing you should find that:

  • Wing speeds up your development of new code
  • Wing makes it easier to understand and work with existing code
  • Wing reveals errors earlier in the development process
  • Wing makes it easier to find and fix bugs
  • Wing adapts to your needs and style

This is made possible through deep code analysis (both static and runtime), a focus on interactive development in the live runtime, high-level editing operations and refactoring, continuous early error detection, support for test-driven development, powerful always-on debugger, seamless support for remote and containerized development, and extreme configurability.

Let’s get started with Wing Pro!

Install Python

If you don’t already have Python on your system, install it now. Two good options are:

  • Obtain the standard Python distribution from python.org
  • Use Anaconda for seamless access to many third party Python libraries. See Anaconda package lists for a list of the available libraries.

Install Wing

If you don’t already have Wing installed, download it now. For detailed installation instructions, see Installing Wing.

Start Wing

Wing can be launched from the start menu on Windows, by double clicking on the application on macOS, or with wing8.3 on Linux. In Wing Personal the executable is instead named wing-personal8 and in Wing 101 it is named wing-101-8 .

For more information, see Running Wing.

Wing Pro requires a license to run. If you don’t have a license, you can obtain a 30-day trial the first time you start it. Wing Personal and Wing 101 are free to run without a license.

Set up a Project

After Wing is running, select New Project from the Project menu to create a new project. This dialog lets you choose or create the source directory and choose or create the Python environment you want to use for your new project. When creating a new source directory, you can optionally pull a revision control repository into it. Wing Pro can also create and install packages into new virtualenv, pipenv, Anaconda env, and Docker container environments.

If you choose Create Blank Project , you can configure your project later with the following steps:

  • Use Add Existing Directory in the Project menu to add your sources to the project. It’s best to constrain this to the directories you are actively working with and let Wing find the libraries you use through the Python Path .
  • Use Project Properties in the Project menu to set Python Executable to the python.exe or other interpreter executable you want to use with your project. If Python is not on the PATH , set this to the the full path that is in sys.executable in the desired Python installation.
  • If your code alters sys.path or loads modules in a non-standard way then you may need to set Python Path in Project Properties so that Wing can find your modules for auto-completion, refactoring, debugging, testing, and other features.
  • You may want to right-click on your main entry point in the Project tool and select Set As Main Entry Point so that debugging always starts there.
  • Use Save Project As in the Project menu to save your project to disk.
  • Use the Packages tool in the Tools menu to manage Python packages in your selected Python environment.

See Project-Wide Properties and Per-File Properties for a description of all available properties.

Notice that Wing also offers other project types in the New Project dialog, including one for connecting to a remote host via SSH, running with Docker or other containers, accessing a Vagrant instance, working with Windows Subsystem for Linux, and a project type for each of the frameworks, tools, and libraries listed in How-Tos.

Wing may consume significant CPU time when it first analyzes your code base. Progress is indicated in the lower left of the IDE window. Once this is done, the results are cached across sessions and Wing should run with a snappy and responsive interface. See Source Code Analysis to learn how Wing’s source analysis system works.

Wing 101 does not have projects. Configuring the Python environment is instead done with Configure Python in the Edit menu.

Basic Configuration

You are now ready to start working with code, but may want to make a few configuration changes first:

Display Colors — The User Interface > Display Theme and User Interface > Editor Theme preferences choose the colors used in the user interface and editor areas.

Key Bindings — Wing can emulate VI/Vim, Visual Studio, Emacs, Eclipse, XCode, MATLAB, and Brief editors, as selected from Keyboard Personality in the Edit menu or with the User Interface > Keyboard > Personality preference.

Tab Key — The default tab key action depends on the selected keyboard personality and in some cases file type, context, and whether or not there is a selection in the editor. This can be changed from the User Interface > Keyboard > Tab Key Action preference.

Completion Keys — By default, the auto-completer uses the Tab key for completion, but other keys can be added using the Editor > Auto-completion > Completion Keys preference.

There are many other options in Preferences.

Navigating Code

Wing Pro provides a number of different ways to navigate the structure of your code, and several methods for quickly finding symbols or files by name:

Source Index menus at the top of the editor provide quick access to other parts of a source file.

Goto-definition is available from the Source menu, and by right-clicking on symbols in the editor, Python Shell and Debug Console. Use the forward/back history buttons at the top left of the editor to return from the point of definition.

Find Points of Use in Wing Pro’s Source menu shows where the current symbol is being used. This distinguishes between separate but like-named symbols.

Find Symbol in the Source menu in Wing Pro and Wing Personal jumps to a symbol defined in the current file when you type a fragment of its name.

Find Symbol in Project in the Source menu in Wing Pro works the same way but searches all files in the project.

Open From Project in the File menu in Wing Pro and Wing Personal provides a similar interface for quickly opening project files.

See Navigating Source for details on the above.

Source Browser in the Tools menu in Wing Pro and Wing Personal provides module or class oriented display of the structure of your code. Details

Source Assistant in the Tools menu shows detailed information about symbols selected in the editor, auto-completer, Source Browser, Python Shell, Project, and other tools. Details

Searching

Wing Pro provides several different interfaces for searching your code. Which you use depends on what you want to search and how you prefer to interact with the search and replace functionality:

Toolbar search is a quick way to search the current file. Details

Search in the Tools menu shows the Search tool, which provides incremental text, wildcard, and regular expression search and replace in selections and the current file or documentation page. Details

Mini-search in Wing Pro and Wing Personal provides powerful keyboard-driven search and replace. The key bindings listed in the Mini-search area of the Edit menu display the search entry area at the bottom of the window. Details

Search in Files in the Tools menu in Wing Pro and Wing Personal shows the Search in Files tool, which provides wildcard and regular expression search and replace in filtered sets of files, directories, named file sets, and within the project and documentation. Details.

Editing Code

Wing Pro’s editor is designed to speed up the process of writing and modifying Python code, and to reduce the incidence of coding errors. Its features include:

Auto-completion in Wing’s editor, Python Shell and Debug Console speeds up typing and reduces coding errors. The auto-completer uses Tab by default for completion, but this can be changed in the Editor > Auto-completion > Completion Keys preference. This feature is disabled by default in Wing 101. Details

Auto-indent in Wing Pro and Wing Personal matches the file’s existing indentation. When multiple lines are pasted, they are re-indented according to context. A single Undo reverts an unwanted indentation change. A selected range of code may be re-indented as a block using Indentation in the Source menu or the indentation toolbar group. The Indentation tool may be used to convert a whole file’s indentation style. Details

Auto-Editing in Wing Pro implements a range of operations such as auto-entering closing parentheses, brackets, braces, and quotes. Among other things, Wing also auto-enters invocation arguments, manages new blocks with the : key, and corrects out-of-order typing. Auto-editing operations can be enabled and disabled in the Editor > Auto-editing preferences group. The default set includes those operations that don’t affect finger memory. The others are well worth learning. Details

Refactoring operations in Wing Pro, accessed from the Refactoring menu, implement automated renaming and moving of symbols, creating functions or methods out of existing code, and introducing variables much more quickly than by manually editing code. Details

Multiple Selections can be made with Multiple Selections in the Edit menu, the multiple selections toolbar item, and by pressing Ctrl+Alt (or Command+Option on macOS) while making a selection with the mouse. Once multiple selections have been made, edits made will be applied to all the selections at once. Details

Code Warnings are shown in Wing Pro for syntax errors, indentation problems, unreachable code, use of undefined variables and attributes, unresolvable imports, and some other problems. External checkers like flake8, mypy, pep8, and pylint may also be configured as sources for the code warnings. Warnings are shown on the editor with details shown in a tooltip when the mouse hovers over the warning indicator. Warnings can be navigated from the warnings menu in the top right of the editor and managed from the Code Warnings tool. Details

Snippets in Wing Pro are included in Wing’s auto-completer as a quick way to enter commonly repeated patterns for coding standards, documentation, testing, and so forth. Data entry for snippet arguments is inline in the editor. Use the Tab key to move between the fields. Edit or add snippets in the Snippets tool. Details

Turbo Completion in Wing Pro is an optional auto-completion mode for Python, made possible by Wing’s powerful source analysis engine. When the Editor > Auto-completion > Python Turbo Mode preference is enabled, Wing turns every non-symbol key into a completion key in contexts where a new symbol name is not being typed. Details

Quick Selection operations in the Edit > Select menu allow selecting whole statements, blocks, or scopes before copying, editing, or searching through them. Details

Debugging Code

Wing’s debugger is a powerful tool for finding and fixing bugs, understanding unfamiliar code, and writing new code interactively. You can launch code from the Debug menu or toolbar, from the Python Shell, or from outside of the IDE either on the same machine or on another host. Wing also supports working with code running on containers like those provided by Docker.

Breakpoints can be set by clicking on the breakpoint margin to the left of the editor. Stepping operations are in the Debug menu and toolbar.

The Stack Data tool is used to inspect or change program data. Right-click on items to display the item as an array or in textual form. Hovering the mouse over a symbol in the editor shows the value for that symbol in a tooltip, if available on the active debug stack. Pressing Shift-Space shows tooltips for all symbols visible in the editor.

Debug process I/O is shown in the Debug I/O tool, or optionally in an external console.

Other debugger features include:

Interactive Debugging is supported by Wing Pro’s Debug Console, which provides a Python prompt that executes code in the current debug stack frame. When the debugger is paused, Wing also uses the live runtime state to populate the auto-completer in the editor, Source Assistant, goto-definition, and other tools. Details

Conditional Breakpoints can be used in Wing Pro to isolate and understand complex bugs by stopping before they occur. Using a conditional breakpoint to isolate a broken case and the Debug Console to design a fix is far more productive than relaunching code repeatedly. Details

Move Program Counter is supported by Wing Pro, by right-clicking in the editor and selecting Move Program Counter Here . Because of how Python is implemented, this feature works only in the innermost stack frame and it does not work when the debugger is stopped on an exception.

Watching Values in Wing Pro by right-clicking on the editor or any of the data views tracks values over time by symbolic name or object reference in the Watch tool. Expressions can be also be watched. Details

Launch Configurations in the Project menu in Wing Pro and Wing Personal define different runtime environments for debugging, executing, and unit testing your code. Details.

Named Entry Points in the Debug menu in Wing Pro and Wing Personal provide a way to launch the same file with different debug environments. Details

Other Features

Wing Pro includes a number of other features designed to make Python coding easier and more productive:

Python Shell — Wing’s Python Shell lets you try out code in an independent sandbox process. To enable debugging, click the bug icon in the top right of the Python Shell . In Wing Pro and Wing Personal, the shell provides auto-completion, goto-definition, and is integrated with the Source Assistant. Details

Unit Testing in Wing Pro’s Testing tool works with unittest, doctest, pytest, nose, and Django unit tests. You can run tests suites, view the results, and debug tests. Details

Version Control in Wing Pro supports revision control with Mercurial, Git, Subversion, Perforce, Bazaar, and CVS. Wing auto-detects which systems are used in your project and shows the appropriate additional menus and tools in the Tools menu. Details.

Difference and Merge in the Source menu can be used to compare and merge files and directories on disk, files open in the IDE, an unsaved buffer with disk, and a working copy with its revision control repository. Details

Remote Development is easy in Wing Pro, to remote hosts, virtual machines, or containers that are accessible via SSH. In this model of remote development, Wing works seamlessly and securely with files stored entirely on the remote host. Use the Remote Hosts item in the Project menu to configure a remote host, then set the Python Executable in Project Properties to that remote host, and use Add Existing Directory in the Project menu to add your remote directories to the project. Wing can edit, debug, test, search, inspect, and manage files, run the Python Shell, and execute OS Commands on the remote host in the same way as it does when working locally. Details

Package management is available for virtualenv and pipenv, using the Packages tool in the Tools menu. This can be used to install, remove, and manage the packages that are installed into your project’s Python environment.

Containers like those provided by Docker are also supported. In this development model, files are stored locally but code is run inside a containerized environment. Details OS Commands in the Tools menu in Wing Pro and Wing Personal’s displays the OS Commands tool, which execute external tools for build, code generation, and other purposes. Details.

Preferences in the Edit menu (or WingPro menu on macOS) gives you control of the overall layout and color of the IDE, among many other options. Right click on tool and editor tabs for layout options, or drag tabs to move them or create new splits. Right-click on the toolbar to configure which tools are visible or to add your own. See Customization for details.

Perspectives in Wing Pro and Wing Personal let you save named tool panel layouts. Details.

Other Features like bookmarks, code folding, keyboard macros are also available, and you can extend Wing by writing Python scripts.

Further Reading

As you work with Wing Pro on your own software development projects, the following resources may be useful:

  • Wing Support Website which includes a Q&A support forum, mailing lists, documentation, links to social media, and other information for Wing users.
  • Wing Reference Manual which documents all the features in detail.
  • How-Tos with instructions for using Wing with third party frameworks, applications, and tool, like Django, Jupyter, matplotlib, Autodesk Maya, Raspberry Pi, pygame, and many others.
  • A collection of Wing Tips, available on our website and by weekly email subscription, provides additional tips and tricks for using Wing productively.

Thanks for using Wing Pro!

Источник

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

Установка интерпретатора

Дистрибутивы для установки:

  • Windows, 32-бита: https://www.python.org/ftp/python/3.7.0/python-3.7.0a1.exe
  • Windows, 64-бита: https://www.python.org/ftp/python/3.7.0/python-3.7.0a1-amd64.exe
  • Дистрибутив для Mac OS X: https://www.python.org/downloads/release/python-362/
  • Для операционных систем GNU/Linux язык Питон скорее всего есть в дистрибутиве, для чего необходимо поставить пакет python3. Возможно, он уже установлен в вашей системе: проверить это можно командой python3.
  • Для Android есть пакет QPython3.

Установка интегрированной среды разработки

Для удобства разработки кода программисты используют среды разработки (IDE).

Для обучения программированию на языке Питон рекомендуется среда разработки Wing IDE 101. Для работы на занятиях будет использоваться WingIDE 101.

Для больших проектов рекомендуется PyCharm Community Edition.

Wing IDE 101

Среда разработки Wing IDE — одна из самых распространенных сред, используемых сейчас в образовании и на олимпиадах. Ее версия Wing IDE 101 специально предназначена для обучения и не содержит ничего лишнего и отвлекающего. Для создания программы достаточно просто открыть среду, создать новый файл и начать писать код: не нужны никакие специальные настройки, не требуется создавать проект и т. п.

Wing IDE работает под основными платформами (Win, Mac, Linux), версию 101 можно бесплатно скачать и установить с сайта wingware.org.

Устанавливать среду нужно после установки транслятора Python.

Если среда не нашла или нашла не ту версию Python, укажите исполняемый файл Python вручную в меню Edit — Configure Python в верхнем поле ввода (обычно он имеет примерно такой вид: c:python34python.exe под Windows, /usr/local/bin/python3 под Mac, /usr/bin/python3 под Linux).

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

Ввод-вывод производится во вкладке Debug I/O, а сообщения об ошибках выводятся во вкладке Exceptions (исключения).

Дистрибутив для Windows: http://wingware.com/pub/wingide-101/5.0.9/wingide-101-5.0.9-1.exe

Дистрибутивы для других операционных систем можно найти на http://wingware.com/downloads/wingide-101

Видео установки Python и Wing IDE 101 на Windows 7 (на английском): https://www.youtube.com/watch?v=OrpavIGbkSw

Обратите внимание: если вы устанавливаете среду после установки Python, то она должна сама обнаружить установленный Python. Если этого не произошло, пропишите в меню Edit-Configure python в верхнем поле ввода путь к исполняемому файлу Python (под windows это обычно что-то типа c:python34python.exe).

PyCharm community edition

Версия для Windows: https://download.jetbrains.com/python/pycharm-community-4.5.4.exe

Остальные версии можно скачать здесь: http://www.jetbrains.com/pycharm/download/

Понравилась статья? Поделить с друзьями:
  • Как установить питон на windows 10 idle
  • Как установить подлинную версию windows 10 бесплатно
  • Как установить питон на windows 10 64 bit
  • Как установить подключение к wifi на windows 7
  • Как установить пиратский windows 10 с флешки