- How To Write Your First Python 3 Program
- Prerequisites
- Writing the “Hello, World!” Program
- Running the “Hello, World!” Program
- Conclusion
- Tutorial Series: How To Code in Python
- Introduction
- Prerequisites
- Первая программа на Python «Hello world»
- Запуск IDLE
- Как написать “Hello, World!”
- Python Hello World
- Creating a new Python project
- What is a function
- Executing the Python Hello World program
- Python IDLE
- Summary
How To Write Your First Python 3 Program
The “Hello, World!” program is a classic and time-honored tradition in computer programming. Serving as a simple and complete first program for beginners, as well as a good program to test systems and programming environments, “Hello, World!” illustrates the basic syntax of programming languages.
This tutorial will walk you through writing a “Hello, World” program in Python 3.
Prerequisites
You should have Python 3 installed and a programming environment set up on your computer or server. If you don’t have a programming environment set up, you can refer to the installation and setup guides for a local programming environment or for a programming environment on your server appropriate for your operating system (Ubuntu, CentOS, Debian, etc.)
Writing the “Hello, World!” Program
To write the “Hello, World!” program, let’s open up a command-line text editor such as nano and create a new file:
Once the text file opens up in the terminal window we’ll type out our program:
Let’s break down the different components of the code.
print() is a function that tells the computer to perform an action. We know it is a function because it uses parentheses. print() tells Python to display or output whatever we put in the parentheses. By default, this will output to the current terminal window.
Some functions, like the print() function, are built-in functions included in Python by default. These built-in functions are always available for us to use in programs that we create. We can also define our own functions that we construct ourselves through other elements.
Inside the parentheses of the print() function is a sequence of characters — Hello, World! — that is enclosed in quotation marks. Any characters that are inside of quotation marks are called a string.
Once we are done writing our program, we can exit nano by typing the control and x keys, and when prompted to save the file press y .
Once you exit out of nano you’ll return to your shell.
Running the “Hello, World!” Program
With our “Hello, World!” program written, we are ready to run the program. We’ll use the python3 command along with the name of our program file. Let’s run the program:
The hello.py program that you created will cause your terminal to produce the following output:
Let’s go over what the program did in more detail.
Python executed the line print(«Hello, World!») by calling the print() function. The string value of Hello, World! was passed to the function.
In this example, the string Hello, World! is also called an argument since it is a value that is passed to a function.
The quotes that are on either side of Hello, World! were not printed to the screen because they are used to tell Python that they contain a string. The quotation marks delineate where the string begins and ends.
Since the program ran, you can now confirm that Python 3 is properly installed and that the program is syntactically correct.
Conclusion
Congratulations! You have written the “Hello, World!” program in Python 3.
From here, you can continue to work with the print() function by writing your own strings to display, and can also create new program files.
Keep learning about programming in Python by reading our full tutorial series How To Code in Python 3.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
Tutorial Series: How To Code in Python
Introduction
Python is a flexible and versatile programming language that can be leveraged for many use cases, with strengths in scripting, automation, data analysis, machine learning, and back-end development. It is a great tool for both new learners and experienced developers alike.
Prerequisites
You should have Python 3 installed and a programming environment set up on your computer or server. If you don’t have a programming environment set up, you can refer to the installation and setup guides for a local programming environment or for a programming environment on your server appropriate for your operating system (Ubuntu, CentOS, Debian, etc.)
Первая программа на 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, в терминале, воспользуйтесь:
Когда вы впервые запускаете IDLE, вы видите примерно следующее на экране:
Это оболочка Python. А три стрелки называются шевронами.
Они означают приглашение интерпретатора, в который вы вводите команды.
Как написать “Hello, World!”
Классическая первая программа — «Hello, World!» . Давайте придерживаться традиции. Введите следующую команду и нажмите Enter:
Python Hello World
Summary: in this tutorial, you’ll learn how to develop the first program in Python called “Hello, World!”.
If you can write “hello world” you can change the world.
Raghu Venkatesh
Creating a new Python project
First, create a new folder called helloworld .
Second, launch the VS code and open the helloworld folder.
Third, create a new app.py file and enter the following code and save the file:
print('Hello, World!')
Code language: Python (python)
The print() is a built-in function that displays a message on the screen. In this example, it’ll show the message ‘Hello, Word!’ .
What is a function
When you sum two numbers, that’s a function. And when you multiply two numbers, that’s also a function.
Each function takes your inputs, applies some rules, and returns a result.
In the above example, the print() is a function. It accepts a string and shows it on the screen.
Python has many built-in functions like the print() function to use them out of the box in your program.
In addition, Python allows you to define your functions, which you’ll learn how to do it later.
Executing the Python Hello World program
To execute the app.py file, you first launch the Command Prompt on Windows or Terminal on macOS or Linux.
Then, navigate to the helloworld folder.
After that, type the following command to execute the app.py file:
python app.py
Code language: Python (python)
If you use macOS or Linux, you use python3 command instead:
python3 app.py
Code language: CSS (css)
If everything is fine, you’ll see the following message on the screen:
Hello, World!
Code language: Python (python)
If you use VS Code, you can also launch the Terminal within the VS code by:
- Accessing the menu Terminal > New Terminal
- Or using the keyboard shortcut Ctrl+Shift+` .
Typically, the backtick key ( ` ) locates under the Esc key on the keyboard.
Python IDLE
Python IDLE is the Python Integration Development Environment (IDE) that comes with the Python distribution by default.
The Python IDLE is also known as an interactive interpreter. It has many features such as:
In short, the Python IDLE helps you experiment with Python quickly in a trial-and-error manner.
The following shows you step by step how to launch the Python IDLE and use it to execute the Python code:
First, launch the Python IDLE program:
A new Python Shell window will display as follows:
Now, you can enter the Python code after the cursor >>> and press Enter to execute it.
For example, you can type the code print(‘Hello, World!’) and press Enter , you’ll see the message Hello, World! immediately on the screen:
Summary
- Use the python app.py command from the Command Prompt on Windows or Terminal on macOS or Linux to execute the app.py file.
- Use the print() function to show a message on the screen.
- Use the Python IDLE to type Python code and execute it immediately.