Back to homepage

Introduction

Python is one of the greatest programming languages invented so far. With that out of the way, let's see how to program in it.

Install Python

If it is not installed already on your computer, go to http://www.python.org to download Python. Follow site instructions for installation.

Interactive mode

There are two modes of operation of Python interpreter. 

Interactive mode is useful for testing very small code fragments. 
Normal mode is for execution of code stored in human-readable text file.

For interactive mode, type in:
python

You will be greeted by something similar to text below.
prompt invites you to type the command. 

Python 2.5.2 (r252:60911, Jan 24 2010, 14:53:14) 
[GCC 4.3.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.

Numbers

Add two numbers directly:

5+3
8


Add two numbers, assigning them to variables first:

a=5
b=3
a+b
8


In regular (non-interactive) Python code you would use print statement
like so:

print a+b
8


Other math operations are straightforward:

c=a*b
print c
15


However, division might return something you didn't expect:

d=a/b
d
1


Problem is laying with the fact that Python considers a and b to be integers (whole numbers), 
and therefore thinks you want an integer result. 
Just rewrite one of the numbers as decimal value, and you will be ok:

b=3.0
d=a/b
d
1.6666666666666667


Trigonometric functions require import of math library:

sin(2)
Traceback (most recent call last):
File "stdin", line 1, in module
NameError: name 'sin' is not defined


To fix that:

import math


By default, trig functions operate on radians:

math.sin(2)
0.90929742682568171

Sine of almost Pi is almost zero :)

math.sin(3.14159)
2.6535897933527261e-06

Closer still if we use pre-recorded value of pi:
math.sin(math.pi)

1.2246063538223773e-16



Random number functions are provided in random library:

import random

First, random decimal number (float) between 0 and 1:

random.random()
0.32104313658720485

random.random()
0.1954833327103993

random.random()
0.68445879892253469


Second, random whole number (integer) between 0 and 1000:

random.randrange(1000)
170

random.randrange(1000)
904

random.randrange(1000)
315


Exponentiation uses old POW syntax from C. Two to the power of eight:

pow(2,8)
256

Square root of 1001:

pow(1001,0.5)
31.63858403911275


Useful function is also RANGE, which prefills a list with progressing
numbers:

range(40)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37,
38, 39]

Strings

String declaration is straightforward, single or double quotes are allowed:

e="one"
f="two"

Adding two strings together (one after another, concatenation) is done with + operator:

g=e+f
print g
onetwo

If you want space in between the strings:

g=e+" "+f
g
'one two'


Parts of the string can be extracted with subscript notation. 0 is the
first character in the string.

First 3 characters:

g[0:3]
'one'

First 5 (space included):

g[0:5]
'one t'

Last three characters to the end (number omitted)

g[-3:]
'two'


You can print unicode characters, just type them in directly into the
string

print "српски"
српски

Other encoding:

print "šđžčć"
šđžčć

Additional useful string transformations

Capitalize first letter of string:

a="why is this in lowercase?"
b=a.capitalize()

b
'Why is this in lowercase?'


Find where the substring is, returns substring position (first char of
substring):

c=b.find("is")
c
4


Replace substring with another substring:

e=b.replace("this in", "this umbrella in")
e
'Why is this umbrella in lowercase?'



Split string into smaller strings (separator given in parentheses),
returns list of items:

f=b.split(" ")
f
['Why', 'is', 'this', 'in', 'lowercase?']

String to number and Number to string conversions

String to integer:

a="1234"
b=int(a)
b
1234


String to floating point number:

c="23.89"
d=float(c)
d
23.890000000000001


Integer or floating point number to string:

e=123.45
f=str(e)
f
'123.45'

Arrays / Lists

Arrays (lists) are easy to work with. They can be numeric, string, or
mixed:

h=[1,3,5,7]
h
[1, 3, 5, 7]

Individual elements are extracted or assigned to like this (first
element is numbered 0):

print h[3]
7
h[3]=222
h
[1, 3, 5, 222]



If you ask for elements outside of the list:

print h[0]+h[7]
Traceback (most recent call last):
File "stdin", line 1, in module
IndexError: list index out of range


Some examples of list manipulations:

print h[0]+h[3]
223

i=["I","love","to","fly"]
i
['I', 'love', 'to', 'fly']

For some Yoda transformations:

print i[3],i[2],i[1],i[0]
to love I fly


Number of elements in a list (works for string length also):

len(i)
3

Normal mode of program execution

Longer programs would normally be stored in a text file, preferably with Python extension py.

Enter the following program into a text editor (copy-paste) and save it as test1.py:


q1=raw_input("Enter some text:")
if len(q1)=1:
    print "Entered text is equal to or shorter than one character."
elif len(q1)==2:
    print "Entered text has length of two characters."
elif len(q1)>2 and len(q1)6:
    print "Entered text is longer than two characters, and shorter than six characters."
else:
    print "Entered text is longer than 6 characters."



Make sure that lines after if, elif, else statements are indented. 
This means you have to type TAB at beginning of line. 

Python uses indentation to recognize which code is executed in many commands, 
so pay close attention to indentation. 

Most Python editors will do it automatically, 
IDLE
for example. 
If you don't know what I'm talking about, use IDLE to type in your programs. 
You can conveniently run them from IDLE as well.



To run this Python program stored in the text file in Linux, just type:

python test001.py
on the command line (BASH shell) and press Enter

(In Windows, just type test001.py on command prompt and press Enter)

You are asked to enter some text:


Enter some text:W
Entered text is equal to or shorter than one character.



Now, if you try to re-run the program and enter text strings of different lengths, 
you will get different outputs:

PythonExamples$ python test001.py
Enter some text:Wh
Entered text has length of two characters.

PythonExamples$ python test001.py
Enter some text:What
Entered text is longer than two characters, and shorter than six
characters.

PythonExamples$ python test001.py
Enter some text:What a charming cactus.
Entered text is longer than 6 characters.


After a while you get bored typing "python" before the name of the
program. One way around that is to add line at the very top of your
Python program file:

#! /usr/bin/env python

Run the program. It barfs out some error message (bash: ./test001.py:
Permission denied), unless you are in FreeBSD/OpenBSD/NetBSD.

To make script executable without typing "python" every time in Linux,
type:

chmod +x test001.py

Now script is made executable, and you can run it with:

./test001.py

and pressing Enter afterwards.

Comments

Single-line comments are entered like so: 

# print "Blah"

Everything after # is ignored by program.



Multi line comments are entered like so:

"""
print "C"
print "+"
print "and -"
"""

Everything within """ and """ is ignored by program.

Is it worth your WHILE?

Another thing that can get you worked up after a while is always re-running this phony program 
to see results. 
This gets us to the notion of WHILE loop, which can save us from too much typing. 
Modify your program as shown below, and save it as test002.py:


#! /usr/bin/env python
q1=""



while q1!="q":
    q1=raw_input("Enter some text:")
    if len(q1)=1:
        print "Entered text is equal to or shorter than one character."
    elif len(q1)==2:
        print "Entered text has length of two characters."
    elif len(q1)>2 and len(q1)6:
        print "Entered text is longer than two characters, and shorter than six characters."
    else:
        print "Entered text is longer than 6 characters."



Output of your program (remember to chmod test002.py if you wish):


PythonExamples$ ./test002.py
Enter some text:qwerty
Entered text is longer than 6 characters.

Enter some text:qwe
Entered text is longer than two characters, and shorter than six
characters.

Enter some text:q
Entered text is equal to or shorter than one character.


What happens here is that program exits when "q" is entered. 
For all other values it keeps looping forever, asking you the same boring question, 
just like your mother. 
And, just like your mother, it doesn't stop until you "q"uit her basement.

FOR all the tubes of the internet, does this wannabe tutorial ever stop?

If you have to perform some operation pre-defined number of times, it is easy to use FOR loop.
This turns your computer into a mindless servant to you, 
repeating required actions FOR as long as you wish, or until your RAM runs out:

list1 = [1,2,3,4]
for z in list1:
    print z, pow(z,2)

What this does? First it makes a list (array) with four numbers in it.
Then, using FOR loop, goes through the list until the end, and prints
values of numbers in the list and their squares (POW function).

Output:

1 1
2 4
3 9
4 16

While you were away for lunch, FILES kept piling up ...

How to work with files? 
Well, there are 3 major ways (modes) for file access, Read, Write, and Append. 
Append just adds stuff at the file end. 

Let's do an example for all 3:


#! /usr/bin/env python
# open file text1.txt as f1 and write few lines of text into it

f1=open("text1.txt","w")
s1="A jolly good\n"
s2="morning, I'll say.\n"
s3="I'll rip your plywood board in half!\n"
f1.write(s1)
f1.write(s2)
f1.write(s3)
f1.close()


# open text1.txt as f2 and read lines into variables

f2=open("text1.txt","r")
line1=f2.readline()
print line1
line2=f2.readline()
print line2
line3=f2.readline()
print line3


# open text2.txt as f3 and write lines from text1.txt but backwards

f3=open("text2.txt","a")
f3.write(line3)
f3.write(line2)
f3.write(line1)
f2.close()
f3.close()


# now open text2.txt again and just add stuff at the end of file

f3=open("text2.txt","a")
f3.write("\n\n") # add two empty lines
f3.write(line1)
f3.write(line2)
f3.write(line3)
f3.close()


Your files will contain the following after program run:

PythonExamples$ cat text1.txt

A jolly good
morning, I'll say.
I'll rip your plywood board in half!


PythonExamples$ cat text2.txt

I'll rip your plywood board in half!
morning, I'll say.
A jolly good





A jolly good
morning, I'll say.
I'll rip your plywood board in half!


Now you are ready to fill your hard drive with useful data files, and read them too. 
Your next step to worldwide domination is to get on top of the tubes, 
that is, to rule the internet.

Getting data through INTERNET tubes

Python lets you eat an icecream in Australia, while reading about the freezing weather in Canada.
Here's how to extract web page data, using urllib2:

#! /usr/bin/env python

import urllib2

for line in
urllib2.urlopen('http://www.theweathernetwork.com/weather/canu0014?ref=homemap'):
if 'Sunrise:' in line:
    print line
if "Sunset:" in line:
    print line
if '''"temp"''' in line:
    print line



Program output:
li>strong>Sunrise: /strong> 5:18/li> li>strong>Sunset: /strong>19:53/li> td class="temp">-11°C/td> td class="temp">-5°C/td> td class="temp">-8°C/td> td class="temp">-19°C/td> td class="temp">-16°C/td>
This program connects to Weather network page for Iqaluit, Nunavut and prints html lines 
if it finds Sunrise: Sunset: or "temp" within them.
Since "temp" search string was in quotes already, it had to be interpreted literally 
with triple ''' on each side of string. 
Other option was "\"temp\"" with escape character \

Of course, html kra* is still visible, but further string manipulation
can easily remove it. 
By the way, those 5 temperatures are forecast for the next 2 days.


Need more on your path to world domination?

http://docs.python.org/tutorial/

Back to homepage