Your First Program in Python

By: Zed A. Shaw Viewed: 153219 times  Printer Friendly Format    


1 print "Hello World!"
2 print "Hello Again"
3 print "I like typing this."
4 print "This is fun."
5 print 'Yay! Printing.'
6 print "I'd much rather you 'not'."
7 print 'I "said" do not touch this.'

Type the above into a single file named ex1.py. This is important as python works best with files ending in .py.

Warning: Do not type the numbers on the far left of these lines. Those are called “line numbers” and they are used by programmers to talk about what part of a program is wrong. Python will tell you errors related to these line numbers, but you do not type them in.

Then in Terminal run the file by typing:

python ex1.py

If you did it right then you should see the same output I have below. If not, you have done something wrong. No, the computer is not wrong.

What You Should See

$ python ex1.py
Hello World!
Hello Again
I like typing this.
This is fun.
Yay! Printing.
I'd much rather you 'not'.
I "said" do not touch this.
$

You may see the name of your directory before the $ which is fine, but if your output is not exactly the same, find out why and fix it.

If you have an error it will look like this:

$ python ex/ex1.py
File "ex/ex1.py", line 3
print "I like typing this.
^
SyntaxError: EOL while scanning string literal

It’s important that you can read these since you will be making many of these mistakes. Even I make many of these
mistakes. Let’s look at this line-by-line.

  1. Here we ran our command in the terminal to run the ex1.py script.
  2. Python then tells us that the file ex1.py has an error on line 3.
  3. It then prints this line for us.
  4. Then it puts a ^ (caret) character to point at where the problem is. Notice the missing " (double-quote) character?
  5. Finally, it prints out a “SyntaxError” and tells us something about what might be the error. Usually these are very cryptic, but if you copy that text into a search engine, you will find someone else who’s had that error and you can probably figure out how to fix it.


Most Viewed Articles (in python )

Latest Articles (in python)

Comment on this tutorial