Write your first program

In this lesson, you will use Python IDLE to write your first program. Start IDLE and you should get a shell window, where you can write and execute commands. Traditionally, the first program you write is a program that prints the words Hello world!. To do that in Python, you can use the print() function. This function will print text in quotes within the parentheses.

So, to type Hello world! to the screen, you use the following command:

print('Hello world!')

Here is the output of the command in IDLE:

Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 24 2015, 22:43:06) [MSC v.1600 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> print('Hello world!')
Hello world!
>>>

Since the Python shell window of Python IDLE is interactive, the result of the command (Hello world!) was echoed back to the screen. This was fine, but what if we want to save our code? Well, Python IDLE offers another window, called the Edit window, where you can write the code and save it in a file, which can then be executed.

As mentioned above, print() is a function. We will talk about functions in later chapters. For now, just remember that this function will print everything that you put inside the parantheses.

 

To open an Edit window, select File > New File from the IDLE shell window:

python idle new file

This opens up a new window where you can write code. Enter the same code as above:

print('Hello world!')

Save the file by selecting File > Save. The extension of the file should be .py:

save file idle

To run the program, simply click Run > Run Module:

run module

The result of the program will be shown in the shell window, after the RESTART line:

result idle

 

You can use both single and double quotes for the text inside the parentheses in the print() function.
Geek University 2022