681.99K
Категория: ПрограммированиеПрограммирование

Introduction to Programming and the Python Language

1.

Lecture 1.
Introduction to programming and the Python language
What is a programming language?
The history and evolution of Python
Features and philosophy of Python
Setting up the environment

2.

What is a programming language?

3.

At the physical level, a computer understands only machine code — a
sequence of zeros and ones (binary code) that controls electrical signals in
the processor. It is extremely difficult for a person to write programs at this
level.
To solve this problem, programming languages have been created —
artificial language systems that act as a bridge between human logic and
machine code.
Python is one of the high-level languages. This means that its syntax is as
close as possible to natural English, abstracting the developer from direct
memory and processor register management.

4.

The history and evolution of Python

5.

The Python language was created by Dutch programmer Guido van Rossum in the late 1980s.
Development began at the Center for Mathematics and Computer Science (CWI) in the Netherlands as a successor to
the ABC language.
December 1989 — Guido began work on the project, naming it after the popular British comedy show of the
1970s, Monty Python's Flying Circus.
February 1991 — the first public release was published (version 0.9.0).
2000 — Python 2.0 was released. The introduction of list inclusions and a full-fledged garbage collection system.
2008 — the release of Python 3.0. It was a major update that fixed architectural flaws, but violated backward
compatibility with Python 2. For many years, the industry used both versions in parallel, until support for Python 2
was officially discontinued on January 1, 2020.

6.

Features and philosophy of Python

7.

Python has gained global popularity due to the following key features:
Key Properties
Interpreted language
Dynamic typing
Multi-paradigm
Cross-platform

8.

Interpretability.
Unlike compiled languages (C, C++, Rust), where the source code is completely translated
into a machine file before running, Python uses an interpreter.
The program is executed line by line. First, the source code .py is compiled into an
internal bytecode.pyc, and then the Python virtual machine (CPython) executes it in real
time.
This speeds up the development and testing process, although it reduces the absolute
execution speed.
•Интерпретируемость. В отличие от компилируемых
языков (C, C++, Rust), где исходный код полностью
переводится в машинный файл перед запуском, Python
использует интерпретатор. Программа выполняется
строка за строкой. Сначала исходный код .py
компилируется во внутренний байт-код .pyc, а затем
виртуальная машина Python (CPython) исполняет его в
реальном времени. Это ускоряет процесс разработки и
тестирования, хотя и снижает абсолютную скорость
выполнения.

9.

Dynamic typing.
You don't need to declare the type of the variable (int, string) in advance. Python
determines the data type automatically when assigning a value to a variable.
At the same time, typing is strict (strong): the language will not allow implicitly
adding a number to a string without explicit conversion.
Динамическая типизация. Вам не нужно
объявлять тип переменной (int, string) заранее.
Python определяет тип данных автоматически в
момент присваивания значения переменной. При этом
типизация является строгой (сильной): язык не
позволит неявно сложить число со строкой без явного
преобразования.

10.

Multi-paradigm.
Python supports object-oriented (OOP), functional, and procedural
programming. You can write code in the style that best suits your
current task.
Мультипарадигменность. Python поддерживает объектноориентированное (ООП), функциональное и процедурное
программирование. Вы можете писать код в том стиле,
который лучше всего подходит для текущей задачи.

11.

Cross-platform.
The same code runs unchanged on Windows, macOS, and Linux.
Кроссплатформенность. Один и тот же код без изменений работает на Windows, macOS и Linux.

12.

The Zen of Python Philosophy
In the Python community, there is an official set of software design guidelines written by
developer Tim Peters in 1999.
It is called the Zen of Python and is documented in the official document PEP 20 (Python
Enhancement Proposal).
You can output this text directly in the Python console by entering the command:
Python
import this

13.

1. Красивое лучше, чем уродливое (Beautiful is better than ugly)
Код должен быть эстетичным. В Python нет лишних символов (точек с
запятой, фигурных скобок), что делает его похожим на обычный текст.
Уродливо (как в некоторых других языках):
if(x>0){data=[1,2,3];print(data);} (все в кучу, тяжело
читать).
•Красиво (в стиле Python):
python
if x > 0: data = [1, 2, 3] print(data)

14.

2. Явное лучше, чем неявное (Explicit is better than implicit)
Никогда не заставляйте программиста угадывать, откуда взялись данные или что
делает функция. Код должен открыто заявлять о своих намерениях.
Неявно (плохо): Использовать «магический» импорт всех функций из модуля:
from math import *. Если вы потом вызовете функцию ceil(), другой
программист не сразу поймет, откуда она взялась — написали вы ее сами или она
пришла из библиотеки math.
•Явно (хорошо):
python
import math result = math.ceil(4.2) # Сразу видно: функция
ceil берется из модуля math

15.

3. Простое лучше, чем сложное (Simple is better than complex)
Если задачу можно решить базовыми инструментами, решайте её
базовыми инструментами. Не нужно строить сложные архитектурные
надстройки (классы, паттерны проектирования), если достаточно
обычного цикла или функции.
Сложно: Создавать целый класс «Калькулятор» с методами
инициализации ради одного сложения двух чисел.
•Просто: Написать
result = a + b

16.

4. Читаемость имеет значение (Readability counts)
Код пишется один раз, а читается сотни раз (вами через полгода или вашими друзьями). Если
код работает, но его невозможно прочесть — это плохой код. Именно поэтому в Python так
важны понятные названия переменных (например, user_age вместо просто x) и отступы.

17.

5. Сложное лучше, чем запутанное (Complex is better than complicated)
Если задача сама по себе объективно тяжелая (например, обработка больших
данных или распознавание лиц), код неизбежно станет сложным (complex). Это
нормально. Но он не должен быть запутанным (complicated) — то есть
превращаться в «клубок спагетти», где функции хаотично вызывают друг друга.
•Решение в стиле Дзен: Разбить сложную задачу на несколько простых,
изолированных шагов (функций), каждый из которых делает ровно одну вещь.

18.

6. Должен существовать один — и, желательно, только один — очевидный
способ сделать это (There should be one-- and preferably only one --obvious
way to do it)
Это главное отличие Python от языков вроде Perl или Ruby, где одну и ту же
задачу можно решить десятью кардинально разными путями. В Python
сообщество стремится к стандартизации. Когда вы открываете чужой код на
Python, вы быстро в нем ориентируетесь, потому что автор, скорее всего,
использовал тот же стандартный подход, что использовали бы и вы.

19.

Главный вывод: как применять Дзен на практике?
Когда вы пишете код на Python, каждый раз задавайте себе три вопроса:
1.Поймет ли мой коллега (или я сам через месяц) этот код без дополнительных
объяснений?
2.Можно ли сделать эту логику проще, не потеряв в надежности?
3.Выглядит ли код аккуратно?
Если ответы «да», значит, вы поймали Дзен Пайтона.

20.

Setting up the environment
Python development requires two components: the Python interpreter itself and the development
environment (a text editor or IDE).

21.

Step 1. Install the Python interpreter
1. Go to the official website python.org to the Downloads section.
2. Download the latest stable version of Python 3 for your operating system.
3. Important when installing on Windows: On the very first screen of the installer, be sure to check the box "Add
python.exe to PATH" (Add Python to the PATH environment variable). Without this, the system will not be
able to run Python from the command line.
4. Check the installation. Open a terminal (Command prompt in Windows / Terminal in macOS) and type:

22.

Step 2. Selecting and configuring the development environment
Two main tools are used to create commercial and educational software:
Criterion
Visual Studio Code (VS
Code)
PyCharm
(Community/Professional)
Type
Lightweight, extensible
code editor
A full-fledged integrated
environment (IDE).
Resources.
Consumes little RAM and
starts up instantly.
It is demanding on
processor and RAM,
indexes the project.
Customization.
Requires manual
installation of plugins
(modular approach).
Ready to work "out of the
box" (all inclusive)
Better for:
Small scripts, web
frontend, microservices.
Large-scale projects, work
with OOP and complex
architecture

23.

Creating the first program and launching the codecreate the classic program
"Hello, World!" and let's look at three main ways to launch it.
The program code in the hello.p file

24.

Мethod 1. Interactive mode (REPL).
It is convenient for quick hypothesis testing and short mathematical operations.
1. Open the terminal.
2. Enter the python (or python3) command.
3. You will see an input prompt in the form of three arrows >>>.
Enter the command:
4. To exit the mode, type exit() or press Ctrl + Z.

25.

Method 2. Run the script through the terminal.
1. Save the code above to a file named hello.py .
2. In the terminal, navigate to the file folder using the cd command (for example, cd
Documents/PythonProjects).
3. Run the file with: command:
4. The terminal outputs a line of text and shuts down.

26.

Method 3. Launch inside the development environment (IDE)
In VS Code:
Open the file hello.py and click on the triangle icon (Run Code / Run Python File) in the upperright corner of the screen.
In PyCharm:
Right-click inside the open code file and select Run 'hello' (or press Shift + F10 / Ctrl +R). The
result will be displayed in the built-in terminal window at the bottom of the screen.

27.

Self-test control questions:
1.
2.
3.
4.
5.
6.
What is the difference between a compiled programming language and an interpreted one?
What type of Python is it?
What happens if I run the import this command in the Python console?
Why is it critically important to check the "Add" box when installing Python on Windows?
python.exe to PATH"?
Why do Python use mandatory indents instead of curly braces?

28.

Thanks for your attention!
English     Русский Правила