Скрипт hello world python

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:

Читайте также:  Most used html elements

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

Python banner image

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

Это оболочка Python. А три стрелки называются шевронами.

Они означают приглашение интерпретатора, в который вы вводите команды.

Как написать “Hello, World!”

Классическая первая программа — «Hello, World!» . Давайте придерживаться традиции. Введите следующую команду и нажмите Enter:

Источник

Hello World Programming Tutorial for Python

Estefania Cassingena Navone

Estefania Cassingena Navone

Hello World Programming Tutorial for Python

🔹 Hello, World!

Hi! if you are reading this article, then you are probably starting to dive into the amazing world of programming and computer science. That’s great.

In this article, you will learn:

  • How to write your first «Hello, World!» program in Python.
  • How to save your code in a Python file.
  • How to run your code.

Writing this program when you are starting to learn how to code is a tradition in the developer community.

Enjoy this moment because it will definitely be part of your memories in the coming months and years when you remember your first steps.

🔸 «Hello, World!» in the Python Shell

Step 1: Start IDLE

During this article, we will work with IDLE (Python’s Integrated Development and Learning Environment), which is automatically installed when you install Python. This is where you will write and run your Python code.

The first thing that you need to do is to open IDLE. You will immediately see the screen shown below.

This is called the Python shell (interactive interpreter). It is an interactive window where you can enter lines or blocks of code and run them immediately to see their effect and output.

image-92

💡 Tip: By default, you will see a smaller font size. You can customize this in «Options > Configure IDLE».

Step 2: Display the Message

You need to tell the program that you want to display a specific message by writing the appropriate line of code.

In Python, we use print() to do this:

image-182

  • First, we write print .
  • Then, within parentheses, we write the message or value that we want to display.

💡 Tip: The message «Hello, World!» is surrounded by double quotation marks because it is represented as a string , a data type that is used to represent sequences of characters in your code (for example, text).

Step 3: See the Output

You will see the following output if you write this line of code in the Python shell and press enter:

image-89

💡 Tip: You will notice that the color of the message inside print() changes to green when you add the last quotation mark.

This occurs because IDLE assigns different colors to the different types of elements that you can write in your code (notice that print is displayed in purple). This is called «syntax highlighting».

Great! You just wrote your first «Hello, World!» program in Python.

If you want to save it in order to run it later (or just to keep it as a nice memory of your first Python program!), you will need to create a Python file, so let’s see how you can do that.

🔹 «Hello, World!» in a Python File

Step 1: Create a File

To create a Python file in IDLE, you need to:

💡 Tips: You can also use the keyboard shortcut Ctrl + N .

image-188

After you click on New File , you will immediately see a new file where you can write your code:

image-190

Step 2: Write the Code

In the new file, write this line of code to print «Hello, World!» :

image-191

💡 Tip: The thick vertical black line shows where the cursor is currently at.

Step 3: Save the File

Save the new file by clicking on File > Save or by using the keyboard shortcut Ctrl + S . You will need to write a name for your file and choose where you want to save it.

image-192

After saving the file, you will see something very similar to this in the folder that you selected:

image-195

💡 Tips: By default, line numbers will not be displayed in the file. If you would like to display them (like in the images above) go to Options > Configure IDLE > General > Check the «Show line numbers in new windows» box.

Step 4: Run the Program

Now you can run your file by clicking on Run > Run Module:

image-93

A new window will be opened and you should see the output of your program in blue:

image-97

Now your program is safely stored in a Python file and you can run it whenever you need to.

🔸 Customize Your Program

You can customize your program to make it unique. You just need to edit the Python file and change the string.

For example, you can add your name after Hello, World! :

image-99

If you run the file, you will see the string displayed in the Python shell:

image-96

🔹 First Python Program Completed

Awesome work. You just wrote your first Python program.

Programming and Computer Science will be key for the future of humanity. By learning how to code, you can shape that future.

You’ll create amazing new products and platforms, and help take us one step further towards a world where technology will be part of every single aspect of our daily lives.

To learn more about the coding uses of Python, you might like to read my article «What is Python Used For? 10+ Coding Uses for the Python Programming Language»

I really hope that you liked my article and found it helpful. Follow me on Twitter @EstefaniaCassN and check out my online courses. ⭐️

Источник

Оцените статью