Skip to main content

2.4) Writing A Script/Program


If you start writing a lot of lines of code, it's not very convenient to type it all one by one in the interactive way. So you can put it all in a file and execute the file. This file is what we call a script or program. For big projects, your program might be made up of several files.

To write a program you will need to use a text editor.

  • If you are using IDLE, to open the text editor, click on New Window in the File menu (or type Ctrl+N).
  • If you are not using IDLE, open the text editor of your choice.

In the text editor, type:


print "Hello, World!"
2+3

Press Enter at the end of the sentences and save it as the file my_first_program.py (in IDLE: menu file > save as). Avoid spaces in the file name as these make the file difficult to use in Unix. The file name must end with a '.py' to indicate that it's a Python program.

Congratulations, you wrote your first python program. Now go to the next page to see how to run it!

Running A Script With IDLE

To run your script in IDLE, in the text editor window, go to the menu run> run module. Alternatively you can press F5 while you are in the editor window. If you haven't saved your program first, it will ask you to save it. You should get the following lines in your shell.

[code lang="python"]
>>> ================================ RESTART ================================
>>>
Hello, World!
>>>
[/code]

It first prints a RESTART line which indicates that everything before has been wiped out (i.e. it’s in the bin). You start from fresh!

Hmmm... this didn’t print the sum of 2 and 3. Let’s see how to fix that on the next page.

Running A Script With The Python Interpreter

To run your script with the python interpreter, in the text editor window, go to the menu run> run module. Alternatively you can press F5 while you are in the editor window. If you haven't saved your program first, it will ask you to save it. You should get the following lines in your shell.

[code lang="python"]
>>> ================================ RESTART ================================
>>>
Hello, World!
>>>
[/code]

It first prints a RESTART line which indicates that everything before has been wiped out (i.e. it’s in the bin). You start from fresh!

Hmmm... this didn’t print the sum of 2 and 3. Let’s see how to fix that on the next page.