Скачать Python и установить на Linux, Mac OS, Windows
Для начала проверьте, возможно, python уже установлен на вашем компьютере. Откройте терминал или командную строку и введите:
python --version
Ниже написаны краткие инструкции для быстрой установки python на вашу OS. Если данной информации не достаточно, смотрите подробные статьи:
- Python для Mac OS
- Python для Linux (Ubuntu)
- Python для Windows
Установка и запуск Python на Mac OS
- Перейдите на страницу “Скачать Python” на официальном сайте и кликните Загрузить Python 3.7.2 (версия может измениться).
- Когда загрузка будет завершена, откройте пакет и следуйте инструкциям. Вы увидите сообщение “Инсталляция прошла успешно” в случае, если Python был успешно установлен.
- Рекомендуется так же загрузить хороший текстовый редактор перед началом работы. Если вы новичок, я рекомендую вам скачать Sublime Text. Он бесплатный.
- Процесс установки прост. Запустите загруженный файл Sublime Text и следуйте инструкциям.
- Откройте Sublime Text и перейдите File > New File (Клавиши быстрого доступа: Cmd+N). Затем, сохраните файл (Cmd+S или File > Save) с расширением .py в таком виде: hello.py или first-program.py .
- Напишите код и снова его сохраните. Новичок может скопировать этот код print(«Hello, World!») . Простая программа выводит “Hello, World!”.
- Перейдите в Tool > Build (Клавиши быстрого доступа: Cmd + B). Вы увидите вывод в нижней части Sublime Text. Мои поздравления, вы успешно запустили свою первую программу Python
Установка и запуск Python на Linux (Ubuntu)
- Сначала установите зависимости:
$ sudo apt-get install build-essential checkinstall $ sudo apt-get install libreadline-gplv2-dev libncursesw5-dev libssl-dev libsqlite3-dev tk-dev libgdbm-dev libc6-dev libbz2-dev
- Перейдите на страницу “Скачать Python” на официальном сайте и кликните Загрузить Python 3.7.2 (версия может измениться).
- В терминале перейдите в каталог, где находится скачанный файл и распакуйте архив командой (имя файла может отличаться, если вы загрузили другую версию python):
$ tar -xvf Python-3.7.2.tgz
- Перейдите в извлеченный каталог.
$ cd Python-3.7.2
- Выполните команды ниже для компиляции исходного кода Python в Ubuntu.
$ ./configure $ make $ make install
- Установить Sublime Text, если вы новичок. Для установки Sublime Text в Ubuntu (18.04), выполните следующие команды.
$ sudo add-apt-repository -y ppa:webupd8team/sublime-text-2 $ sudo apt-get update $ sudo apt-get install sublime-text
- Откройте Sublime text. Для создания нового файла, перейдите к File > New File (клавиши быстрого доступа: Ctrl+N).
- Сохраните файл с расширением .py например, как: hello.py или first-program.py .
- Добавьте и сохраните код (Ctrl+S или File > Save). Если вы новичок, просто скопируйте указанное ниже:
print("Hello, World!")
- Перейдите на Tool > Build (Клавиши быстрого доступа: Ctrl+B). Вы увидите вывод в нижней части Sublime Text. Поздравляем, вы успешно запустили свою первую программу на Python.
Установка и запуск Python на Windows
- Перейдите на страницу “Скачать Python” на официальном сайте и кликните Загрузить Python 3.7.2 (версия может измениться).
- Когда загрузка будет завершена, дважды кликните на файл и следуйте инструкциям по его установке. Когда Python установлен, вместе с ним также устанавливается программа IDLE. Она предоставляет графический интерфейс для работы с Python.
- Убедитесь, что флажки “Установить для всех”(рекомендуется) и «Add Python 3.7 to PATH» вы отметили. Если в процессе установки Python будет обнаружена более ранняя версия, уже установленная на вашем компьютере, вместо этого появится сообщение «Обновить сейчас» (Upgrade Now) и флажки не будут отображаться.
- Откройте IDLE, скопируйте следующий код ниже и нажмите клавишу ввода.
print("Hello, World!")
- Чтобы создать файл в IDLE , перейдите в Файл >Новое окно (клавиши быстрого доступа: Ctrl + N)
- Добавьте код Python (вы можете скопировать код ниже) и сохраните (клавиши быстрого доступа: Ctrl + S) с .py расширением файла, например: hello.py или your-first-program.py .
print("Hello, World!")
- Перейдите в меню Run > Run module (клавиша быстрого доступа: F5) и увидите вывод. Поздравляем, вы успешно запустили свою первую программу Python на Windows.
- ТЕГИ
- Скачать и установить Python
2. Using the Python Interpreter¶
The Python interpreter is usually installed as /usr/local/bin/python3.11 on those machines where it is available; putting /usr/local/bin in your Unix shell’s search path makes it possible to start it by typing the command:
python3.11
to the shell. 1 Since the choice of the directory where the interpreter lives is an installation option, other places are possible; check with your local Python guru or system administrator. (E.g., /usr/local/python is a popular alternative location.)
On Windows machines where you have installed Python from the Microsoft Store , the python3.11 command will be available. If you have the py.exe launcher installed, you can use the py command. See Excursus: Setting environment variables for other ways to launch Python.
Typing an end-of-file character ( Control — D on Unix, Control — Z on Windows) at the primary prompt causes the interpreter to exit with a zero exit status. If that doesn’t work, you can exit the interpreter by typing the following command: quit() .
The interpreter’s line-editing features include interactive editing, history substitution and code completion on systems that support the GNU Readline library. Perhaps the quickest check to see whether command line editing is supported is typing Control — P to the first Python prompt you get. If it beeps, you have command line editing; see Appendix Interactive Input Editing and History Substitution for an introduction to the keys. If nothing appears to happen, or if ^P is echoed, command line editing isn’t available; you’ll only be able to use backspace to remove characters from the current line.
The interpreter operates somewhat like the Unix shell: when called with standard input connected to a tty device, it reads and executes commands interactively; when called with a file name argument or with a file as standard input, it reads and executes a script from that file.
A second way of starting the interpreter is python -c command [arg] . , which executes the statement(s) in command, analogous to the shell’s -c option. Since Python statements often contain spaces or other characters that are special to the shell, it is usually advised to quote command in its entirety.
Some Python modules are also useful as scripts. These can be invoked using python -m module [arg] . , which executes the source file for module as if you had spelled out its full name on the command line.
When a script file is used, it is sometimes useful to be able to run the script and enter interactive mode afterwards. This can be done by passing -i before the script.
All command line options are described in Command line and environment .
2.1.1. Argument Passing¶
When known to the interpreter, the script name and additional arguments thereafter are turned into a list of strings and assigned to the argv variable in the sys module. You can access this list by executing import sys . The length of the list is at least one; when no script and no arguments are given, sys.argv[0] is an empty string. When the script name is given as ‘-‘ (meaning standard input), sys.argv[0] is set to ‘-‘ . When -c command is used, sys.argv[0] is set to ‘-c’ . When -m module is used, sys.argv[0] is set to the full name of the located module. Options found after -c command or -m module are not consumed by the Python interpreter’s option processing but left in sys.argv for the command or module to handle.
2.1.2. Interactive Mode¶
When commands are read from a tty, the interpreter is said to be in interactive mode. In this mode it prompts for the next command with the primary prompt, usually three greater-than signs ( >>> ); for continuation lines it prompts with the secondary prompt, by default three dots ( . ). The interpreter prints a welcome message stating its version number and a copyright notice before printing the first prompt:
$ python3.11 Python 3.11 (default, April 4 2021, 09:25:04) [GCC 10.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>>
Continuation lines are needed when entering a multi-line construct. As an example, take a look at this if statement:
>>> the_world_is_flat = True >>> if the_world_is_flat: . print("Be careful not to fall off!") . Be careful not to fall off!
For more on interactive mode, see Interactive Mode .
2.2. The Interpreter and Its Environment¶
2.2.1. Source Code Encoding¶
By default, Python source files are treated as encoded in UTF-8. In that encoding, characters of most languages in the world can be used simultaneously in string literals, identifiers and comments — although the standard library only uses ASCII characters for identifiers, a convention that any portable code should follow. To display all these characters properly, your editor must recognize that the file is UTF-8, and it must use a font that supports all the characters in the file.
To declare an encoding other than the default one, a special comment line should be added as the first line of the file. The syntax is as follows:
# -*- coding: encoding -*-
where encoding is one of the valid codecs supported by Python.
For example, to declare that Windows-1252 encoding is to be used, the first line of your source code file should be:
# -*- coding: cp1252 -*-
One exception to the first line rule is when the source code starts with a UNIX “shebang” line . In this case, the encoding declaration should be added as the second line of the file. For example:
#!/usr/bin/env python3 # -*- coding: cp1252 -*-
On Unix, the Python 3.x interpreter is by default not installed with the executable named python , so that it does not conflict with a simultaneously installed Python 2.x executable.
Table of Contents
- 2. Using the Python Interpreter
- 2.1. Invoking the Interpreter
- 2.1.1. Argument Passing
- 2.1.2. Interactive Mode
- 2.2.1. Source Code Encoding
Первая программа на Python «Hello world»
В настоящее время используются только версия Python 3. Разработка и поддержка Python 2 прекращены, так что мы работаем с третей версией во всех статьях.
В какой-то момент ваших приключений в программировании вы, в конце концов, столкнетесь с Python 2. Не беспокойтесь. Есть несколько важных отличий, о которых вы можете почитать здесь.
Если вы используете Apple или Linux, у вас уже установлен Python 2.7 и 3.6+ (в зависимости от версии OS). Некоторые версии Windows идут в комплекте с Python, но вам также потребуется установить Python 3.
Он очень прост в установке на Linux. В терминале запустите:
$ sudo apt-get install python3 idle3
Это установит Python и IDLE для написания кода.
Для Windows и Apple я предлагаю вам обратиться к официальной документации, где вы найдете подробные инструкции: https://www.python.org/download
Запуск IDLE
IDLE означает «Интегрированная среда разработки». В вашей карьере программирования вы столкнетесь с многочисленными интегрированными средами разработки, хотя за пределами Python они называются IDE.
- Если у вас Windows, выберите IDLE из меню «Пуск».
- Для Mac OS, вы можете найти IDLE в приложениях > Python 3.
- Если у вас Linux, выберите IDLE из меню > Программирование > IDLE (используя Python 3.*).
Для Mac OS и Linux, в терминале, воспользуйтесь:
$ idle3
Когда вы впервые запускаете IDLE, вы видите примерно следующее на экране:
Это оболочка Python. А три стрелки называются шевронами.
Они означают приглашение интерпретатора, в который вы вводите команды.
Как написать “Hello, World!”
Классическая первая программа — «Hello, World!» . Давайте придерживаться традиции. Введите следующую команду и нажмите Enter:
При подготовке материала использовались источники:
https://pythonru.com/baza-znanij/gde-skachat-python-i-kak-ego-ustanovit-na-linux-mac-os-windows
https://docs.python.org/3/tutorial/interpreter.html
https://pythonru.com/uroki/pervaja-programma-na-python-hello-world
- 2.1. Invoking the Interpreter