Create a Python project
Pure Python projects are intended for Python programming. A project helps you organize your source code, tests, libraries that you use, and your personal settings in a single unit. In case you don’t need a project, you can edit your file in the LightEdit mode.
To create a project, do one of the following:
From the main menu, choose File | New Project
On the Welcome screen, click New Project
New Project dialog opens.
In the New Project dialog, specify the project name and its location. The dialog may differ depending on the PyCharm edition.


Next, choose whether you want to create a new environment or use an existing interpreter, by clicking the corresponding radio-button.
To use a remote Python interpreter, select Previously configured interpreter .
The following steps depend on your choice:
If this option has been selected, choose the tool to be used to create a virtual environment. To do that, click the list and choose Virtualenv , Pipenv , Poetry , or Conda .
Next, specify the Location and Base interpreter of the new virtual environment.
Select the Inherit global site-packages checkbox if you want all packages installed in the global Python on your machine to be added to the virtual environment you’re going to create. This checkbox corresponds to the —system-site-packages option of the virtualenv tool.
Select the Make available to all projects checkbox if you want to reuse this environment when creating Python interpreters in PyCharm.
If PyCharm detects no Python on your machine, it provides the following options:
Specify a path to the Python executable (in case of non-standard installation)
Download and install the latest Python versions from python.org
Install Python using the Command-Line Developer Tools (macOS only).


If this option has been selected, choose the desired interpreter from the list, or (if the desired interpreter is not found), click Add Interpreter and choose the interpreter.
When PyCharm stops supporting any of the outdated Python versions, the corresponding Python interpreter is marked as unsupported.

Create a main.py welcome script : keep this option selected if you want PyCharm to add the main.py file to your project. This file contains a very simple Python code sample and can be a starting point of your project.
Once you created a project, you can proceed with configuring the project structure.
Step 1. Create and run your first Python project
You have installed Python itself. If you’re using macOS or Linux, your computer already has Python installed. You can get Python from python.org.
To get started with PyCharm, let’s write a Python script.
Create a Python project
If you’re on the Welcome screen, click New Project . If you’ve already got any project open, choose File | New Project from the main menu.
Although you can create projects of various types in PyCharm, in this tutorial let’s create a simple Pure Python project. This template will create an empty project.
Choose the project location. Click button next to the Location field and specify the directory for your project.
Also, deselect the Create a main.py welcome script checkbox because you will create a new Python file for this tutorial.
Python best practice is to create a virtualenv for each project. In most cases, PyCharm create a new virtual environment automatically and you don’t need to configure anything. Still, you can preview and modify the venv options. Expand the Python Interpreter: New Virtualenv Environment node and select a tool used to create a new virtual environment. Let’s choose Virtualenv tool, and specify the location of the environment and the base Python interpreter used for the new virtual environment.
If PyCharm detects no Python on your machine, it provides the following options:
Specify a path to the Python executable (in case of non-standard installation)
Download and install the latest Python versions from python.org
Install Python using the Command-Line Developer Tools (macOS only).


Now click the Create button at the bottom of the New Project dialog.
If you’ve already got a project open, after clicking Create PyCharm will ask you whether to open a new project in the current window or in a new one. Choose Open in current window — this will close the current project, but you’ll be able to reopen it later. See the page Open, reopen, and close projects for details.
Create a Python file
In the Project tool window, select the project root (typically, it is the root node in the project tree), right-click it, and select File | New . .
Select the option Python File from the context menu, and then type the new filename.

PyCharm creates a new Python file and opens it for editing.
Edit Python code
Let’s start editing the Python file you’ve just created.
Start with declaring a class. Immediately as you start typing, PyCharm suggests how to complete your line:

Choose the keyword class and type the class name, Car .
PyCharm informs you about the missing colon, then expected indentation:

Note that PyCharm analyses your code on-the-fly, the results are immediately shown in the inspection indicator in the upper-right corner of the editor. This inspection indication works like a traffic light: when it is green, everything is OK, and you can go on with your code; a yellow light means some minor problems that however will not affect compilation; but when the light is red, it means that you have some serious errors. Click it to preview the details in the Problems tool window.
Let’s continue creating the function __init__ : when you just type the opening brace, PyCharm creates the entire code construct (mandatory parameter self , closing brace and colon), and provides proper indentation.
If you notice any inspection warnings as you’re editing your code, click the bulb symbol to preview the list of possible fixes and recommended actions:
Let’s copy and paste the entire code sample. Hover the mouse cursor over the upper-right corner of the code block below, click the copy icon, and then paste the code into the PyCharm editor replacing the content of the Car.py file:
This application is intended for Python 3
At this point, you’re ready to run your first Python application in PyCharm.
Run your application
Use either of the following ways to run your code:
Right-click the editor and select Run ‘Car’ from the context menu .
Since this Python script contains a main function, you can click an icon in the gutter. If you hover your mouse pointer over it, the available commands show up:

If you click this icon, you’ll see the popup menu of the available commands. Choose Run ‘Car’ :
PyCharm executes your code in the Run tool window.

Here you can enter the expected values and preview the script output.
Note that PyCharm has created a temporary run/debug configuration for the Car file.

The run/debug configuration defines the way PyCharm executes your code. You can save it to make it a permanent configuration or modify its parameters. See Run/debug configurations for more details about running Python code.
Summary
Congratulations on completing your first script in PyCharm! Let’s repeat what you’ve done with the help of PyCharm:
Getting started with PyCharm
In the previous two posts of this absolute beginner series, we installed Anaconda Navigator and learned about virtual environments. Having completed the basic setup, it’s now time to choose an IDE and get to coding.
I should mention from the start that choosing and IDE is not crucial when starting learning. Just go with anything that is comfortable for you… Any recommendations in this post are my preferences which might not match yours. That is absolutely fine, all is subjective 🙂
PyCharm Installation and Setup
PyCharm is developed by JetBrains which produces IDE applications for many popular languages (Javascript, C/C++, PHP, Ruby etc.). I’ve worked with PHPStorm for several years before starting with Python, so my transition to PyCharm was quite smooth.
PyCharm is available for download on Windows, Mac and Linux. The Professional Edition trial is 30 days, but, unlike other of their IDEs, JetBrains offers a perpetually free Community Edition.
Download and installation is a straightforward process. When launching PyCharm for the first time, you’ll have to go through a couple of settings. Choose a dark or light theme (I chose the dark side if anyone wonders ) and skip installation of other plugins for now. As a side note, you might notice that one of the plugins is for supporting the R language which was mentioned as an alternative to Python.
After setup is complete, you’ll see the welcome screen. It’s time to create our first project in PyCharm.
Creating a Project
On the Welcome screen, simply click Create a Project.
I’ve named the project learning_project. It will have its own folder on the disk. I’ve left the default path, but you can place the project wherever you wish.
Expanding Project Interpreter: New Virtualenv environment we can see more details about the project.
Most important, PyCharm will create a new virtual environment for this project. This is done for all new projects, without any additional settings having to be made. Quite handy…
Then we see the base interpreter is the python we installed with Anaconda. So PyCharm recognizes any existing Python installations.
The other 2 checkbox options are more advanced, so there’s no need to worry about them for now.
Creating a Python file and running it
On the left side of the UI we see the Project. Right click on its name and create a new Python file.
In the Python file add the same code from the numpy test in the previous post:
To run the file, press CTRL+SHIFT+F10 (or just SHIFT+F10, depending on version). You’ll see the following error: No module named ‘numpy’
Do you have any idea what the problem is?
Well, we haven’t installed numpy inside this project’s virtual environment.
Installing a Package in PyCharm
Packages in PyCharm can be installed using pip, the package installation manager for Python.
In the lowest bar of the UI, click on terminal and type
pip will then download and install the package inside the virtual environment. Any dependencies will automatically be collected and installed as well.
When the installation is successfully complete, you should see the following:
Running the file again will prove successful this time, with the expected value [1, 2, 3] being displayed on the screen.
Having a virtual environment automatically created for every project is just one of PyCharm’s features. The Getting started guide on the official site provides more thorough introduction.
Alternatives to PyCharm
There are of course many alternatives to PyCharm, which proves Python is a very popular language. Two are available inside Anaconda Navigator: Spyder and Visual Studio Code.
Spyder
Spyder is a Python IDE aimed specifically at Data Scientists. You can check out a great overview video here.
Visual Studio Code
A lightweight free code editor from Microsoft, Visual Studio Code is available on all platforms. It’s not set up for Python out of the box, but it has official Python support via an extension. Check out the get started guide.
Atom
Like Visual Studio Code, Atom is a light editor, not specific to Python, but highly configurable and offering Python support via extensions.
If you want to read more, here is a great overview of IDEs and code editors for Python: https://realpython.com/python-ides-code-editors-guide/
Conclusion
You can check them all out before deciding which one to use. My advice is not to dwell too much on this now, any option is good enough to start learning about Python, Machine Learning or Data Science… and you can always switch IDEs when you are more experienced.
Next post will be an overview of Jupyter Notebooks, an indispensable tool for any Python user.
Your opinions, feedback or (constructive) criticism are welcomed in discussions below or at @mariussafta
Join our Facebook and Meetup groups and keep an eye out for discussions and future meetups.
Name already in use
2022-2-level-labs / docs / public / starting_guide_ru.md
- Go to file T
- Go to line L
- Copy path
- Copy permalink
- Open with Desktop
- View raw
- Copy raw contents Copy raw contents
Copy raw contents
Copy raw contents
Подготовка к прохождению курса
Перед началом прохождения курса «Программирование для лингвистов» каждому студенту необходимо сделать несколько шагов, которые подготовят необходимые инструменты к дальнейшей работе:
Другие полезные инструкции
Установка интерпретатора языка программирования Python
Чтобы установить интерпретатор языка программирования Python на свой компьютер, выполните следующие шаги:
Скачайте установочный файл для своей системы с официального сайта

- NB: Для скачивания нажмите кнопку Download Python 3.XX.XX
- NB №2: Версия Python должна быть >= 3.10!
Запустите установочный файл и следуйте указаниям по установке
Проверьте корректность установки:
- Откройте терминал и выполните следующую команду:
- Mac: python3 -V
- Windows: python -V
- Вы должны увидеть строку, похожую на следующую: Python 3.10.2
- Как открыть терминал:
Установка системы контроля версий Git
Чтобы установить систему контроля версий Git, выполните следующие шаги:
Скачайте установочный файл для своей системы с официального сайта

- NB: Для скачивания нажмите кнопку Download for <название ОС>
Запустите установочный файл и следуйте указанием по установке
Проверьте корректность установки:
- Откройте терминал и выполните следующую команду:
- git
- Вы должны увидеть строку, похожую на следующую: usage: git .
- Как открыть терминал:
Установка среды разработки PyCharm
Чтобы установить среду разработки PyCharm, выполните следующие шаги:
Скачайте установочный файл для своей системы с официального сайта

- NB: Для скачивания нажмите кнопку Download
- NB №2: Рекомендуется использовать Community Edition, так как эта версия бесплатна
- NB №3: Так как Вы являетесь студентом ВШЭ, Вы можете использовать и Professional Edition, зарегистрировавшись с учебной почтой.
- Данная версия предоставляет дополнительные возможности.
Запустите установочный файл и следуйте указанием по установке
Проверьте корректность установки:
Откройте PyCharm из меню приложений
Вы должны увидеть похожий интерфейс:

Регистрация на платформе GitHub
Чтобы зарегистрироваться на платформе GitHub, выполните следующие шаги:
В верхнем правом углу нажмите кнопку Sign up :

- NB: Рекомендуется использовать личную почту, чтобы после окончания учёбы не пришлось менять почту с учебной на личную
- NB №2: Рекомендуется (но не обязательно) в качестве логина использовать фамилию и имя
- Пример: AndreiKashchikhin
Создание Personal Access Token для аутентификации
Чтобы у Вас была возможность взаимодействовать со своей рабочей машины с удалённым репозиторием, Вам необходимо создать и использовать Personal Access Token (PAT).
Чтобы создать PAT, выполните следующие шаги:
Откройте главную страницу GitHub и войдите в свой аккаунт
В правом верхнем углу нажмите на свой аватар и из списка выберите Settings :

Из списка слева выберите вкладку Developer settings :

Из списка слева выберите вкладку Personal access tokens :

Нажмите кнопку Generate new token :

Введите название для PAT в поле Note (1), выберите Expiration (2), поставьте галочку слева от настроек repo (3), workflow (4), gist (5):

Внизу страницы нажмите кнопку Generate token
Нажмите на кнопку копирования, чтобы перенести токен в буфер обмена:

- NB: Обязательно сохраните этот токен! Он будет использоваться в других шагах в качестве пароля, необходимого для аутентификации.
- NB №2: После закрытия этой страницы, токен нельзя будет снова увидеть или найти на GitHub.
В следующих шагах инструкции, при требовании пароля, вводите сохранённый токен.
Если у Вас возникают проблемы на каком-то из шагов, Вы можете обратиться к официальной документации. Там же Вы можете узнать больше о PAT.
Создание форка репозитория
Чтобы создать форк репозитория на платформе GitHub, выполните следующие шаги:
Откройте сайт репозитория, который Вам прислал преподаватель
В верхнем правом углу нажмите кнопку Fork :

На открывшейся странице нажмите кнопку Create Fork

Форк создан. Обратите внимание на ссылку в адресной строке браузера: она будет содержать имя Вашего GitHub пользователя и название репозитория:
-
<имя-Вашего-пользователя>/202X-2-level-labs
Добавления менторов в коллабораторы
В Ваш форк можете вносить изменения только Вы. В процессе прохождения курса может возникнуть ситуация, когда ментору будет необходимо внести изменения в Ваш форк (добавить изменения из основного форка, разрешить конфликты и т.д.).
Чтобы у менторов была возможность вносить изменения в Ваш форк, их нужно добавить в коллабораторы.
Чтобы добавить человека в коллабораторы форка, выполните следующие шаги:
Откройте сайт форка, который Вы создали на шаге Создание форка репозитория

- NB: Обратите внимание на ссылку в адресной строке браузера: она будет содержать имя Вашего GitHub пользователя и название репозитория.
Нажмите кнопку Settings :

Слева выберите вкладку Collaborators :

Нажмите кнопку Add people

В открывшемся окне введите имя GitHub пользователя ментора и выберите его из списка:

Нажмите кнопку Add <имя-пользователя> to this repository :

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

- NB: После данного шага обязательно напишите добавленному ментору, чтобы он мог принять запрос.
Проделайте шаги 4-7 для всех менторов курса. Их список Вы можете:
- Уточнить у преподавателей или
- найти в файле admins.txt , который находится по пути <адрес-основного-репозитория>/config .
- Пример для 2022 года: https://github.com/fipl-hse/2022-2-level-labs/blob/main/config/admins.txt
Клонирование форка репозитория для локальной работы
Чтобы склонировать форк на Вашу систему, выполните следующие шаги:
Откройте сайт Вашего форка, который Вы создали на предыдущем шаге
Нажмите кнопку Code , выберите HTTPS и нажмите кнопку копирования:

Откройте терминал и перейдите в удобную папку:
- Чтобы переходить из папки в папку в терминале, используйте команду cd <название-папки>
- Пример: cd work
Выполните следующую команду для клонирования репозитория:
- git clone <ссылка-на-ваш-форк>
- Пример: git clone https://github.com/WhiteJaeger/2022-2-level-labs
- Как открыть терминал:
Создание проекта в среде разработки PyCharm
Чтобы создать проект и работать с Вашим форком в среде разработки PyCharm, выполните следующие шаги:
Откройте PyCharm и нажмите кнопку Open

В открывшемся окне выберите папку с форком, который Вы склонировали на шаге «Клонирование форка репозитория для локальной работы»

- NB: На скриншоте выше показано, что форк был склонирован в папку PycharmProjects .
- NB №2: Нужно выбрать именно папку с форком, имеющую название 202X-2-level-labs , а не папку с конкретной лабораторной работой.
В открывшемся окне нажмите кнопку OK

- NB: Если в поле Base Interpreter версия Python < 3.9, то нажмите на Python 3.X и из выпадающего списка выберите более новую версию
Проект создан, слева Вы можете увидеть файлы проекта

Изменение исходного кода и отправка изменений в удалённый форк
Основную работу Вы будете вести в файле main.py в папке с каждой лабораторной работой.
Процесс выглядит следующим образом:
- Вы изменяете исходный код в файле main.py
- Вы фиксируете изменения с помощью системы контроля версий git
- Вы отправляете изменения в удалённый форк
Далее будет пример этого процесса.
Изменение исходного когда
По умолчанию функции не имеют внутри себя реализации — только pass в теле функции:

Ваша задача — реализовать функцию по предоставленному описанию лабораторной работы:

Фиксация изменений с помощью системы контроля версий git
Git — система контроля версий, которая позволяет сразу нескольким разработчикам сохранять и отслеживать изменения в файлах проекта.
Сейчас мы зафиксируем изменения, сделанные на предыдущем шаге в файле main.py . Чтобы это сделать, выполните следующие шаги:
Откройте терминал в среде разработки PyCharm:

В терминале выполните команду git add <путь-до-лабораторной-работы>/main.py

В терминале выполните команду git commit -m «message»

- NB: В качестве message рекомендуется использовать краткое описание тех изменений, которые Вы сделали. Этот текст будет публично доступен!
Больше информации о командах, описанных выше, можно найти в официальной документации по Git.
Отправка изменений в удалённый форк
После предыдущего шага изменения находятся в состоянии зафиксированных. Они сохранены только у Вас на системе. Чтобы отправить их в удалённый (находящийся на платформе GitHub) форк, созданный ранее, выполните следующие шаги:
Откройте терминал в среде разработки PyCharm:

В терминале выполните команду git pull
- NB: При просьбе ввести пароль, введите созданный Personal Access Token
В терминале выполните команду git push

- NB: При просьбе ввести пароль, введите созданный Personal Access Token
Откройте главную страницу Вашего форка:

- NB: Вы увидите сделанный commit и сообщение, которое Вы написали.
Больше информации о командах, описанных выше, можно найти в официальной документации по Git.
Создание Pull Request
Чтобы менторы смогли увидеть Ваши изменения и провести проверку, Вам нужно создать Pull Request на платформе GitHub.
Чтобы создать Pull Request, выполните следующие шаги:
Откройте сайт репозитория, который Вам прислал преподаватель
Выберите вкладку Pull Requests

Нажмите кнопку New pull request

Нажмите кнопку compare across forks

Нажмите head repository и из списка выберите Ваш форк (он будет содержать имя Вашего пользователя)

Нажмите кнопку Create pull request

Введите название для Pull Request

- NB: Имя PR должно соответствовать следующему шаблону: Laboratory work #X, Name Surname — 2XFPLX
- NB №2: Пример имени Вы можете увидеть на скриншоте выше.
Нажмите Assignees и из списка выберите ментора, который указан в таблице успеваемости:

Нажмите кнопку Create pull request

- NB: Pull Request появится в списке PR, который находится на странице из шага №2.
Продолжение работы заключается в повторении нескольких шагов:
- Они автоматически будут обновляться и в Pull Request, который Вы создали
В процессе прохождения курса в основной репозиторий будут добавляться изменения (новые лабораторные работы, изменения в тестах, исправления ошибок и т.д.) — эти изменения не будут автоматически появляться в сделанных форках.
Чтобы добавить изменения в Ваш форк из основного репозитория, выполните следующие шаги:
Откройте сайт репозитория, который Вам прислал преподаватель
Нажмите кнопку Code , выберите HTTPS и нажмите кнопку копирования:

Откройте терминал в среде разработки PyCharm:

В терминале выполните команду git remote add upstream <ссылка-на-основной-репозиторий>

В терминале выполните команду git fetch upstream

- NB: Обратите внимание, что ссылка на скриншоте выше указывает на родительский репозиторий.
В терминале выполните команду git merge upstream/main —no-edit

- NB: В зависимости от количества изменений вывод команды может отличаться от того, что на скриншоте выше.
- NB №2: В результате выполнения этой команды в Вашем локальном форке появятся последние изменения из основного репозитория.
Больше информации о командах, описанных выше, можно найти в официальной документации по Git.