Download Very quick tutorial on Python

Survey
yes no Was this document useful for you?
   Thank you for your participation!

* Your assessment is very important for improving the workof artificial intelligence, which forms the content of this project

Document related concepts
no text concepts found
Transcript
Very quick tutorial on Python
by Mark Meyer
May 2014
This tutorial will get you started on Python. You are strongly urged to install it on your own
computer this summer and play with it, possibly even write some simple programs with it.
1. Installing Python
Python works on every platform. Just find your platform's installer at http://python.org and click
on the Downloads tab. We will use version 3.3, though you can install version 3.4 if you like.
Do not use version 2.7 or anything before version 3, as versions 2 and 3 are not
compatible. Many people and books still use version 2.7 but there are major differences
and a 2.7 program generally will not run on version 3.
If you want to play with Python on your iPad, there is a free app called CodeToGo that you can
use. What this does is send off your Python programs to a server and run them there and sends
the results back. It is fun and can be useful.
2. How to run Python
Most of the examples will work on both Windows and Mac, though the instructor uses Windows
almost exclusively.
The simplest way to write and run a program is to create a file and end its name with .py using
your favorite editor, like Notepad, Textpad or Wordpad. (If you use Microsoft Word, be sure to
save as plain text!)
Once you have created a Python source program, perhaps on your desktop, you need to open a
shell. In Windows, go to the start button, and in the Search/Run box type cmd and press return,
or else find Command Window and run that. That opens up a black shell box with white letters
and provides a command line interface. Navigate to the desktop or whichever folder has your
.py file. Then issue the python command on your program.
Here are commands that I would type to run my program in a file named myprog1.py:
C:\> cd C:\Users\Mark\Desktop
C:\> python myprog1.py
If your program asks for input, you will just type it into this window and press RETURN. All
output will be on the black window.
Mac users should use the terminal app (just go to the Spotlight and type "terminal.")
You can also run Python quickly and interactive by merely typing "python" at the prompt in your
CMD or terminal window:
C:\> python
This will start up Python in interactive mode, and you will see >>>. Type any single line
statement here. Or you can define a function or create a while loop. Just keep pressing return
until it gives you the prompt.
To get out of this, type "quit" followed by open and close parentheses:
>>> quit()
and press RETURN.
As a side benefit of using the command line interface, you can see the version of Python you
have installed. Python will show you the version when it starts.
There are many IDEs (integrated development environments) for Python. The most famous is a
freebie that comes with every Python installation, called IDLE. In Windows, just click on the
start button and in the search/run box, type IDLE and it will open up. You can type single lines
of Python code and run them right there, or you can edit files. There are youTube tutorials on
how to use IDLE. We will use IDLE for quick experiments.
Another excellent IDE for Python PyCharm. There is a free community version you can
download. Go to http://www.jetbrains.com/pycharm.
A Python program can also be a GUI (graphical user interface) program. Such Python programs
pop up windows on your desktop, just like Java can.
3. Python example programs
What follows next are some small programs that illustrate many things. Work through them in
order.
Program 0
Topic: echo printing
1
2
3
4
5
while True:
line = input("? ")
if not line: break
print(line)
print("DONE!")
This is a crude echo printing program. It stops when the user types a blank line, which is
considered "false" on line 3.
If you don't want to stop at a blank line, you might choose some special keystroke combination
like CONTROL-D, which is very common in Unix (and somewhat in Windows.) In that case,
you have to ask if the input line had the special CONTROL-D character, which is ASCII 4:
1
2
3
4
5
while True:
line = input("? ")
if line == chr(4): break
print(line)
print("DONE!")
Program 1
Topic: input and output of strings
1
2
3
name = input("What is your name? ")
print("Hi there,",name)
print("Good-bye!")
Line 1 uses the built-in function input(). Its string parameter is a prompt. It returns a string,
which we then put into a variable, in this case name. You do not need to declare the types of
variables, and a variable can hold different things of differing types at various times. Then we
use the built-in function print().
Program 2
Topic: input and output of ints and floats
1
2
3
4
age = input("How old are you in years? ")
age = int(age)
# convert string "26" to integer 26
age += 1
# add one
print("Next year, you'll be",age,"years old")
Line 1 uses the built-in function input() again, which always returns a string. But we want a
number that we can do arithmetic on. So in line 2 we convert it to an integer by using the builtin int() function. Notice the comment at the end of the line, which starts with a pound or sharp
sign.
Line 3 adds 1. There are other operators, like -=, *=, /=, etc. But there is no ++ or - - in
Python.
Line 4 shows that you can print lots of things at the same time with the built-in print()
function. It can take any number of parameters, separated by commas. By default it puts one
space between each one when it executes.
Program 3
Topic: High precision arithmetic
1
2
3
4
5
6
7
8
9
10
x = 2**10
print(x)
x = 2**100000
print(len(str(2**100000)))
print(1/7)
print(1//7)
print("%.100f" % (1/7))
print(7//3)
print(2**0.5)
print("%.100f" % (2**0.5))
In line 1, you can see the exponentiation operator is **. You don't need to use Math.pow() or
anything like that. In line 3, you see a very large number produced (2100000). Python
automatically switches over to "unlimited" precision when handling huge numbers so it doesn't
crash on this or require a special library. Line 4 prints out how long that number is in digits by
converting it to a string and then finding the length of that string.
Line 5 produces 0.14285714285714285, not 0 as Java would. In other words Python
automatically converts the result to a float (which is Python's term for real number.) To mimic
Java, use // which means "integer division." Line 6 produces 0.
Line 7 uses the format operator, which is %. The format string is on the left and the values to
format are on the right. Python uses the C-style formatting codes. "%.100f" is the code for a
real number ("f") that is as long as needs to be, with 100 places after the decimal point.
Exponentiation is used for roots, too, so the square root of 2 is computed in line 9. In line 10, the
same number is printed with more places after the decimal point.
Program 4
Topic: the math module
1
2
3
import math
print(math.pi)
print(min(5,3))
This short program illustrates how to use code from another file. In Python, code is put into files
called modules. The module file in this example is named math.py, though we say
"import math" in line 1. There are no special formats to the math.py module. It is just a file of
Python code. Usually modules contain functions and constants. The math.pi function is one
such. Some functions like min() are built-in and not inside any module.
Program 5
Topic: while loops and if statements
1
2
3
4
5
6
7
8
x = int(input("Enter first integer: "))
y = int(input("Enter second integer: "))
while x != y:
if x < y:
y -= x
else:
x -= y
print("The gcd is ",x)
This program uses one variation of Euclid's algorithm for finding the greatest common divisor
(GCD) of two integers.
Notice how you can nest function calls so that you can convert the value obtained from input()
to an int in one line. This occurs in lines 1 and 2.
Make sure you put the colon after else: as shown on line 6. If you like, you can put a single
line of code on the same line as an if statement, such as:
if k == 17: print("This is incorrect")
In fact, you could have put the else line on the same line, too, as shown in the following, more
condensed version of the whole program:
1
2
3
4
5
6
x = int(input("Enter first integer: "))
y = int(input("Enter second integer: "))
while x != y:
if x < y:
y -= x
else:
x -= y
print("The gcd is ",x)
However, this condensed version is considered less readable so it is used less often. A single if
statement on one line with no else is common, however.
Program 6
Topic: The basics of lists
1
2
3
4
5
6
7
8
9
10
friends = ["Mark", "Sally", "Kathy", "Doran", "Luke", "Maddie"]
print(friends[0])
print(friends[-1])
print(friends[0:3])
print(str(friends))
print(",".join(friends))
print("; ".join(friends))
friends.sort()
# changes in place
x = sorted(friends)
# makes a new list
newfriends = "John,Jane,George,Jeanette,Jorge".split(",")
Lists are one of the most basic data structures. Every language has some form of list, often
called an array.
You can think of a Python list as a superarray. It is like Java's ArrayList but you can use square
brackets like an actual array. Lists are 0-based, as usual, but you can use negative indexes to
start from the end. friends[-1] is the last element that has a value in it. It is identical to
friends[len(friends)-1].
There are some other things that are unusual, such as array slices. friends[0:3] takes a slice
out of the friends array, including those elements whose indexes are 0, 1, and 2. Notice that
array element 3 is not included.
You can make an array in many ways, such as from an array literal in line 1, or by splitting a
string in line 10. Lists can be turned into a string in several ways. One cheap way is by using
the str() function in line 5, but it looks like the original list, with commas and square brackets.
A more natural string can be made by using the join method as in lines 6 and 7. One strange
thing about join is that it is a method of the str class, so it looks backwards to our eyes.
There are methods, including sort(), which will sort the list in place. Another method named
sorted()sorts the list but doesn't change it. Rather, sorted() returns a new list.
Program 6.5
Topic: strings
1
2
3
4
5
6
more here!
Program 7
Topic: for loops
1
2
3
4
5
6
friends = "Mark,Sally,Kathy,Doran,Anthony,George".split(",")
shortnames = 0
for friend in friends:
print("I really like",friend)
if len(friend) < 5: shortnames += 1
print("There are",shortnames,"short names in this list.")
For loops are very common in Python because they embody an iterator, which is basically a way
of spinning through all items in a collection. A list is one type of collection. In line 3, the header
of a for loop, Python sets friend to friends[0] and then does the body of the loop (lines 45). When done with the body, Python checks to see if it has gone through the entire collection.
If not, it then sets friend to friends[1] and does the body again, until all done.
The above program will also work if friends is another kind of data structure such as a set or a
dict.
Program 8
Topic: ranges
1
2
3
4
5
6
friends = "Mark,Sally,Kathy,Doran,Anthony,George".split(",")
shortnames = 0
for i in range(len(friends)):
print("I really like",friends[i])
if len(friends[i]) < 5: shortnames += 1
print("There are",shortnames,"short names in this list.")
There is no "counting for loop" in Python as in C or Java. Instead, we generate a list of integers
and let some variable, i in line 3, take on each value of the list. In line 3, there are 6 names in
friends. friends[0] is "Mark", and friends[5] is "George". len(friends) is 6 and
range(len(friends)), just like the expression range(6), will return [0,1,2,3,4,5].
Variable i will take on 0, do the body of the loop (lines 4-5), then take on 1 and do the body
again, and so forth.
A range is a special type of object that can generate a sequence of integers. You can make a list
of those integers from a range, or you can just use the range in a for loop.
1
2
3
print(list(range(5)))
print(list(range(1,15,3)))
if 5 in range(10): print(True)
In the above code, line 1 would print out [0,1,2,3,4]. Line 2 would print out [1,4,7,10,13]
because it starts at 1, ends at 14 and goes up by 3 each time. Here are some more examples.
Notice that the end of the range is never included! If the lower end is left off, it defaults to 0.
range(5)
range(1,6)
range(1,6,2)
0,1,2,3,4
1,2,3,4,5
1,3,5
You can test inclusion in a range by using the in operator, as shown in line 3.
Program 9
Topic: functions
To make a function use the def keyword, followed by a function header, which is a legal name
followed by a list of parameters. Then there is a colon. What comes next is the body of the
function, indented by blanks or tabs.
1
2
def square(n):
return n*n
If the body of the function is one line, it may be put on the same line as the header:
1
def square(n): return n*n
You can do this even if the body is several lines long by separating the statements with
semicolons, though this sacrifices readability.
Functions often have a documentation string in them to aid searching through APIs. These
documentation strings, called docstrings, use three double quotes in a row or three single quotes
in a row to both start and end the docstring. The docstring must be the first thing after the
function header:
1
2
3
4
def sqrt(n):
'''Compute the square root of the parameter and return it as
a float'''
return n**0.5
The docstring normally doesn't do anything but can be used when you want to read it again. Just
print out the function name followed by .__doc__ (Notice the two underscores before and 2
more after doc.)
print sqrt.__doc__
Program 10
Topic: local variables
1
2
3
4
5
6
7
def gcd(number1, number2):
a = number1
b = number2
while a > 0 and b > 0:
if a > b: a %= b
else: b %= a
return a if b == 0 else b
In the program above, the gcd of two ints is calculated by a slightly different method using the
modulus operator (%), which returns the remainder after integer division. 18 % 3 is 0 because
183 is 6 with remainder 0. 17 % 3 is 2 because 173 is 5 with remainder 2.
The expression-level if/else operator is illustrated in line 7. The expression (a if b==0 else b)
evaluates to a when the value of b is 0, and evaluates to b otherwise. It could have been written
using a full-blown if-else construct.
The parameters to this function are number1 and number2. They are assigned values when you
enter the function and act as local variables. For example print(gcd(18,12)) would assign
18 to number1 and 12 to number2. We can create other variables inside a function, as we did in
lines 2 and 3, namely a and b. These variables will not clash with similarly named variables
outside the function. That is, we could have variables named a, b, number1 and number2
outside this function and Python would keep their values separate from those inside the function.
Global variables are variables which are declared outside a function. Their use is generally
considered dangerous and undesirable. The way to declare a global variable in Python is to put
the keyword global in front of it, as shown below:
1
2
3
4
5
6
def gcd(number1, number2):
global a
a = number1
global b
b = number2
(as above)
You have to declare a variable to be global in a separate statement from assigning it a value, as
shown in the pairs of lines 2,3 and 4,5. You cannot condense those four lines into two.
Program 11
Topic: nested functions
1
2
3
4
def euclid_dist(x1, y1, x2, y2):
def square(n): return n*n
def sqrt(n): return n**0.5
return sqrt(square(x1-x2) + square(y1-y2))
Functions can call other functions. Line 2 defines a square() function and line 3 declares
another function called sqrt(). Both are inner functions that are not visible or usable outside
the dist() function. In a sense, they vanish whenever control leaves the dist() function.
Functions need to be declared at the time of execution. Simply defining a function does not run
the body; hence any function called in the body need not be defined yet. But when that
executable statement is run, and the function is called, the function needs to have been defined.
This implies that if you have "main" code that uses defined functions, those function definitions
have to appear before your main code. This may be a little awkward because you will see just a
lot of defs at the top of your file, not your main code.
The following will not work because euclid_dist() is not defined yet in line 2.
1
2
3
4
x1 = input("x1: ")
print(euclid_dist(x1,y1,x2,y2))
def euclid_dist( … as above…)
A way to fix this is to define a main() function at the top, followed by all other defined functions
that it calls, and at the bottom, simply call the main.
1
2
3
4
5
6
7
def main():
x1 = input("x1: ")
print(euclid_dist(x1,y1,x2,y2))
def euclid_dist( … as above…)
main()
# call main here
Program 12
Topic: named parameters
1
2
3
4
5
6
7
8
def append2list(oldlist, newthing):
oldlist.append(newthing)
mylist = ["cat","dog","snake","bird"]
append2list (mylist, "cow")
append2list(newthing="cow", oldlist=mylist)
print(mylist)
Normally, you could call append2list() as in line 5. The parameters usually match up in terms
of position. Hence "cow" gets put into the parameter newthing while mylist is the identity of
oldlist, in line 5. To override this, put the name of the parameter in front of the value in the
line 7. A warning: both parameters oldlist and newthing must appear in the call. That is, if your
function has two parameters in the definition, then in every call there must be two items.
Program 13
Topic: default values for parameters
1
2
3
4
5
6
7
8
def append2list(oldlist, newthing="bat"):
oldlist.append(newthing)
mylist = ["cat","dog","snake","bird"]
append2list(mylist)
# a bat gets put into this list
append2list(mylist, "deer")
print(mylist)
Sometimes you might want to give a default value, in case one is omitted. This is done with an
equals sign in the header, as in line 1. This is an extension of the example of Program 12. "bat"
is the default animal to put into the list.
Normally, default parameter values are used for values that commonly occur, such as printing
formats, shown below:
1
2
3
4
def formatString(number, format="%10.2f"):
return format % number
print (formatString(7/3))
You can specify a value for the format parameter if you want something other than "%10.2f"
But if you are happy with that, just leave it off. (Printing formats cannot be intermixed between
ints and floats, however. If number is an int, this will crash!)
If you have more than one named default parameter, and you leave off some parameters in the
actual call, Python must not get confused about which is which. It starts from the end of the
formal parameter list and works backwards, filling in defaults for missing actual parameters. Of
course, named parameters could be combined with this to keep things straight.
Program 14
Topic: optional parameters
1
2
3
4
5
6
7
def append(somelist, val1, *othervals):
somelist.append(val1)
for x in othervals:
somelist.append(x)
mylist = [53,27]
append(mylist, 2, 14, 99)
Optional parameters let you call the same function in many different ways, with differing
numbers of parameters. The optional parameters must always be at the end of the header and the
name of the list is preceded by an asterisk, as in line 1. Non-optional parameters precede it, and
for obvious reasons there can be only one optional parameter name.
Optional parameters are gathered together into a list at call time (line 7) and this list can be
iterated over like any other list (lines 3 and 4.)
Program 15
Topic: tuples
1
2
3
4
5
6
7
8
record = "Mark", 26, 56385.43, "programmer"
print (record)
print (record[0])
print (record[-1])
print (len(record))
print (record[1:3])
print (str(record))
for i in record: print (">>>>", i)
Tuples are just frozen lists. That is, they look and act exactly like lists except they can't be
changed once they are made. To emphasize this, Python makes you specify tuples with
parentheses instead of square brackets.
mylist = [1, 5, "john"]
mytup = (1, 5, "john")
is a list with 3 elements
is a tuple with 3 elements
The list can be changed, such as mylist[2] = "susan", which would replace "john" with
"susan." But mytup[2] = "susan" will crash. We say tuples are immutable, i.e. cannot be
changed or mutated.
The mytup assignment above could be written without the parentheses, such as:
mytup = 1, 5, "john"
One of the main reasons why tuples are frozen is so they can be used like a kind of "name" or
identifier for quick searching and identification. This will come in handy with maps later.
There are some surprising uses for tuples. One of them is to swap two variables' values.
x, y = y, x
The reason this works is because the right side creates a tuple. So the above is a shorthand for
x, y = (y, x)
The tuple is formed from the current values in y and x. For example, if y is 17 and x is 2, then
(17,2) is the tuple so created.
Then assigning a tuple to a list of variables will "unpack" the tuple's parts into the variables. The
list of variables must be the right length or the statement will crash. For example, going back to
mytup above, you could unpack that into three variables:
a, b, c = mytup
which is kind of shorthand for
a = mytup[0]; b = mytup[1]; c = mytup[2]
Thus, the swap statement works! x, y = y, x
Tuples can be converted to lists easily by using the list() typecaster. The original tuple is not
changed. A new list is created from the values in the tuple:
somelist = list(mytup)
You can create a tuple from a list by doing something similar:
newtup = tuple(somelist)
which will create a new tuple.
If you needed to change a tuple, a roundabout way would be to "unfreeze" it by converting it to a
list, changing the desired element of the list, then "freezing" it into a tuple again. The original
tuple object would be thrown away, however, and a completely new one made at the end by the
tuple() built-in function.
temp = list(mytup)
temp[2] = "susan"
mytup = tuple(temp)
Program 16
Topic: sets
1
2
3
4
5
6
7
8
9
myset = {"Mark", 26, 56385.43, "programmer"}
print (myset)
print (len(record))
mylist = list(myset)
for i in myset: print (">>>>", i)
if "Judy" in myset: print("Yay!")
if "Mark" not in myset: print ("Mark's not home")
newset = set([5,7,2,8,5,9,7])
print(newset)
Sets are collections where each element is unique (occurs no more than once) and the order
doesn't matter. So they vary from lists in these two ways. In addition, you cannot get at the
individual pieces of a set through indexing like you do with sets. Thus myset[0] doesn't work.
You can create a list from a set (line 4), however, and you can create a set from a list (line 8.)
However, if the list has duplicates, they are removed. Thus, line 9 would print [5,7,2,8,9]
because 5 and 7 occur twice in the list that is fed to the set() built-in function.
Since you can't peek inside a set with indexing, you can use a for loop to iterate through its
elements, as in line 5. And you can use the "in" operator (line 6) to ask if something exists in
the set. There is also a "not in" operator as shown in line 7. Mathematics often uses the term
"element of."
Perhaps the most useful thing about a set is that is creates a unique "list" of things when you
create a set from a list, obviating the need to code that yourself. Thus, removal of duplicates in
line 8 is quite handy.
Program 17
Topic: dicts
1
2
3
4
5
6
7
8
ages = {"Mark":57, "Kathy":26, "Sally":60, "Luke":3}
print (ages)
print (len(ages))
mylist = list(myset)
for i in myset: print (">>>>", i)
print (ages["Kathy"])
ages["Mark"] += 1
agevalues = list(values(ages))
A dictionary is a kind of collection object where you pair up other objects. That is, you store
objects (of any type) into the collection but you get at them using a string or any other object,
called the key. Arrays and lists and tuples could be thought of as a special kind of dictionary
where the type of the keys is an integer, such as 0, 1, 2, etc. In a dictionary, the keys are often
not numbers, though they can be. Keys are often strings, but could be almost anything, including
tuples.
Suppose you created a collection called mylist. If mylist were an ordinary list,
mylist[5] = 27 would put the value 27 at location 5. For a dict, you can write something more
liberally like
capitals["Nebraska"] = "Lincoln"
thereby storing the string "Lincoln" in the capitals collection, but at the "Nebraska" location. We
would say "Nebraska" is the key and "Lincoln" is the value associated with that key.
Keys must be unique in a dictionary. If they weren't, then you would have confusion because the
dictionary wouldn't know which value to give you when you asked for whatever was associated
with the key. For example, the state of Nebraska only has one capital, so it makes sense that if
you ask the capitals dictionary to give you whatever was associated with "Nebraska," it would
find only one such entry and give you "Lincoln."
Values do not have to be unique, however. Suppose that the good folks of Illinois wanted to
build a new city in honor of their famous son, Lincoln, and name it after him. They could make
Lincoln their capital:
capitals["Illinois"] = "Lincoln"
That would work because there is still only one unique capital city for Illinois. Its name just
happens to be the same as the capital of Nebraska. So keys must be unique but values do not
need to be.
If you need more than one value to be associated with a single key, then the value could be list.
For example, some books say that country of the Netherlands has two capital cities. So you
would have to specify that like:
capitals["Netherlands"] = ["The Hague", "Amsterdam"]
Or you could have associated a tuple or a set:
capitals["Netherlands"] = ("The Hague", "Amsterdam")
capitals["Netherlands"] = {"The Hague", "Amsterdam"}
The important thing about dicts is that an object can be stored in the collection and accessed
again given another object (called the key), but only one object can be associated with that key
at any given time. You could change the association later, though:
capitals["Netherlands"] = "Rotterdam"
In this case, the single string "Rotterdam" wipes out the list (or tuple or set) that was formerly
associated with "Netherlands."
Dictionaries use a hashing implementation to store and find values given keys, and because of
the way Python stores lists and tuples, only tuples can be keys. The following would be legal:
population[("Lincoln","Nebraska")] = 287000
and this would keep the population of that city in that state different from other cities named
Lincoln and other cities in Nebraska.
However the following will not work:
population[["Lincoln","Nebraska"]] = 287000
because ["Lincoln", "Nebraska"] is a mutable list, not a fixed tuple.
Program 18
Topic: Objects and classes
1
2
3
4
5
6
7
8
9
10
11
class Fraction:
''' A class for a simple fraction '''
def __init__(self, num, den):
self.numerator = num
self.denominator = den
# in main
frac1 = Fraction(3, 5)
print("Fraction is ", frac1.numerator, "/", frac1.denominator)
print(Fraction.__doc__)
Objects and classes in Python are very similar to objects and classes in Java and other languages,
with some interesting twists. Making a class is simple, as line 1 shows. Line 2 is a
documentation string, similar to what you can put into any function. Later, when you want to
just see the documentation for a class or a function, put .__doc__ after its name (note that
__doc__ has four underscores, two in front and two in back!) These docstrings can be many
lines long. Just start out with three double quotes or three single quotes and after the last line,
put three of the same kind of quotes again.
Classes generally contain methods only. There is a special method called __init__ that is called
when making a new instance of this class. Java calls this a constructor. All methods that are not
class methods (aka "static methods" in Java), must have self as the first parameter, as does the
method in line 4. The Python keyword self is synonymous with this of Java.
To make instance variables for a class, the constructor just assigns self.varname a value, as in
lines 5 and 6. This is the only way to make an instance variable.
To make an object from this class, do not use Java's new keyword. Instead, just pretend the class
name is a function, as in line 9. Then you can use the typical "dot" notation to access its methods
and members.
Python allows inheritance like Java and C and many others, but it also allows multiple
inheritance (where more than one class is a superclass.) Here's how you could extend the
Fraction above to make a more involved class:
class MixedFraction (Fraction):
If there were two superclasses, they would be listed inside the parentheses.
Note that you can find out what is inside a class by using the built-in dir() function:
print (dir(Fraction))
Program 19
Topic: More complex OOP
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Fraction:
''' A class for a simple fraction '''
numfracs = 0
def __init__(self, num, den):
self.numerator = num
self.denominator = den
Fraction.numfracs += 1
def add(self, otherfrac):
if self.denominator == otherfrac.denominator:
return Fraction(self.numerator + otherfrac.numerator,
self.denominator)
else:
newdenom = self.denominator * otherfrac.denominator
top1 = self.numerator * otherfrac.denominator
top2 = otherfrac.numerator * self.denominator
return Fraction(top1 + top2, newdenom)
In the program above, there is a class variable, numfracs, which is declared in line 4. Since it is
not preceded by self, it is a common variable for all instances of Fraction. It will keep track of
how many Fractions we make, and will be incremented in line 9 when we make a new
Fraction. Note that when it is used as a class variable inside a method, it must have the class
name prepended to the front, as in line 9.
Lines 11-19 show a realistic method other than the constructor method __init__. The add
method is an instance method, hence it must have self as the first parameter. Then it takes a
second fraction which is put into otherfrac. This method returns an entirely new Fraction.
We could have rigged it up so that it added the otherfrac into the current one, changing it.
Here's how to make some fractions and add them:
f1 = Fraction(3,4)
f2 = Fraction(5,7)
f3 = f1.add(f2)
print(f3.numerator,"/",f3.denominator)
If you change the name of the method from add to __add__ in line 11, you can use the +
operator, as shown below:
f1 = Fraction(3,4)
f2 = Fraction(5,7)
f3 = f1 + f2
print(f3.numerator,"/",f3.denominator)
Program 20
Topic: Even more complex OOP
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
class Fraction:
''' A class for a simple fraction '''
numfracs = 0
def __init__(self, num, den):
self.numerator = num
self.denominator = den
Fraction.numfracs += 1
def __add__(self, otherfrac):
if self.denominator == otherfrac.denominator:
return Fraction(self.numerator + otherfrac.numerator,
self.denominator)
else:
newdenom = self.denominator * otherfrac.denominator
top1 = self.numerator * otherfrac.denominator
top2 = otherfrac.numerator * self.denominator
return Fraction(top1 + top2, newdenom)
def __str__(self):
return str(self.numerator) + "/" + str(self.denominator)
def __float__(self):
return self.numerator / self.denominator
Next, let's change add to __add__ to take advantage of the builtin operator +. Let's also give our
class a way to print itself elegantly, with the __str__ method in lines 21-22. The following
prints 3/4:
f1 = Fraction(3,4)
print(f1)
Finally, sometimes we want to see the real number equivalent, so we can do that in lines 24-25
with the __float__ method:
print(float(f1))
There are many other things about Python's object system that we cannot cover here. But what
follows are a few items:


There are no private or protected members, but if a name starts with an underscore, it is
considered private. It will not show up if you do dir(classname).
Since there may be several parent classes, the super keyword does not exist in Python.
To get at methods of superclasses, use the name of the class explicitly, such as
MyParent.somefunction().
Program 21
Topic: Modules revisited
1
2
3
4
5
def square(n):
return n*n
if __name__ == '__main__':
print("Main code goes here.")
A module is merely a file with Python code in it. Usually there are class and function definitions
but there may be "naked" code, too (lines 4-5.) Modules' names end in .py. Suppose the above
is called mymath.py.
If you want to run mymath.py as a main program, you would run it from the command line:
C:\> python mymath.py
This is useful if you want to put debugging or testing code in the file which will exercise all the
functions in it. However, if you want to use module by importing it elsewhere, you wouldn't
want that code to run. So the standard practice is to put the code inside an if statement that
checks to see if the module is being run as a main program or not. Only if you run it as a main
module will __name__ be set to '__main__', as shown in line 4.
To use module's contents inside another program, use the import statement, but leave the .py off
the name:
import mymath
This statement does not need to be the first line in the file. It can be anywhere.
Program 22
Topic: Files
There are some very simple ways to read and write external files in Python. The following reads
the entire file's contents as one huge string which can be broken up later.
1
2
3
4
5
with open("mystuff.txt") as f:
text = f.read()
print(text)
print(len(text))
If you wanted to process this file's contents one line at a time, simply split it up and run a for
statement:
for line in text.split("\n"):
print(line[2:-5])
# do something with each line
# (this is just an example)
The "with" construct above is a control structure that simply make exception handling very neat.
It runs the statement after with (in this case the open() function call) and then it tries to run the
indented statements. If anything goes wrong, it closes the file properly and cleans up.
Here's a version without the "with" construct:
f = open("mystuff.txt")
text = f.read()
f.close()
Creating or overwriting an existing file are easy. Just open with "w" as the second parameter.
f = open("mystuff.txt","w")
f.write("This is new contents\nof the file.\nThere are 3 lines.")
f.close()
You could also write lines to a file one at a time:
f = open("mystuff.txt","w")
f.write("This is new contents\n")
f.write("the file.\n")
f.write("There are 3 lines.")
f.close()
You don't have to do the f.write() statements all in one clump. You could be in a loop or a
function or anywhere.
Just make sure to close the file or else some of the text that you tried to write to it won't show up
because the OS will stop your Python program before everything is written out.
Program 23
Topic: File filter programs
1
2
3
4
5
6
7
8
9
10
infilename = input("What is the name of the input file?")
outfilename = input("What is the name of the output file?")
fin = open(infilename)
fout = open(outfilename, "w")
for line in fin.read().split("\n"):
if not dokeep(line): continue
newline = modify(line)
fout.close()
Notice that you need to write two functions and declare them above this code:
dokeep(line) returns True or False, determines if we should keep this line or ignore it
modify(line) returns a string that is some new version of the original input line; might
be as simple as just returning the line unchanged. In that case the real
work is in the dokeep() method.