Introduction & History Python was conceived in the late
1980s by Guido van Rossum at the National Research Institute for
Mathematics and Computer Science in the Netherlands as a successor
of the ABC programming language and first published and released in
1991. Python supports multiple programming paradigms (primarily
functional, object oriented and imperative), and features a fully
dynamic type system and automatic memory management; it is thus
similar to Perl, Ruby, Scheme. To try Python just install the
Python interpreter and we can use the IDLE (Integrated Development
Environment) that comes with the interpreter. Python makes it easy
to run single lines of code (its what we call one-liner programs).
To make bigger programs in Python you just have to write the whole
program in a notepad and then save it as *.py and open the file
with the Python IDLE and then run the program. NASA uses
Python.
Slide 3
Very Simple Programs We start by creating simple programs with
single lines of code: To output something on the screen we type
print . Commas outside the quotations serve as a concatenation when
used with the print operator. Math in Python: Python Operators: In
the division if we type 19.0/3.0 the output will be 6.33333 because
in Python unlike JAVA we dont have float double etc Order of
Operations: parentheses () ; exponents ** ; multiplication
*,division \ and remainder % ; addition + and subtraction -.
Slide 4
Simple Programs (Cont) Math operations work only outside the
quotations in a print statement concatenated using commas. A
comment is a piece of code that is not run. In python, you make
something a comment by putting a hash # in front of it. A hash
comments everything after it in the line, and nothing before it.
VARIABLES : Variables store a value just like java but the
difference is that in Python we dont declare a type for the
variable. A variable can be an integer a string etc Its very easy
to declare a variable in Python for example : v = 1 or v = v * 5 or
v = Hello etc
Slide 5
The While Loop The While Loop works just like the while in java
but without the use of curly braces nor the parentheses in the
while statement. So the code that we want to loop must be indented
after the while statement or else it wont be part of the loop. For
example a while loop in Python would be in this form: while
condition that the loop continues: what to do in the loop have it
indented the code here is not looped because it isn't indented
Slide 6
Boolean Expressions Boolean expressions are used to set
conditions for the loop to continue. Basically a loop keeps going
if the condition is true, otherwise the loop stops. Boolean
Operators:
Slide 7
Conditional Operators Unlike loops, conditionals are only run
once. The most common conditional in any programming language, is
the if statement. There is also the else statement and the elif
statement which is the same as elseif in JAVA. Here is how its
written in Python: if conditions: run this code# similar to the
while loop the code inside elif conditions: # the if elif and else
must be INDENTED run this code elif conditions: run this code else:
run this code but this happens regardless because it isn't
indented
Slide 8
Functions Functions are little self-contained programs that
perform a specific task, which can be used at any time, in any
place and can be incorporated into larger programs. Python has lots
of pre-made functions that can be used right now by simply calling
them. Here is the general form that calling a function takes:
function_name(parameters) Suppose a function called user_input that
asks the user to type in something then turns it into a string of
text for example: a = user_input("Type in something, and it will be
printed on screen:") print a The return value of the function will
be stored in the variable a.
Slide 9
Functions (Cont) To define our own Functions we use the def
operator: def function_name (parameter_1,parameter_2): this is the
code in the function more code return value to return to the main
program this code isn't in the function because it isn't indented
The only thing functions see of the main program is the parameters
that are passed to it. The only thing the main program sees of
functions is the returned value that it passes back.
Slide 10
Tuples A Tuple is a list of values, but you cant change their
values once you initialize it. Each value is numbered starting from
zero. For example: the names of the months of the year: months =
('January','February','March','April','May','June',\
'July','August','September','October','November',' December') print
months[2]# printing the 3 rd month, march. print months# print the
whole list. The \ at the end of the first line carries over that
line of code to the next line. The parentheses are optional it just
stops Python from getting things confused.
Slide 11
Lists Lists are a list of values. Each one of them is numbered,
starting from zero. You can remove values from the list, and add
new values to the end. For example: Your cats names. cats = ['Tom',
'Snappy', 'Kitty', 'Jessie', 'Chester'] print cats[2] # printing
the name of the 3 rd cat, Kitty. cats[0:2] # would recall the1st
and 2nd cats.(range) cats.sort()# sorts the list alphabetically.
The code is the same as a tuple, EXCEPT that all the values are put
between square brackets, not parentheses. To add a value to the
list, just use the append() function: cats.append('Catherine') #
adds Catherine to the end of the list. To delete a value from the
list, just use the del operator: del cats[1] # removes the 2nd cat,
Snappy.
Slide 12
Dictionaries In a dictionary, you have an index of words, and
their definitions. In Python, the word is called a key, and the
definition a value. For example a telephone book where you give the
computer a name, and it gives us a number. Name = Key, Number =
Value. phonebook = {'Andrew Parson':8806336, \ 'Emily
Everett':6784346, 'Peter Power':7658344, \ 'Lewis Lame':1122345} #
we use curly braces instead. print phonebook['Lewis Lame']# print
his number on screen. To add a person to the phonebook just type:
phonebook['Gingerbread Man'] = 1234567 To delete a person from the
phonebook, just use the del operator: del phonebook['Andrew
Parson']# deletes Andrew from the phonebook
Slide 13
Dictionaries (Cont) Using the function has_key():
function_name.has_key(key-name)#It returns True if the dictionary
#has key-name in it, False otherwise. Using the function keys():
phonebook.keys()#This returns a list of all the names of the keys.
You could use this function to put all the key names in a list:
keys = phonebook.keys() Using the function values():
phonebook.values()#This returns a list of all the values in a
phonebook. You can't sort dictionaries because they are in no
particular order. You can find the number of entries with the len()
function: print "The phonebook has", \ len(phonebook), "entries in
it"
Slide 14
The For Loop The for loop does something for every value in a
list. For example: # First, create a list to loop through: newList
= [45, 'eat me', 90210, "The day has come, the walrus said, \ to
speak of many things", -67] # Second, create the loop: # Goes
through newList, and sequentially puts each bit of information #
into the variable value, and runs the loop: for value in newList:
print value As you see, when the loop executes, it runs through all
of the values in the list mentioned after 'in'. It then puts them
into the variable value, and executes through the loop, each time
with value being worth something different.
Slide 15
Classes Since Python is an object-oriented-programming language
we can create classes that relates functions and variables together
in a way that they can see each other and work together. We create
a class using the class operator, The function __init__ is run when
we create an instance of a class. (constructor in JAVA) The
operator self is how we refer to things in the class from within
itself. It is the first parameter in any function defined inside a
class. Any function or variable created on the first level of
indentation of where we put class Shape is automatically put into
self. To access these functions and variables elsewhere inside the
class, their name must be preceded with self and the dot .
operator. (e.g. self.variable_name). For example the definition of
a shape:
Slide 16
Classes (Cont) class Shape: def __init__(self,x,y): self.x = x
self.y = y description = "This shape has not been described yet
author = "Nobody has claimed to make this shape yet" def
area(self): return self.x * self.y def perimeter(self): return 2 *
self.x + 2 * self.y def describe(self,text): self.description =
text def authorName(self,text): self.author = text def
scaleSize(self,scale): self.x = self.x * scale self.y = self.y *
scale
Slide 17
Classes (Cont) Using a class: rectangle = Shape(100,45)
#creating an instance of a class. print rectangle.area() #finding
the area of the rectangle. print rectangle.perimeter() #finding the
perimeter of the rectangle. rectangle.describe("A wide rectangle,
more than twice\ as wide as it is tall") #describing the rectangle.
rectangle.scaleSize(0.5) #making the rectangle 50% smaller.
longrectangle = Shape(120,10) #another instance of shape.
fatrectangle = Shape(130,120) #both have their own functions and
#variables contained inside them.
Slide 18
Inheritance We define a new class, based on another, parent
class. Our new class brings everything over from the parent, and we
can also add other things to it. If any new attributes or methods
have the same name as an attribute or method in our parent class,
it is used instead of the parent one. Using inheritance we can
easily define a Square: class Square(Shape): def __init__(self,x):
self.x = x self.y = x We redefined the __init__ function of Shape
so that the X and Y values are the same. (we have overridden the
constructor)
Slide 19
Pointers & Dictionaries of Classes Consider the following
statement in Python: instance2 = instance1 #instance2 is pointing
to instance1 There are two names given to the one class instance,
and you can access the class instance via either name. In other
languages, you do things like this using pointers(C++), however in
python this all happens behind the scenes just like in JAVA. In
addition we can assign an instance of a class to an entry in a list
or dictionary. # First, create a dictionary: dictionary = {} #
Then, create some instances of classes in the dictionary:
dictionary["long rectangle"] = Shape(600,45) #You can now use them
like a normal class: print dictionary["long rectangle"].area()
Slide 20
Modules A module (packages in JAVA) is a Python file that has
only definitions of variables, functions, and classes. We import
bits of it (or all of it) into other programs using the import
operator. For example, to import moduletest.py into your main
program we write: import moduletest This assumes that the module is
in the same directory as mainprogram.py, or is a default module
that comes with Python. You normally put all import statements at
the beginning of the Python file, but technically they can be
anywhere. In order to use the items in the module in your main
program, use the following: # modulename.itemname print
moduletest.ageofqueen piano = moduletest.Piano()
Slide 21
Modules (Cont) One way to get rid of the modulename is to
import only the wanted objects from the module. To do this, you use
the from operator: # from modulename import itemname from
moduletest import printhello printhello() We can also import a
module in the normal way (without the from operator) and then
assign items to a local name: timesfour = moduletest.timesfour
print timesfour(565)
Slide 22
File Input/Output To open a text file you use the open()
function. You pass certain parameters to it to tell it in which way
the file should be opened: r for read only, w for writing only, a
for appending and r+ for both reading and writing. Example:
openfile = open('pathtofile', 'r') openfile.read() print
openfile.read() wont work because the cursor has changed its place.
This cursor tells the read function where to start from. To set the
cursor, you use the seek() function. It is used in the form:
seek(offset, whence) whence is optional, and determines where to
start from. If whence is 0, the bytes/letters are counted from the
beginning. If it is 1, the bytes are counted from the current
cursor position. If it is 2, then the bytes are counted from the
end of the file. If nothing is put there, 0 is assumed. offset
decribes how far from whence the cursor moves.
Slide 23
File Input/Output (Cont) For example: openfile.seek(45,0)
#moves cursor 45 bytes/letters after the beginning of the file.
openfile.seek(10,1) #moves cursor 10 b/letters after the current
cursor position. openfile.seek(-77,2) #moves cursor 77
bytes/letters before the end of the file. print openfile.read() #It
will print from the spot you seeked to. After this is done #the
cursor will be at the end of the file so to print #something again
you will have to seek again. More I/O Functions: openfile.tell()
#takes no parameters/returns where the cursor is in the file.
openfile.readline() #takes no parameters/reads from where the
cursor is till the #end of the line. You can optionally pass to it
the maximum number of bytes/letters to read by putting a number in
the brackets.
Slide 24
File Input/Output (Cont) openfile.readlines() # is much like
readline(), however readlines() reads all the lines from the cursor
onwards, and returns a list, with each list element holding a line
of code. For example: If you had the text file:The returned list
would be: openfile.write('this is a string') # It writes from where
the cursor is, and overwrites text in front of it. openfile.close()
# It closes the file so that you can no longer read or write to it
until you reopen it again.
Exception Handling print 'Subtraction program:' #to handle
exceptions we use the try and except operators. loop = 1#except
without parameters catches all errors. while loop == 1: try: a =
input('Enter a number to subtract from > ') b = input('Enter the
number to subtract > ') except NameError: print "\nYou cannot
subtract a letter" except SyntaxError: print "\nPlease enter a
number only." print a - b try: loop = input('Press 1 to try again
> ') except (NameError,SyntaxError): loop = 0