How to Create and Run Your First Python Program on the Raspberry Pi - dummies

How to Create and Run Your First Python Program on the Raspberry Pi

By Sean McManus, Mike Cook

Creating Python programs on the Raspberry Pi can help simplify your life. The problem with entering instructions in the shell is that you have to enter them each time you want to use them. The commands are carried out straight away, too, which limits the sophistication of the kinds of things you can do.

You can solve these problems by creating a program, a set of repeatable instructions that you can save as a file and use again.

To create a program, you use script mode, which is a blank window when you open it. To open the script mode window, click the File menu at the top of the Python shell, and then click New Window.

When you enter commands in script mode, they’re not carried out straight away. The window acts like a simple text editor, and enables you to enter your list of commands (or program), and gives you control over when those commands are carried out.

Enter the following commands in the script mode:

# simple times table program
print “This program calculates times tables”
print “It is from Raspberry Pi For Dummies”

The two print commands should look familiar to you, but the first line is new. In Python, anything after a # is ignored by the computer. The hash mark indicates a comment, used to add notes to programs so you can understand them later.

The very best programs are written in such a way that you can understand them easily anyway, but it’s a good idea to leave little messages to your future self so you can quickly understand important aspects of the program.

To save your program, click the File menu at the top of the script mode window and choose Save. You use this same menu to reopen previously saved programs too.

The term used for starting a program is running it, so click the Run menu and then click Run Module to see your program in action. Alternatively, the keyboard shortcut to run the program is F5. When you run the program, Python switches back to the shell and you see those two lines of text printed out on the screen.

Congratulations! You’ve just written your first Python program!

Before you can run your program, you must save it. If you made changes since the last time it was saved, you are prompted to save the program when you try to run it. This overwrites the previous version of the program.

On the File menu of the script mode window is an option to save a copy of the program or to save it using a different filename (Save As), which can be useful if you might want to revert to an earlier version.