Python hello world windows

Первые шаги¶

Давайте посмотрим, как создать традиционную программу «Hello World» на Python. Это научит вас писать, сохранять и выполнять программы на Python.

Существует два способа запуска программ на Python: использование интерактивного приглашения интерпретатора и использование файла с текстом программы. Сейчас мы увидим, как пользоваться обоими методами.

Использование командной строки интерпретатора¶

Откройте окно терминала (как было описано в главе Установка) и запустите интерпретатор Python, введя команду python3 и нажав Enter.

Пользователи Windows могут запустить интерпретатор в командной строке, если установили переменную PATH надлежащим образом. Чтобы открыть командную строку в Windows, зайдите в меню «Пуск» и нажмите «Выполнить…». В появившемся диалоговом окне введите «cmd» и нажмите Enter; теперь у вас будет всё необходимое для начала работы с python в командной строке DOS.

Если вы используете IDLE, нажмите «Пуск» → «Программы» → «Python 3.0» → «IDLE (Python GUI)».

Как только вы запустили python3, вы должны увидеть >>> в начале строки, где вы можете что-то набирать. Это и называется командной строкой интерпретатора Python.

Теперь введите print('Hello World') и нажмите клавишу Enter. В результате должны появиться слова «Hello World».

Вот пример того, что вы можете увидеть на экране, если будете использовать компьютер с Mac OS X. Информация о версии Python может отличаться в зависимости от компьютера, но часть, начинающаяся с приглашения (т. е. от >>> и далее) должна быть одинаковой на всех операционных системах.

$ python3
Python 3.3.0 (default, Oct 22 2012, 12:20:36)
[GCC 4.2.1 Compatible Apple Clang 4.0 ((tags/Apple/clang-421.0.60))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> print('hello world')
hello world
>>>

Обратите внимание, что Python выдаёт результат работы строки немедленно! Вы только что ввели одиночный «оператор» Python. print используется для того, чтобы (что неудивительно1) напечатать любое переданное в него значение. В данном случае мы передали в него текст «Hello World», который и был напечатан на экране.

Как выйти из командной строки интерпретатора

Если вы используете IDLE или оболочку GNU/Linux или BSD, вы можете выйти из командной строки интерпретатора нажатием Ctrl-D или введя команду exit() (примечание: не забудьте написать скобки, «()»), а затем нажав клавишу Enter. Если вы используете командную строку Windows, нажмите Ctrl-Z, а затем нажмите клавишу Enter.

Выбор редактора¶

Поскольку мы не можем набирать программу в командной строке интерпретатора каждый раз, когда нам нужно что-то запустить, нам понадобится сохранять программы в файлах, чтобы потом иметь возможность запускать их сколько угодно раз.

Прежде чем приступить к написанию программ на Python в файлах, нам нужен редактор для работы с файлами программ. Выбор редактора крайне важен. Подходить к выбору редактора следует так же, как и к выбору личного автомобиля. Хороший редактор поможет вам легко писать программы на Python, делая ваше путешествие более комфортным, а также позволяя быстрее и безопаснее достичь вашей цели.

Одно из самых основных требований — это подсветка синтаксиса, когда разные элементы программы на Python раскрашены так, чтобы вы могли легко видеть вашу программу и ход её выполнения.

Если вы не знаете, с чего начать, я бы порекомендовал воспользоваться программой Komodo Edit, которая доступна для Windows, Mac OS X и GNU/Linux.

Если вы пользуетесь Windows, Не используйте Блокнот — это плохой выбор, поскольку он не обладает функцией подсветки синтаксиса, а также не позволяет автоматически вставлять отступы, что очень важно в нашем случае, как мы увидим позже. Хорошие редакторы, как Komodo Edit, позволяют делать это автоматически.

Опытные программисты, должно быть, уже используют Vim или Emacs. Не стоит даже и говорить, что это два наиболее мощных редактора, и вы только выиграете от их использования для написания программ на Python. Лично я пользуюсь ими обоими для большинства своих программ, и даже написал книгу о Vim. Я настоятельно рекомендую вам решиться и потратить время на изучение Vim или Emacs, поскольку это будет приносить вам пользу долгие годы. Однако, как я уже писал выше, новички могут пока просто остановиться на Komodo Edit и сосредоточиться на изучении Python, а не текстового редактора.

Я повторюсь ещё раз: обязательно выберите подходящий редактор — это сделает написание программ на Python более простым и занимательным.

Для пользователей Vim

Существует хорошее введение в использование Vim как мощного IDE для Python, автор — John M Anderson. Также я рекомендую плагин jedi-vim и мой собственный конфигурационный файл.

Для пользователей Emacs

Существует хорошее введение в использование Emacs как мощного IDE для Python, автор — Ryan McGuire. Также я рекомендую Конфигурацию dotemacs от BG.

Использование программных файлов¶

А теперь давайте вернёмся к программированию. Существует такая традиция, что какой бы язык программирования вы ни начинали учить, первой вашей программой должна быть программа «Привет, Мир!». Это программа, которая просто выводит надпись «Привет, Мир!». Как сказал Simon Cozens2, это «традиционное заклинание богов программирования, которое поможет вам лучше изучить язык».

Запустите выбранный вами редактор, введите следующую программу и сохраните её под именем helloworld.py .

Если вы пользуетесь Komodo Edit, нажмите «Файл» → «Новый» → «Новый файл», введите строку:

В Komodo Edit нажмите «Файл» → «Сохранить» для сохранения файла.

Куда сохранить файл? В любую папку, расположение которой вы знаете. Если вы не понимаете, что это значит, то создайте новую папку и используйте её для всех ваших программ на Python:

  • C:\py в Windows
  • /tmp/py в GNU/Linux
  • /tmp/py в Mac OS X

Чтобы создать папку, воспользуйтесь командой mkdir в терминале. Например, mkdir /tmp/py.

Не забывайте указывать расширение файла .py. Например, «file.py«.

В Komodo Edit нажмите «Инструменты» → «Запуск команды», наберите python3 helloworld.py и нажмите «Выполнить». Вы должны увидеть вывод, показанный на скриншоте ниже.

Screenshot of Komodo Edit with the Hello World program

Но всё-таки лучше редактировать программу в Komodo Edit, а запускать в терминале:

  1. Откройте терминал, как описано в главе Установка.
  2. Перейдите в каталог, в котором вы сохранили файл. Например, cd /tmp/py.
  3. Запустите программу, введя команду python3 helloworld.py.

Вывод программы показан ниже.

$ python3 helloworld.py
Привет, Мир!

Если у вас получился такой же вывод, поздравляю! — вы успешно выполнили вашу первую программу на Python. Вы только что совершили самый сложный шаг в обучении программированию, заключающийся в написании своей первой программы!

Если вы получите сообщение об ошибке, введите вышеуказанную программу в точности так, как показано здесь, и запустите снова. Обратите внимание, что Python различает регистр букв, то есть print — это не то же самое, что Print (обратите внимание на букву p в нижнем регистре в первом случае и на букву P в верхнем регистре во втором). Также убедитесь, что перед первым символом в строке нет пробелов или символов табуляции — позже мы увидим, почему это важно.

Как это работает

Программа на Python состоит из выражений. В нашей первой программе имеется всего лишь одно выражение. В этом выражении мы вызываем функцию print, которая просто выводит текст 'Привет, Мир!'. О функциях мы узнаем в одной из последующих глав, а пока вам достаточно понять, что всё, что вы укажете в скобках, будет выведено на экран. В данном примере мы указали 'Привет, Мир!'.

Python никак не обрабатывает комментарии, кроме специального случая в первой строке. Она называется »строка shebang»; когда первые два символа файла с программой — #!, за которыми следует путь к некоторой программе, это указывает вашей Unix-подобной системе, что вашу программу нужно запускать именно в этом интерпретаторе, когда вы »исполняете» её. Это объясняется подробно в следующем параграфе. Помните, что вы всегда можете запустить свою программу на любой платформе, указав интерпретатор напрямую в командной строке, как например, команда python helloworld.py .

Важно! Вставляйте разумные комментарии в ваши программы, чтобы объяснить некоторые важные детали вашей программы — это будет полезно для тех, кто будет читать вашу программу, так как им легче будет понять, что программа делает. Помните, что таким человеком можете оказаться вы сами через полгода!

Исполнимые программы на Python¶

Это касается только пользователей GNU/Linux и Unix, но пользователям Windows тоже будет полезно об этом знать.

Каждый раз, когда нам нужно запустить программу на Python, нам приходится в явном виде запускать python3 foo.py. Но почему бы нам не запускать её точно так же, как и все другие программы? Этого можно достичь при помощи так называемого hashbang.

Добавьте строку, указанную ниже, в самое начало вашей программы:

Теперь ваша программа должна выглядеть так:

#!/usr/bin/env python3
print('Привет, Мир!')

Теперь необходимо установить программе атрибут исполнимости, используя команду chmod, а затем выполнить программу.

Команда chmod здесь используется для изменения режима файла3 добавлением атрибута исполнимости для всех пользователей в системе4.

$ chmod a+x helloworld.py

После этого мы можем запускать программу напрямую, потому что наша операционная система запустит /usr/bin/env, который, в свою очередь, найдёт Python 3, а значит, сможет запустить наш файл.

$ ./helloworld.py
Привет, Мир!

Здесь «./» обозначает, что программа находится в текущем каталоге.

Ради интереса можете даже переименовать файл в просто «helloworld» и запустить его как ./helloworld, и это также сработает, поскольку система знает, что запускать программу нужно интерпретатором, положение которого указано в первой строке файла программы.

Но до сих пор мы могли выполнять свою программу только если знали полный путь к ней. А что, если нам нужно запускать эту программу из любого каталога? Это можно организовать, расположив свою программу в одном из каталогов, перечисленных в переменной окружения PATH.

При попытке запуска какой-либо программы система ищет её в каталогах, перечисленных в переменной окружения PATH, и запускает. Таким образом, мы можем сделать программу доступной из любого места, скопировав её в один из каталогов, перечисленных в PATH.

$ echo $PATH
/usr/local/bin:/usr/bin:/bin:/usr/X11R6/bin:/home/swaroop/bin
$ cp helloworld.py /home/swaroop/bin/helloworld
$ helloworld
Привет, Мир!

Мы можем вывести на экран значение переменной PATH при помощи команды echo, добавив перед именем переменной символ $, чтобы указать оболочке, что мы хотим получить значение этой переменной. Мы видим, что /home/swaroop/bin — один из каталогов в переменной PATH, где swaroop — это имя пользователя, которое я использую в своей системе. В вашей системе, скорее всего, будет аналогичный каталог для вашего пользователя.

Вы также можете добавить какой-либо каталог к переменной PATH — это можно сделать, выполнив PATH=$PATH:/home/swaroop/mydir, где '/home/swaroop/mydir' — это каталог, который я хочу добавить к переменной PATH.

Этот метод полезен для написания сценариев, которые будут доступны для запуска в любой момент из любого места. По сути, это равносильно созданию собственных команд, как cd или любой другой, которые часто используются в терминале GNU/Linux или приглашении DOS.

Когда речь идёт о Python, слова «программа» или «сценарий (скрипт)» обозначают одно и то же.

Получение помощи¶

Для быстрого получения информации о любой функции или операторе Python служит встроенная функция help. Это особенно удобно при использовании командной строки интерпретатора. К примеру, выполните help(print) — это покажет справку по функции print, которая используется для вывода на экран.

Для выхода из справки нажмите q.

Аналогичным образом можно получить информацию почти о чём угодно в Python. При помощи функции help() можно даже получить описание самой функции help!

Если вас интересует информация об операторах, как например, return, их необходимо указывать в кавычках (например, help('return')), чтобы Python понял, чего мы хотим.

Резюме¶

Теперь вы умеете с лёгкостью писать, сохранять и запускать программы на Python.

И поскольку сейчас вы уже используете Python, давайте узнаем больше о его основных принципах.

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 directory called helloworld anywhere in your system, e.g., C:\ drive.

Second, launch the VS Code and open the helloworld directory.

Third, create a new app.py file, enter the following code, and save it:

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, World!'.

What is a function #

When you sum two numbers, that’s a function. And when you multiply two numbers, that’s also a function. Generally, a 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 you can use 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 directory.

After that, type the following command to execute the app.py file:

python app.pyCode language: Python (python)

If you use macOS or Linux, you use python3 command instead:

python3 app.pyCode 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 (`) located 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:

  • Code editing with syntax highlighting
  • Smart indenting
  • And auto-completion

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:

A new Python Shell window will display as follows:

IDLE Shell

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:

IDLE Shell - hello world

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.

Was this tutorial helpful ?

Last Updated :
02 Apr, 2025

When we are just starting out with Python, one of the first programs we’ll learn is the classic “Hello, World!” program. It’s a simple program that displays the message “Hello, World!” on the screen.

Here’s the “Hello World” program:

Python

print("Hello, World!")

How does this work:

print-hello-world

Hello World

  • print() is a built-in function in Python that tells the program to display something on the screen. We need to add the string in parenthesis of print() function that we are displaying on the screen.
  • “Hello, World!” is a string text that you want to display. Strings are always enclosed in quotation marks.

There are two more ways to print the same string “Hello World” :

Python

# Using Single Quote
print('Hello World')

# Using Triple Quotes
print('''Hello World''')

Both the above methods work same as the first method that is the double quotes method.

Try it Yourself:

Try printing your name following the same steps as given above. Use all the three methods to print your name.

Python

# Edit this code and try to print Your Name
print()

Looking to start your programming journey or elevate your Python expertise? Boot.dev’s Complete Python Course offers dynamic, project-driven approach to mastering Python. Perfect for aspiring developers or anyone looking to level up their Python skills. Take the leap into a future-ready career-enroll today and code with confidence!

Similar Reads

  • Python program to print calendar of given year

    Given a valid year as input, write a Python program to print the calendar of given year. In order to do this, we can simply use calendar module provided in Python. For more details about calendar module, refer this article. # Python program to print calendar for given year # importing calendar libra


    3 min read

  • Python Program to Find and Print Address of Variable

    In this article, we are going to see how to find and print the address of the Python variable. It can be done in these ways: Using id() functionUsing addressof() functionUsing hex() functionMethod 1: Find and Print Address of Variable using id()We can get an address using id() function, id() functio


    2 min read

  • Python Program for word Guessing Game

    Learn how to create a simple Python word-guessing game, where players attempt to guess a randomly selected word within a limited number of tries. Word guessing Game in PythonThis program is a simple word-guessing game where the user has to guess the characters in a randomly selected word within a li


    5 min read

  • Python program to print current year, month and day

    In this article, the task is to write a Python Program to print the current year, month, and day. Approach: In Python, in order to print the current date consisting of a year, month, and day, it has a module named datetime. From the DateTime module, import date classCreate an object of the date clas


    1 min read

  • Output of Python Program | Set 1

    Predict the output of following python programs: Program 1: [GFGTABS] Python r = lambda q: q * 2 s = lambda q: q * 3 x = 2 x = r(x) x = s(x) x = r(x) print (x) [/GFGTABS]Output: 24Explanation : In the above program r and s are lambda functions or anonymous functions and q is the argument to both of


    3 min read

  • Output of Python programs | Set 7

    Prerequisite — Strings in Python Predict the output of the following Python programs. These question set will make you conversant with String Concepts in Python programming language. Program 1[GFGTABS] Python var1 = ‘Hello Geeks!’ var2 = «GeeksforGeeks» print «var1[0]: «,


    3 min read

  • Output of Python programs | Set 8

    Prerequisite — Lists in Python Predict the output of the following Python programs. Program 1 [GFGTABS] Python list = [1, 2, 3, None, (1, 2, 3, 4, 5), [‘Geeks’, ‘for’, ‘Geeks’]] print len(list) [/GFGTABS]Output: 6Explanation: The beauty of python list datatype is that within


    3 min read

  • Python program to convert ASCII to Binary

    We are having a string s=»Hello» we need to convert the string to its ASCII then convert the ASCII to Binary representation so that the output becomes : 01001000 01100101 01101100 01101100 0110111. To convert an ASCII string to binary we use ord() to get the ASCII value of each character and format(


    2 min read

  • Python Tutorial | Learn Python Programming Language

    Python Tutorial – Python is one of the most popular programming languages. It’s simple to use, packed with features and supported by a wide range of libraries and frameworks. Its clean syntax makes it beginner-friendly. Python is: A high-level language, used in web development, data science, automat


    10 min read

  • Output of Python program | Set 15 (Loops)

    Prerequisite — Loops in Python Predict the output of the following Python programs. 1) What is the output of the following program? [GFGTABS] Python x = [‘ab’, ‘cd’] for i in x: i.upper() print(x) [/GFGTABS]Output:[‘ab’, ‘cd’]Explanation: The function upper() does not modify a string


    2 min read

After you’ve installed IDLE for Python, it’s time to write your first Python program with IDLE. We will write and run a simple program to print a message “Hello World” on the screen or console.

You can use another text editor, but for simplicity, we will use Python Shell’s built-in file editor (or Editor window). This is where you’ll be writing your first program to display “Hello World”.

IDLE, an integrated development environment (IDE), provides two different windows to write and run a Python program. They are:

  • Shell window
  • Editor window

Let’s understand each one in detail with example programs.

Shell Window to Create First Python Program


The shell window provides us the feature to run Python statement or instruction one by one in the interactive prompt. It allows the programmer to write one statement at a time. In the interactive prompt, we can run lines or pieces of codes before using them in a bigger program.

When we will open IDLE on your computer system, the shell window pops up. So, let’s write our first Python program to display a message, “Hello World” on the console.

Open IDLE on your computer system and write the following code below.

print("Hello World")

After writing the above code, press Enter key. As you press the Enter key, Python reads, interprets, and outputs “Hello World” on the console. If any bugs or errors are in the code, then it will display. The screenshot like below should appear.

Writing first Python program in shell window

As you can see in the above screenshot, Python use blue color to show the output, keywords in orange color, and text in quotation in green color. Thus, Python shell is useful to run one statement or a piece of codes immediately.


Note:

A prompt is a text, or a symbol used to represent the system’s readiness to execute the next input. The symbols “>>>” means the computer is waiting for a new statement.

Editor window (Script mode)


The shell window (or interactive prompt) is best to run a single line of statement at a time. It is the best place for solving mathematical expression as well.

However, we cannot write the code every time on the shell window. It is not appropriate to write multiple lines of code.

The major drawbacks of using shell window is that it does not save our code. When we close it, the code you wrote is gone forever. Therefore, if you are working on an extensive project or game, you should not use shell window.

You should use IDLE’s editor window. It will let you save your code. IDLE’s editor window also contains built-in tools to help you write your programs and troubleshoot any errors or bugs.

Using editor window (script mode), we can write multiple lines of code into a file that we can execute it later. Follow all the steps below to create, save, and run your first Python program in editor window or script mode.


(a) Launch IDLE

A shell window opens up when we start IDLE. Ignore it and click on File in the IDLE menu. Choose a New File to create a blank editor window in which we will write our program. Look at the screenshot below.

Launch IDLE


(b) Type the first line of code

Now, in the editor window, write the following line of code.

print("Hello World")

The word “print” is a Python instruction that tells the Python interpreter to print “Hello World” on the console.


(c) Save your file

Before you run your first program code, you must save it. To save it, press “Ctrl + S” or go to the File menu and choose Save option.

Save your program file


(d) Save the file

A pop-up box will open up. Write a name for your program, such as “helloworld”, and click Save, as shown in the below screenshot. Python programs often have a name ending with “.py” extension, which makes them easy to recognize.

When we save a program, Python automatically adds “.py” extension at the end, so we don’t need to write it in.

Type file name


(e) Run your first Python program

After saving the first python program, it’s time to run the program to see if it works. To run your program, click on “Run” on the menu and choose “Run Module”, as shown in the below screenshot.

Run your first python program


(f) Output

As you click on Run module, you will see the message “Hello World” in the shell window. Look at the below output as shown in the screenshot.

Output of first python program


(g) Fix mistakes

If the program code is not working properly, stay calm! Every beginner or programmer makes mistakes, and finding these “bugs” or “errors” is vital if you want to become an expert at coding.

Go back to the editor window and check your program code for typing errors. These typing errors can be in the code. They are:

  • Did you include the brackets properly?
  • Did you write the word “print” accurately?

Fix any mistakes, then attempt to run the program code again.


(h) Add more lines of code

Now, go back to the editor window and write two more lines of code in your program.

print("Hello World")
person = input("What is you name?")
print("Hello,", person)

The second line asks for your name and then stores it in a variable called person. The third line uses your name to display a new greeting. When you will run the above code, the following output will generate.

Output:
    Hello World
    What is you name? Deepak
    Hello, Deepak

(i) Final task

Run the program code again to check it. When you enter your name and press the enter/return key, the shell will display a personalized message.

Congratulations, you have completed your first Python program! You have placed your first step towards becoming a powerful Python programmer.


Writing and running your first hello world program in IDLE is an easy task. Here, you have learned step by step on how to write your first Python program with IDLE. I hope that you will have understood of writing and running your first python program in both interactive prompt and script mode.
Thanks for reading!!!

Hello World Programming Tutorial for Python

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.

Let’s begin.

🔸 «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

💡 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:

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

Image

💡 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

💡 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:

  • Open the Python Shell.
  • Click on File in the toolbar.
  • Click on New File.

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

Image

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

Image

New File Displayed

Step 2: Write the Code

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

Image

💡 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

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

Image

💡 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

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

Image

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

Great work!

🔸 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

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

Image

🔹 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. ⭐️



Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

Понравилась статья? Поделить с друзьями:
0 0 голоса
Рейтинг статьи
Подписаться
Уведомить о
guest

0 комментариев
Старые
Новые Популярные
Межтекстовые Отзывы
Посмотреть все комментарии
  • Как правильно устанавливать windows 10 с флешки
  • Какие элементы окна программы windows вам известны
  • Как посмотреть какая у тебя версия windows
  • Проецирование на этот компьютер windows 10 не работает
  • Как узнать когда установлена система windows