Your First Program in Python
By: Zed A. Shaw 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.
- Here we ran our command in the terminal to run the ex1.py script.
- Python then tells us that the file ex1.py has an error on line 3.
- It then prints this line for us.
- Then it puts a ^ (caret) character to point at where the problem is. Notice the missing " (double-quote) character?
- 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.
Comment on this tutorial
- Data Science
- Android
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Subscribe to Tutorials
Related Tutorials
How to install Jupyter in Ubuntu and make it accessible through Apache Reverse Proxy
Python Basics - Setting up your Python Development Environment
Schwartzian Transform in python
Multidimensional list (array) in python
Remove duplicates from a list in python
Convert number to string in python
Perl's chomp() equivalent for removing trailing newlines from strings in python