Hello, world!

By Martin McBride, 2018-07-22
Tags: print
Categories: python language beginning python


Introduction

The traditional first program you write when learning any programming language is a "Hello, world!" program, that simply prints a message on the screen.

About this lesson

So far we have learnt to interact with Python using the IDLE console window. We have used that to perform simple calculations using Python. That is a useful start, but it isn't really programming.

A computer program needs to be able to complete a task automatically, which means that it needs to perform a sequence of operations without any help from the user.

Here we will learn:

  • The difference between the console and edit windows in IDLE
  • How to create and run a simple Python program
  • How to display a message to the user of our program

Running the IDLE console window

We have already seen how to run the IDLE console window, in the previous lesson Using Python as a calculator.

Open up the IDLE console window as before:

Opening an edit window

IDLE has a second type of window called an edit window. This allows you to type, save and run code.

From the IDLE console window you should choose the File | New File menu item. This will open the new editing window:

You will normally keep both the console window and edit window open, and switch between them as needed:

  • The edit window is where you type in the code you want to run.
  • The console window is where you look to see any output or error messages.

Typing in your code

We are now going to write a Hello, world! program – a simple program that outputs the message "Hello, world!".

Here is the program. Type it in, exactly as shown, in the edit window.

print("Hello, world!")

This program only has one line of code. It uses the print function to display some text in the console window.

The text is stored as a string. We met strings in the previous lesson, a string is just some text enclosed in double-quote characters, like this:

"text"

Note: the text shown uses different colours to make the code easier to read. This is called syntax highlighting.

You just need to type the code in. The editor will apply syntax highlighting automatically (it might not use the exact colours that are shown above, different editors use different colours, and in IDLE you can configure the colours it uses if you wish).

Running your code

You can now run your program.

  1. Select the Run | Run Module menu item (or just use the F5 shortcut key).
  2. Before the program runs, you will be asked to save your code to file. Save it wherever you like, for example, you could save it as hello.py in the c:\temp folder.
  3. Then your code should run. You can switch back to the console window to see the output.

If you get an error message, see the hints later on.

Seeing the result

You should now look the console window, where Python displays its results:

Ignore the RESTART message, Python prints that each time it runs a new program.

Our output text is displayed in blue underneath – the text from our print statement: Hello, world!

In case of errors

Like most programming languages, Python expects a program to obey exact rules (called the Python syntax). If not, it will give an error. If your program gave an error instead of the expected result, here are some things to check:

  • You must use Python version 3.6 or later. Earlier versions might not run this code.
  • The code must be exactly as shown – any differences or missing characters can cause an error.
  • print must be at the start of the line (there shouldn't be any spaces, tabs or anything else before the word print).
  • The code should all be on one line, not split over two lines.
  • print must be in lower case. For example, typing in 'Print' with an upper case P isn't valid and will give an error.

For certain errors, Python will pop up an error window to tell you of the error. It will also mark the line where the error occurred, in the edit window.

For most errors, Python will print out an error message, in the console window. This can be useful in helping you find the error (although sometimes it can be a little cryptic). It will tell you which line the error, so you can look back at the edit window to try to find it.

Sequencing

Now we are going to write a program with more than one line. We will print a bit of information about the system. This is a very simple program, it just contains a list of instructions. Python will execute the instructions, one at a time, in the order they are written. This is called sequencing.

import sys

print("This is my first python program")
print("that has more than one line!")
print("It uses Python version", sys.version)

The import statement in the first line is needed because we are going to use a special variable later on that exists in the Python sys module. A module is just a collection of pre-existing code. We need to tell Python to get the module ready.

Then we print some messages. The third message has two parts, a text string and a value sys.version that is taken from the sys module. This value is a string that represents the version of Python you are using.

Run your program. It should display something like this in the console window:

This is my first python program
that has more than one line!
It uses Python version 3.6.0 (v3.6.0:41df79263a11, Dec 23 2016, 08:06:12) [MSC v.1900 64 bit (AMD64)]

You might recall that variable names can't contain a dot character '.'. So what is the deal with sys.version? This refers to a variable called version that lives in the sys module (the module we imported at the start of the code). The dot syntax is used to show this relationship. But don't worry too much about this at the moment, you will learn about it later.

See also

If you found this article useful, you might be interested in the book NumPy Recipes or other books by the same author.

Join the PythonInformer Newsletter

Sign up using this form to receive an email when new content is added:

Popular tags

2d arrays abstract data type alignment and angle animation arc array arrays bar chart bar style behavioural pattern bezier curve built-in function callable object chain circle classes clipping close closure cmyk colour combinations comparison operator comprehension context context manager conversion count creational pattern data science data types decorator design pattern device space dictionary drawing duck typing efficiency ellipse else encryption enumerate fill filter font font style for loop formula function function composition function plot functools game development generativepy tutorial generator geometry gif global variable gradient greyscale higher order function hsl html image image processing imagesurface immutable object in operator index inner function input installing iter iterable iterator itertools join l system lambda function latex len lerp line line plot line style linear gradient linspace list list comprehension logical operator lru_cache magic method mandelbrot mandelbrot set map marker style matplotlib monad mutability named parameter numeric python numpy object open operator optimisation optional parameter or pandas partial application path pattern permutations pie chart pil pillow polygon pong positional parameter print product programming paradigms programming techniques pure function python standard library radial gradient range recipes rectangle recursion reduce regular polygon repeat rgb rotation roundrect scaling scatter plot scipy sector segment sequence setup shape singleton slice slicing sound spirograph sprite square str stream string stroke structural pattern subpath symmetric encryption template tex text text metrics tinkerbell fractal transform translation transparency triangle truthy value tuple turtle unpacking user space vectorisation webserver website while loop zip zip_longest