Python reference
This page is intended to serve as a brief, beginners reference to the Python programming language.
Contents
[hide]VARIABLES
In Python, there is no need to specify a type when storing information in a variable. It is basic and straightforward to store information.
number = 1
This would store the integer value 1 in the variable 'number'.
message = "hello"
This would store the string 'hello' in the variable 'message'. Be sure to remember quotation marks for strings.
FILES
Typing in stuff is fun, but if you have a lot of data, it is more likely to be stored somewhere on your hard drive. So we need to be able to read data from a file.
And similarly, printing works for short things, but if you want to look at something later, it needs to be written to a file.
The trickiest part of the process is putting the file in the right place so Python knows where to find it. You can use IDLE to make a new window, type a few sentences into it, and then save it as a txt file (like sentences.txt). IDLE should choose the appropriate directory automatically.
To do anything with a file, the first thing to do is to open it. Here's how:
myFile = open('sentences.txt', 'r')
myFile is a variable to hold the file object that the open function returns. The function itself takes two parameters. The first is a string with the name of the file.
The second indicates what you want to do with the file. The options are as follows:
open('sentences.txt', 'r')
The above code opens a file for reading, thus the 'r' above. You can access the contents of the file in this manner.
open('sentences.txt', 'w')
The above code opens a file for writing, thus the 'w' above. You can append to documents in this manner.
FILE USE IN PIG LATIN PROGRAM
def convertFromFile(): myInFile = open('sentences.txt','r') myOutFile = open('translated.txt','w') for sentence in myInFile: sentence = sentence.strip() answer = "" brokenSentence = sentence.split() for word in brokenSentence: answer = answer + toPigLatin(word) + " " myOutFile.write("In Pig Latin, "+sentence+" is "+answer+'\n') myInFile.close() myOutFile.close()
This is the conversion program. This will open a text file that has sentences in it and convert the sentences to Pig Latin, while adding the Pig Latin to another text file called 'translated.txt'.
The above code makes use of a method called toPigLatin() and then takes a string as a parameter. The code for this method is below:
def toPigLatin(word): vowels = 'aeiou' if (word[0] in vowels): return word+"way" else: while word[0] not in vowels: word = word[1:]+word[0] return word+"ay"
LISTS
Lists are used very frequently in Python. An example of a list is below:
ls = [1,2,3,4,5]
The above code instantiates a list that contains the values 1,2,3,4, and 5. These all have indices associated with them. The 1 is in position 0, the 2 in position 1, and so on, all the way to position 4, which holds the value 5.
LIST FUNCTIONS
ls = [1,2,3,4,5]
In order to access certain elements in a list, we can use methods such as:
ls[0]
This would return the number 1, because that is the element at position 0 (the front) of the list.
len(ls)
This would return 5, which is the length of the list (number of elements in it).
ls[-1]
This would return 5, which is the last element in the list. An index of -1 starts from the back of the list and gives you that element, so ls[-2]
would give you 4 as a result because it is 2 positions from the back.
ls[1:3]
This would return the list [2,3] because it returns everything from the first number's index (inclusive) to the second number's index (but not including this number). In other words, this returns everything from position 1, including position 1, all the way to position 3, not including position 3. This is called a slice.
ls[:3]
This is another example of slicing. When no first number is given, it automatically starts from the beginning, so this would be from the beginning up to position 3 (not including position 3). This would return the list [1,2,3].
ls[1:]
Similar to the above code, this will begin at position 1, including position 1, and go all the way to the end (because no number was specified for the second number. This would return the list [2,3,4,5].
ls[:]
This gives you a copy of the entire list [1,2,3,4,5]. This can be helpful for list manipulation.
ls[::2]
This gives you every other element in the list. So it will go through all of the list and return the number every 2 steps, which is what the 2 means. This will return the list [1,3,5].
ls + [6,7,8]
This is simple concatenation. It would result in the list [1,2,3,4,5,6,7,8]
ls*2
This is a multiplier, and would result in the list [1,2,3,4,5,1,2,3,4,5].
3 in ls
This is a conditional statement that would return True because it would search the list for 3 and find it. If we searched for something like 100, it would return False.
min(ls)
This would return 1 in our case. It checks the list for the smallest element and returns it.
max(ls)
Works similarly to min() except it returns the largest element. If we were working with the original value of ls (which is [1,2,3,4,5]) then this would return 5.
sum(ls)
This would return 15, which is the sum of all of the elements of the list (1+2+3+4+5).
Lists are mutable, which means we can change values within them by making calls like the one below:
ls[0] = 10
This would set the value of position 0 to 10 (and change it from its previous value of 1). If we printed the list after this change, the list would now be:
[10,2,3,4,5]
Similarly, we can use slices to do this:
ls[1:3] = [0,0]
This would set the positions 1 and 2 in ls to 0, so if we used the original values in ls (which is [1,2,3,4,5]), then the new list would be [1,0,0,4,5]
What do we do if we don't know where a value is in a list?
ls.index(3)
This checks the list for 3 as a value and returns the index. This would return 2 because 3 is in position 2 of this list.
ls.count(3)
This checks how many times the value 3 is in the list. In this case, it would only return 1.
ls.append(6)
This would add 6 to the end of the list, giving it the new value of [1,2,3,4,5,6].
Let's make a new list, called ls2 and it will be the following:
ls2 = [3,4,2,1,5]
This list contains the same elements as the ls we had before, but it is in a different order. How can we make them the same?
ls2.sort()
This would sort the list and it would end up being [1,2,3,4,5], which is what ls was.
TUPLES
A tuple is very similar to a list.
One major difference is that it uses parentheses:
tup = (1,2,3,4)
Almost everything you can do with a list you can do to a tuple. This table lists what can and can not be done with tuples.
What Can Be Done | What Can't Be Done |
|
|
The things you cannot do are the things that change the tuple. This is where lists and tuples are different. Tuples are immutable objects. They cannot be altered.
DICTIONARIES
This idea of key and value could be applied to almost anything. A student is a key; the associated value might be their score on an exam. Or it might be their social security number.
One other example: The key could be a variable, and the value could be the associated object. In fact, this is exactly how Python works with variables.
DICTIONARY EXAMPLE
grades = {'arthur':90, 'belle':60, 'charles':80}
The code above creates a dictionary with the keys being arthur, belle, and charles. They each have grades on an exam, where the grades are the values of 90, 60, and 80 respectively.
Note how it's formed. We use curly braces (hold down shift while typing square brackets) around the entries. Each entry is separated by a comma, just like a list or tuple. Each entry consists of two things separated by a colon. To the left of the colon is the key, to the right is the value.
Simply typing grades into the Python Shell would return the dictionary in its entirety. But let's see how to access specific values in it.
grades['arthur']
The above code would return the value associated with the key 'arthur', which is 90.
Dictionaries are mutable, so it's easy to change the key/value pairs. For example, if we misgraded Charles' exam, we can enter:
grades['charles'] = 85
This code will change the value associated with charles from 80 to 85.
We can also add in new keys too:
grades['doug'] = 70
This code will add a new key 'doug' and a value of 70 associated with him.
There are some methods which can be used on dictionaries that we have seen before.
len(grades) would return the number of students entered (# of keys). 'charles' in grades would return true because charles is one of the keys. list(grades) returns a list of all of the students in the dictionary. grades.values() returns a list of all of the values of the exam grades.
There are many more functions than these which can be used to help with dictionaries. Type help(dict) to check them out in IDLE.
FOR-LOOPS
In Python, as well as in most programming languages, you can do for-loops to accomplish many things in a program.
for i in range(5): print("hey")
This code will print the word "hey" five times.
You could also do something like this:
for i in range(5): print (i)
This code will print the numbers 0 through 4 on different lines. Each time the it would go through the loop, the i is updated by one. It starts at 0, then prints 0, then after it prints, it is incremented (one is added to it), then it prints its new value (1). It does this all the way until it reaches the number in the range (exclusive), so in this case it stops at 4, because when 1 is added to it, it is no longer strictly less than 5.
for number in ls: print (number)
This code will step through the list and instead of incrementing the value of the variable "number" in each iteration, it will be set to the next element in the list. If the list (ls) were [2,4,6,1] then for the first iteration of the loop, the value of number would be 2, followed by 4, followed by 6, and finally by 1. This is an extremely useful for-loop to know and use. You can also do this type of loop with strings. See below for an example.
for letter in word: print (letter)
If the string stored in word was "fish" then on the first iteration, it would print f, and then i, and then s, and finally h.
INPUT AND OUTPUT
INPUTS This will help you learn how request inputs and store them in variables.
We have learned how to store values into variables already. Now we will learn how to request information from the user and store that information in a variable.
entree = input('How much is the entree?')
When this line of code is entered into python, it will immediately print a message (in this case "How much is the entree?"). After the message pops up, there will be a place to type and press enter. Once some text is entered, it will be stored in the entree variable.
If the above code was run and the user typed in 5.50 as the price, the variable entree would contain the value 5.50 afterwards.
This would be fine if we wanted to print it, but we are in a heap of trouble if we want to add 2 to this value or add it to another price. We must convert it to another datatype before we can do this.
In order to make this conversion, we can type the following:
entree = float(entree)
Now we can manipulate the value of entree by typing something like:
entree + 2
You can also do you this with int(variable) to convert it to an integer.
Finally, if we want to print this value in a sentence, we can do something like the following:
print ("The total is " ,entree)
The total is 5.50
"The total is 5.50" is what is printed when the above is run.
EXAMPLE INPUT PROGRAM
The following program prompts a user for the radius of a circle and it returns the diameter, the circumference, and the area of that circle.
# Computes statistics about a circle # by Scott Weiss radius = input('Enter the radius of the circle: ') radius = float(radius) diameter = 2 * radius circumference = 3.14 * diameter area = 3.14 * (radius ** 2) print('The diameter is: '+str(diameter)) print('The circumference is: '+str(circumference)) print('The area is: '+str(area))
FUNCTIONS
It's most closely tied to the mathematical idea of a function. Here's a simple one: f(x) = x + 5, which adds five to the input.
If I give you a value for x, say 2, you put it into the equation on the right side to get 2 + 5 or 7. So we would say f(2) is 7.
In programming, we use a function in the same way. We give a function some inputs, it does some computations, and (probably) gives us an output.
In general, we use a function to do a particular subtask that's part of a larger program. Let's look at some examples.
getAverage()
def getAverage(x, y): return (x+y)/2
This straightforward function will return the average of two numbers that it takes as input.
MODULES
Let's figure out the sine of a 30-degree angle in Python!
It should be 1/2 or 0.5.
Just like in trig class, it's sin. So evaluate sin(30) should give us the answer, right?
Actually not. It doesn't seem to know what sin means. The error says that 'sin' is not defined.
Python does know about sin. But it's not part of the system when you start Python up. Why can't Python just load all possible functions at startup?
If we loaded every possible function, we'd overwhelm your computer's memory! There'd be no room for your actual program. So we'll only bring in most functions when we say that we need them.
MATH MODULE
Functions are grouped into files called modules. For example, all the trigonometric functions are in a module called math.
So to use sin, we need to tell Python to bring the math module into the shell.
SIN() FUNCTION
Here's the statement we need:
import math
Note the orange color of import. That shows it is a reserved word.
Now Python knows about this module, and we can use it! Go ahead and figure out sin(30) by calling the name of the module:
OK, to use a function from a module (after importing the module), give the name of the module, then a period (.), then the name and any parameters.
The call for the sin function would be:
math.sin(30)
so give it a try. Remember the result should be 0.5.
-0.9880316240928618??
This does not give us 0.5. Why is that? The reason is that the sin() function expects to receive its parameter in a unit called radians (and we gave it in degrees). How do we fix this?
There's a function called radians() that takes a value in degrees and converts it to radians. That's exactly what we want.
So how do we use it? This is really cool.
math.sin(math.radians(30))
Remember to read it inside out (just like nested math functions f(g(x))). Take 30, convert it to radians, then take the sine of that angle.
That gets us really close to 0.5 (we discussed why it was off in class last week). How do we push it the rest of the way?
How about round? Can you add that to the call?
round(math.sin(math.radians(30)), 1)
SQRT() FUNCTION
Let's see how we would use the math module to calculate the square root of a number:
>>> import math >>> math.sqrt(4) 2.0
LOG() FUNCTION
Let's see how we would use the math module to calculate the log of a number:
>>> import math >>> math.log(2) 0.6931471805599453
The way the log() function works as shown above is to calculate the natural log of a number. If we wanted to specify the base of the number, you would just add it after the 2 with a comma. For example, if I wanted to calculate the log (base 10) of 2, I would type the following:
>>> import math >>> math.log(2, 10) 0.30102999566398114
EXP() FUNCTION
The last thing we will look at in the math module is the concept of e. In order to calculate e in Python, you need to make the call to the function exp(), as follows:
>>> import math >>> math.exp(2) >>> 7.38905609893065
This function returned e raised to the second power.
RANDOM MODULE
There is also a module called Random. This can be used to bring in random numbers for a program that might need them.
RANDINT() FUNCTION
import random randNum = random.randint(1,30)
The randint function returns a value in the range from 1 to 30 inclusive.
TURTLE MODULE
All of our programs to date have been text-based. Now we're going to do some drawing. Python has a module called turtle that makes it easy to do simple line drawings.
IDLE does not play well with graphical programs. We'll develop some turtle code using IDLE, but we'll run it using the basic shell. To open the basic shell in Windows, choose All Programs from the Start Menu, select Python 31, and then choose Python (command line).
The turtle is a symbol on the screen that marks where you are in the drawing. Think of it as the tip of a pen. We'll build the drawing by moving the turtle around.
The first thing we enter is the same as other modules:
import turtle
Next we want to create a turtle object. We've created objects before, but all of those used special punctuation to help specify the object. For example:
We put quotes around the text we want to make a string.
To make a list, we use square brackets around the elements, which are separated by commas.
Most objects, either those from modules or ones we create, don't use punctuation for creation. Instead they use a special kind of function called a constructor. The name of the constructor is always the name of the corresponding class.
So let's see how this works for turtles. Enter the following into the shell:
yertle = turtle.Turtle()
You should see a window automatically pop up on your screen. (If it doesn't, look behind some other windows.) The window should be labelled "Python Turtle Graphics". In the center of the window, there should be a black triangle pointing to the right.
This is the picture of what you should have after importing turtle and creating yertle above.
turtle (lowercase t) is the name of the module we've imported. Turtle (capital T) is the constructor. Now yertle is a Turtle object.
Now we'll draw a square. To do this, we'll use methods to manipulate yertle. We'll use two here. forward() takes a distance as a parameter and moves the turtle forward (based on how it's pointing) that many pixels. left() takes an angle and turns the turtle that many degrees to the left. As you may guess, there's also a right() method that turns the turtle right.
Each angle in the square is 90 degrees so you go left or right 90 degrees to squarely turn.
for x in range(4): yertle.forward(100) yertle.left(90)
This code draws a square in the Turtle Graphics. [See code here]
Let's see this in a function.
def drawSquare(t, dist): """Makes t draw a square whose side length is dist""" for x in range(4): t.forward(dist) t.left(90)
The parameters of this function are a turtle and the side length of the square.
def drawRegularPolygon(t, dist, s): """Makes t draw a polygon with s sides whose side length is dist""" for x in range(s): t.forward(dist) t.left(360/s)
This function draws a polygon with the turtle t. dist represents the side length and s represents the number of sides of the polygon.
def drawHouse(t, dist): drawRegularPolygon(t, dist, 4) # the square t.up() t.left(90) t.forward(dist) # move to the top of the square t.right(90) # point in the correct direction t.down() drawRegularPolygon(t, dist, 3) # the triangle
I raised and lowered the pen while I shifted the turtle, but it would just redraw a line that already exists if I hadn't. This function draws a house of side lengths valued at dist. The length of the roof pieces is the same as the side lengths.
CLASSES
Classes take a very different approach. Instead of having the data be in a sense external to the function, the data becomes internal to the function.
A function (or really a method) is called on a particular object. This object "knows" its own data, so it works appropriately with that data. The data about the object is thus not passed via parameters; it's already within the object.
To clarify, suppose we make a House class. House objects will have a size and location as part of their data (in the same way that a string object has its text as its data). We can then make a method for a House called draw.
CLASS DECLARATION
Defining a class involves a new keyword. Unsurprisingly, it is class. Here's the first line.
class House:
Pretty straightforward, I hope. class indicates what we're doing; House is the name we picked for the class.
The same rules for variable and function names apply for names of classes. You may have noticed, though, that I capitalized House. The typical style is that classes have capitalized names to give an immediate visual clue as to their purpose.
The colon at the end, as usual, indicates we're about to begin a block of code that actually defines the class.
We'll generally begin a class with a docstring, just like we did with functions. Here's an example for House:
"""Represents a house A house has a size, represented by the length of one side It also has a location, represented by the x and y-coordinates of its lower-left corner. """</[pre> Then we follow it with the definition of each of the methods we want objects of the class to act on. There are several categories of methods that we'll often want to include. === '''CLASS CONSTRUCTOR''' === The call will use House(). But in the House module, when we define the constructor, we use an odd looking name. <pre>def __init__(
That's two underscores before and after the word init. Those underscores indicate a function which we will usually call in an atypical way.
As we saw with Turtles, we usually write something like t.forward(100). We give the object, then a period, then the function name followed by parameters.
But with the constructor, we didn't give a Turtle object first (we gave the module name first). As another example, we can define the method __add__ if we want to give a special meaning to the + sign for our class (the full list or these types of functions is here). Then we'd be able to write h1+h2 to add two Houses together.
init is an abbreviation for initialize. Remember we use the constructor to set up the object. For a House, that means we need to set up its size and location.
So that data should be passed to the method. We'll also need one more parameter - the object we're constructing.
How do we pass the object if we haven't built it yet? Python provides a solution to this by making a special parameter named self. This must always be given as the first parameter to the method. In fact, it will be the first parameter to every method we write for the class.
So let's put all these ideas together to get the header line of the method:
def __init__(self, dist, x, y):
We need to have the object (self) remember the data so we can use it later. We use variables to remember data, so it looks like we need to make variables tied to self.
Here's how to do it:
self.__xCoord = x
Let's break this down. self is the object. The dot indicates we're accessing a part of the object. Instead of a method as we've seen before, this time we're accessing a variable named __xCoord. Variables associated with a class or object are known as attributes. This particular attribute represents the x-coordinate of the lower-left corner.
You'll notice that the name of the attribute starts with two underscores. This is not a requirement; xCoord would have worked too. I'll get to why you want an underscore there in a little bit.
The rest of the line is your basic variable assignment. To repeat, this means the object now remembers the value of x in its __xCoord attribute. Can you fill in the lines we need for the other attributes?
Here's my answer. (You may want to use my attribute names for consistency later.)
def __init__(self, dist, x, y): self.__xCoord = x self.__yCoord = y self.__sideLength = dist
That's the complete answer. You may think you need to return the constructed object (i.e. return self). However, constructors don't need you to return anything.
You can run this module now, although it doesn't do anything exciting. You can create House objects with it:
myHouse = House(100, 10, 10)
myHouse is a House with side length of 100 whose lower-left corner is at position (10, 10).
CLASS FUNCTIONS
def __str__(self): """Builds a description of the house""" answer = "a House with side length of " answer += str(self.__sideLength) answer += " and lower-left corner at (" answer += str(self.__xCoord) answer += "," answer += str(self.__yCoord) answer += ")" return answer
This function returns a description of a house class.
myHouse = House(100, 10, 10) str(myHouse)
This will return a description of the House, in a sentence that says "A House with side length of 100 and lower-left corner at (10,10)".
CLASS ACCESSORS
Accessors are pretty easy to write. They return certain values in a class. Here's one for the side length in the House class:
def getSideLength(self): return self.__sideLength
def getXCoord(self): return self.__xCoord
This returns the value of the x coordinate of the house's bottom left-corner.
def getYCoord(self): return self.__yCoord
This returns the value of the y coordinate of the house's bottom left-corner.
CLASS MUTATORS
def setXCoord(self, newX): self.__xCoord = newX
This method sets the value of the x coordinate to the one you specify.
The body is just an assignment. Note that since this method changes the object, it does not need to return anything. It's analogous to the sort or reverse methods on a list.
def setYCoord(self, newY): self.__yCoord = newY
This method sets the value of the y coordinate to the one you specify.
def setSideLength(self, newSide): if (newSide < 0): self.__sideLength = 50 else: self.__sideLength = newSide
This method sets the sideLength to what the user specifies. If the user tries to give it a negative value, it sets the sideLength to a default value of 50.
def getArea(self): """Computes and returns the area of the house shape""" square = self.__sideLength ** 2 triangle = (self.__sideLength ** 2) * math.sqrt(3) / 4 return square + triangle
This gets the area of the house (including the base and the roof).