Writing Your First Program
Last updated
Last updated
You should have a free Cloud9 account setup or you should have Python and a text editor installed onto your computer. Please refer back to the Introduction for more details and links.
You will use two different programs to create and test your programs. One is a text editor and the other is a terminal emulator. The text editor simply allows you to edit the text of your files. After all, code is just text that the computer understands. The terminal is the program that you use to actually run your program. We will also use it to perform other operations which you will learn later. It is a very powerful program and allows you to do anything you might want to do. Make sure that whichever environment you use has a good text editor and a decent terminal.
We create programs using the text editor. Python programs consist of files that end in a ".py" extension. An example file look like: my-first-program.py
. It is easiest if you don't put any spaces in your file names. The contents of the file are what make the program work. In your first program you should try something easy. Try using the print
command to display something in the terminal.
Type the following command in your text editor and then save it as my-first-program.py
.
Now try executing the program that you have just created by clicking on the terminal and typing:
Press 'Enter' when you are finished to execute the command. The result of this command should print 'hello world' (without quotes) in your terminal.
Using a terminal can sometimes be challenging. A terminal is a tool that allows you to execute commands. Almost all of the commands that we do have something to do with the file system. Your terminal usually starts in your home directory. When you saved that file you saved it to the home directory so when you typed python my-first-program.py
it was able to call the python
command with your file because your file was in the current directory. If it had been in a different directory you would have had to point to that location otherwise the command would fail. To become a little more comfortable using the terminal try going through this tutorial.
Make your own 'hello world' program!
You can create comments by putting a '#' at the beginning of a line. Comments are not executed by the interpreter so they serve as notes to other developers (or even yourself when you forget) regarding your code. You can also create multi-line comments by putting triple quotes around your text: