Python Hello World
Here's how to create a quick Python program that displays "Hello world".
Creating a simple program that displays some text is often the first thing any programmer does after setting up their environment for the first time. This only takes a few seconds, and it can confirm to the programmer that the environment is set up and working. "Hello world" seems to be the most common thing to say when writing these programs. I'm going to stick with that tradition here, but feel free to write anything you like!
Anyway, you can create a simple "hello world" program by using Python's
print() function to output the text "Hello World" to the screen. We already did this previously, but this time we'll save the program so we can run it later.
Write the Program
Open your Python editor (IDLE is fine), and enter the following code:
This will output the following:Result
This is probably the simplest Python program you'll ever create, nevertheless it's still a Python program. As with any computer program, you can save this to a file, then add to more functionality later if needed.
Save your Program
Go ahead and save your program to a file called hello.py. This is typically done using the editor's File > Save or similar.
Run your Program
Here's how to run the program:
- Open your file (if not already open). This is typically done using File > Open or similar.
- Run the file. How to do this will depend on your editor and platform.
- In IDLE, try Run > Run Module (shortcut F5).
- In Visual Studio Code, use Ctrl+Shift+B on Windows and Linux, or Cmd+Shift+B on Mac to run the build task (configured via your task runner, as explained when we configured the environment).
Add a Comment
Comments are an important part of programming. They allow you, the programmer, to explain what each part of your code does. This is especially important when your program is a bit more than one line, as ours is at the moment.
But it's good practice to add comments as you write the program — even while the program is small. It doesn't take long before your program spans hundreds (or even thousands) of lines. And then it can be a real headache going back and trying to figure out what you were trying to do back when you wrote the program.
In Python, comments start with the hash character (
#) that is not part of a string literal, and ends at the end of the physical line.
In other words, if you want to write a comment, start the line with
#. Like this:
As you can see by the result, the comment isn't actually output to the screen. It's simply there for the programmer (and any other programmers) benefit.
Try to make your comments descriptive but concise. Also, many programmers and development teams employ the practice of including a large, detailed comment at the top of the file that explains what the file does, the date it was created, its version number, the author, etc.