Первая программа (Your First Python Program)
Словарь урока (Lesson Vocabulary)
- program — программа
- code — код
- print — вывод, печать
- syntax — синтаксис
- run — запускать
- execute — выполнять
- script — скрипт
- error — ошибка
Введение (Introduction)
Добро пожаловать во второй урок нашего курса! Сегодня мы напишем нашу первую программу на Python и запустим её. Это будет простая программа "Hello, World!", которая является традиционным первым шагом в изучении любого языка программирования.
Welcome to the second lesson of our course! Today, we will write our first Python program and run it. It will be a simple "Hello, World!" program, which is a traditional first step in learning any programming language.
Что такое программа? (What is a Program?)
Программа — это набор инструкций, которые компьютер выполняет для достижения определенной цели. В случае с Python, эти инструкции записываются в виде текстовых файлов с расширением .py.
A program is a set of instructions that a computer executes to achieve a specific goal. In the case of Python, these instructions are written as text files with the .py extension.
Создание первой программы (Creating Your First Program)
Давайте создадим нашу первую программу на Python. Для этого нам понадобится текстовый редактор или IDE, которые мы установили в предыдущем уроке.
Let's create our first Python program. For this, we will need a text editor or IDE that we installed in the previous lesson.
Шаг 1: Создание файла (Step 1: Creating a File)
- Откройте ваш текстовый редактор (например, Visual Studio Code, PyCharm или даже стандартный Блокнот/Notepad).
Open your text editor (e.g., Visual Studio Code, PyCharm, or even standard Notepad). - Создайте новый файл.
Create a new file. - Сохраните этот файл с именем
hello.py. Убедитесь, что расширение файла именно.py, а не.txt.
Save this file with the namehello.py. Make sure the file extension is.py, not.txt.
Шаг 2: Написание кода (Step 2: Writing Code)
В файле hello.py напишите следующую строку кода:
In the hello.py file, write the following line of code:
print("Hello, World!")Это простая команда, которая выводит текст "Hello, World!" на экран. Давайте разберем её:
This is a simple command that displays the text "Hello, World!" on the screen. Let's break it down:
print()— это встроенная функция Python, которая выводит информацию в консоль.print()is a built-in Python function that outputs information to the console."Hello, World!"— это строка текста (строковый литерал), которую мы хотим вывести. Строки в Python заключаются в двойные или одинарные кавычки."Hello, World!"is a text string (string literal) that we want to output. Strings in Python are enclosed in double or single quotes.
Шаг 3: Запуск программы (Step 3: Running the Program)
Теперь давайте запустим нашу программу. Это можно сделать несколькими способами, в зависимости от того, какую среду разработки вы используете.
Now, let's run our program. This can be done in several ways, depending on which development environment you're using.
Запуск из командной строки (Running from Command Line)
- Откройте командную строку (терминал).
Open a command line (terminal). - Перейдите в директорию, где сохранен файл
hello.py, используя командуcd. Например:
Navigate to the directory where thehello.pyfile is saved using thecdcommand. For example:
или на Mac/Linux:cd C:\Users\YourName\Documentscd /home/username/documents - Запустите программу с помощью команды:
Run the program using the command:
илиpython hello.pypython3 hello.py
Запуск из IDE (Running from IDE)
Если вы используете IDE, как PyCharm или Visual Studio Code, вы можете запустить программу, нажав кнопку "Run" или используя горячие клавиши (обычно F5 или Ctrl+F5).
If you're using an IDE like PyCharm or Visual Studio Code, you can run the program by clicking the "Run" button or using keyboard shortcuts (usually F5 or Ctrl+F5).
Шаг 4: Проверка результата (Step 4: Checking the Result)
После запуска программы вы должны увидеть текст Hello, World! в консоли или в окне вывода вашей IDE.
After running the program, you should see the text Hello, World! in the console or in the output window of your IDE.
Hello, World!
Поздравляем! Вы только что написали и запустили свою первую программу на Python!
Congratulations! You have just written and run your first Python program!
Расширение программы (Expanding the Program)
Давайте немного расширим нашу программу, добавив ещё несколько строк:
Let's expand our program a bit by adding a few more lines:
print("Hello, World!")
print("Welcome to Python programming!")
print("This is my first program.")Сохраните изменения и запустите программу снова. Теперь вы должны увидеть три строки текста:
Save the changes and run the program again. Now you should see three lines of text:
Hello, World!
Welcome to Python programming!
This is my first program.
Вывод специальных символов (Printing Special Characters)
В Python есть несколько специальных символов, которые можно использовать для форматирования вывода. Один из самых распространенных — символ новой строки \n:
Python has several special characters that can be used to format output. One of the most common is the newline character \n:
print("Line 1 \n Line 2 \n Line 3")При запуске этого кода вы увидите:
When running this code, you will see:
Line 1
Line 2
Line 3
Обработка ошибок (Error Handling)
Что произойдет, если мы допустим ошибку в нашем коде? Давайте попробуем написать команду print с ошибкой:
What happens if we make a mistake in our code? Let's try writing the print command with an error:
print "Hello, World!")При запуске этого кода вы получите сообщение об ошибке, примерно такое:
When running this code, you will get an error message like this:
File "hello.py", line 1
print "Hello, World!")
^
SyntaxError: Missing parentheses in call to 'print'. Did you mean print("Hello, World!")?
Это сообщение об ошибке говорит о том, что мы пропустили открывающую скобку в вызове функции print. Python даже предлагает нам исправление: print("Hello, World!").
This error message says that we missed the opening parenthesis in the print function call. Python even suggests a correction: print("Hello, World!").
Внимательно читайте сообщения об ошибках — они часто содержат полезную информацию о том, что пошло не так и как это исправить.
Read error messages carefully—they often contain useful information about what went wrong and how to fix it.
Интересный факт (Fun Fact)
Традиция начинать изучение языка программирования с программы "Hello, World!" была введена в учебнике по языку C, написанном Брайаном Керниганом и Деннисом Ритчи в 1978 году.
The tradition of starting to learn a programming language with a "Hello, World!" program was introduced in a C language textbook written by Brian Kernighan and Dennis Ritchie in 1978.
Подведение итогов (Summary)
В этом уроке мы:
In this lesson, we:
- Создали нашу первую программу на Python
Created our first Python program - Научились использовать функцию
print()для вывода текста
Learned how to use theprint()function to output text - Узнали о строковых литералах и специальных символах
Learned about string literals and special characters - Познакомились с сообщениями об ошибках и их интерпретацией
Got acquainted with error messages and their interpretation
Хотя наша первая программа очень проста, это важный шаг в изучении Python. В следующих уроках мы будем постепенно добавлять новые концепции и возможности языка.
Although our first program is very simple, it's an important step in learning Python. In the following lessons, we will gradually add new language concepts and features.
Проверь себя (Check Yourself)
- Какое расширение имеют файлы Python?
What extension do Python files have? - Какая функция используется для вывода текста в консоль?
Which function is used to output text to the console? - Что означает символ
\nв строке Python?
What does the\nsymbol mean in a Python string? - Как запустить Python-скрипт из командной строки?
How do you run a Python script from the command line?
Практическое задание (Practice Task)
Создайте программу about_me.py, которая выводит информацию о вас. Программа должна выводить:
Create an about_me.py program that outputs information about you. The program should output:
- Ваше имя
Your name - Ваш возраст
Your age - Ваше хобби
Your hobby - Почему вы изучаете Python
Why you are learning Python
Используйте функцию print() для каждой строки информации. Попробуйте также использовать символ новой строки \nдля объединения нескольких строк в одном вызове print().
Use the print() function for each line of information. Also try using the newline character \nto combine multiple lines in a single print() call.
Практические задания (Practice Tasks)
Какой символ используется для комментариев в Python? (Which symbol is used for comments in Python?)
Что выведет функция print('Hello' + 'World')? (What will print('Hello' + 'World') output?)
Какой результат будет у выражения 2 + 3 * 4? (What will be the result of 2 + 3 * 4?)
Вывод нескольких строк (Multiple Lines Output)
print("Привет, мир!")
print("Добро пожаловать в Python!")
print("Давайте учиться программировать!")Использование end (Using end)
print("Привет", end=" ")
print("мир", end="!")
print() # Переход на новую строкуИспользование sep (Using sep)
print("Python", "is", "awesome", sep="-")