Syntax

VARIABLES

The print statement displays the contents of the variable to the screen, ie:

print 7
print a #prints the contents of the variable a
print name #prints the contents of the variable a

Arithmatic Operators

A Simple Python Program

#!/usr/bin/python        
print "Hello" #prints Hello to the screen
print 2 + 2
a = 10 #stores 10 in a
a = a + 2 #stores 12 in a

b = 3.5
c = .8
d = b * c
print d

z = "Fred"
zz = " and Wilma"
print z #prints "Fred"
print z+zz #prints "Fred and Wilma", the plus sign concatenates the two strings

Running The Program

If the program is saved in a file named al.py there are two steps to running a python program: Before you can run the program, you need to tell the computer that the file is a program by issuing chmod u+x al.py (you only need to use chmod once). To run the program type ./followed by the program name.

Branching

Making a choice between several actions. Use the if statement. To make a choice we need to test a variable, ie using ==. Without indentation the program creates an IndentationError. The colon must be placed at the end of the if and else lines.

Example 1

a = 3
if a==5
print "a is equal to 5"

Example 2

x = 3
if x==3:
print "x is equal to"
print x
print "end of text one"

Nesting

Putting one or more if statements inside another.

Example 1

if name == "Fred":
  if age == 25:
    print "Fred is 25"
  else: "Fred is not 25"

Example 2

name = "fred"
age = 25
if name == "Fred":
  if age == 25:
    print "Fred is 25"
  else:
    print "Fred is not 25"
else:
  if age == 25:
    print "It is not Fred, age is 25"
  else
    print "Not Fred, not 25" 

Looping

Repeating operations. Eliminates repetition in the code. ie. printing “fred” 100 times would be annoying. Since in the above example we need to count from 1 to 100; the end condition is when count ==100. Loops repeat operations until a condition is met.

The While Loop

The while loop repeats a block (indented) of code until a test is false.

Example: Count from 0 to 99

count = 0
while count < 100:
print "Fred", count
count = count + 1

Out:

Fred 0
Fred 1
...
Fred 99

The For Loop and Range() Function

Used to count a number or iterations. Easier to count with than while loop. Range(5) returns the set of values 0,1,2,3,4. The for loops sets i equal to the next value from the set created by range(). Range() can have a starting value where it will begin the count; ie. range(3,6). With no starting value it will begin with 0. When the set is empty, the loop ends. The set does not need to be created using range(); range is for counting. Strings can create a set in a for loop.

Example: Iterate from 0 to 4

for i in range(5):
print i

Out:

0
1
2
3
4

Example: Loop through a String

In:

s1 = "Fred"
for i in s1:
print i

Out:

F
r
e
d