








Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!









Introduction to Python
A snake! A snake! A scaaary snake? Yes, but Python is also a programming language that youâll be learning this semester! Python bears some resemblance to Java, but is cleaner and easier to read in general. There are a few important differences from Java that you should note. First, you donât need to declare the types of variables. Thus you write x = 1 rather than int x = 1. Variables do have types, but you donât need to announce the type when you first use a variable. In fact, you can write x = 1 and then x = ââabcdââ in the same program; after the first assignment, x is an integer; after the second, itâs a string. (N.B. In general this is a very bad idea, so avoid it!) Second, the environment in which you work with Python lets you type bits of code and see what happens without an intermediate compiling step. This makes experimentation and testing very simple. Third, a feature of Python that you will grow to love and cherish is how easy it is to read. Instead of using a lot of punctuation and other symbols, which are what makes code in most programming languages look daunting and scary, Python uses English keywords and natural-sounding syntax. For example, this is a declaration and an if-condition in Python:
x = 1 if x > 0: print "x is positive" print "What beautiful syntax!" print "Do you love Python yet?"
Youâll notice that instead of using curly braces to delimit code blocks, Python uses whites- pace indentation. That means that correctly nesting your code now has semantic meaning, instead of just making it easier for you (and your TAs) to read. Weâll learn more about syntax later, so for now, just marvel at its beauty. Python is similar to Java in that it also handles your memory management, meaning it allocates memory and has a garbage collector to free up that memory once it is no longer needed, making your life a whole lot easier. If youâre not already convinced that Python rules...
Weâll be using Python throughout the semester to code up some of the algorithms youâll be learning. As a computer scientist you should get used to learning new languages readily, not only because itâs an important part of the subject, but also because itâs useful (and
Introduction to Python
fun!). Python is especially important to learn because it is used very widely as a scripting language â Pixar uses it for all their tools, for instance â so knowing it could one day help you get a job making a movie like Toy Story 3.
Itâs tradition when learning a new programming language that your first program is a âHello Worldâ program, so letâs start out by writing a simple one-line program that prints âHello world!â To start, open a terminal and run cs016_install pythonIntro. This will create a directory located at ~/course/cs016/pythonIntro and copy over primePrinter.py and checkexpect.py, which weâll use later in the tutorial. Go ahead and cd into the tutorial directory: cd ~/course/cs016/pythonIntro. Open the text editor Kate, by typing kate & in your terminal. Just like you used Kate to write .java files in CS15, weâll be using Kate to write .py files in CS16. Before you do anything else, we need to configure Kate to work best with Python:
Itâs important you configure Kate as specified above because Python usese whitespace indentation to delimit your code (more on this later). For the sake of convenience, we insist that you use 4 spaces to indent your code. It will make your code look consistent across machines and prevent inconsistencies between sapces and hard tabs. Note: You only need to configure Kate this one time. The settings will stay saved across sessions. Now that Kate has been configured, letâs actually write some Python code! Type
print "Hello world!"
and save your file as helloWorld.py. The .py is very important, so donât forget it! Save the file in your ~/course/cs016/pythonIntro directory. Now go back to your terminal, make sure you are in the pythonIntro directory and type python helloWorld.py to run the program. It will print Hello world! to your terminal. Hold on, do you really have to type python yourProgramName.py every time you want to run a program? (Or for the especially lazy, scroll through your commands until you find the last time you typed it?) Heck no! Go back to Kate and type
Introduction to Python
Itâs very important this code comes after the function definition, because functions must be defined before they can be called. (Note that this is different than Java). This bit of code will allow you to run it as a standalone program. The main line here is similar to Javaâs public static void main(String args[]). It contains the code that will run when you execute the program. Save your file (make sure it ends in .py!) and then run it using one of the two techniques we discussed earlier. The terminal will now greet you as if your name is Stephen. The number sign/pound sign/hash symbol/octothorpe # is used for inline comments in Python, similar to Javaâs double slashes // for commenting. Substitute your name into the parameters and watch your terminal try to befriend you. Unfortunately if you try to say hi back, you will see this:
gemini ~/course/cs016 $ python sayHi.py Hello Stephen! gemini ~/course/cs016 $ Hello Terminal! bash: Hello: command not found
So much for that ;( Letâs look at something a little more complicated. Say you had written out some pseudocode for a function that prints out the numbers 1 to n for n â„ 1. It might look something like this:
Algorithm printOneToN(n): This algorithm prints out the numbers from 1 to n for n â„ 1. If n is less than 1, it prints an error message to alert the user. Input: an integer n Output: none
if n < 1 then print "Invalid input: integer value cannot be less than 1" return for i â 1 to n do print i
In Python, following the CS16 Python coding conventions, it would look like this:
def print_one_to_n(n): """print_one_to_n: int ->. Consumes: an integer, n Produces: nothing Purpose: this function prints out the numbers from 1 to n for n >= 1. If n is less than 1, it prints an error message to alert the user. """ if n < 1:
Introduction to Python
print "Invalid input: integer value cannot be less than 1" return for i in range(1, n + 1): print i
Youâll notice that there arenât many differences between the pseudocode and Python. That is because Python is wonderful! Letâs go over some of the new Python syntax. An if-condition starts with if followed by the condition and a colon, no parentheses needed. Even though there are multiple lines of code in the if-block, there are no curly braces because everything is indented four spaces. So fresh and so clean. We could also write the if-statement as the equivalent statement:
if not n > 0:
Python favors English keywords in the place of punctuation, so you will see not used in Python in place of! in Java, and instead of &&, and or for ||. The function also has a for-loop to print the numbers from 1 to n. So why does it say range(1, n + 1)? The built-in function range() generates arithmetic progressions based on the optional start parameter, and required stop parameter that you feed it. Letâs understand this a bit better by just running python from your terminal. Python provides its own shell, where you can now run python commands to try things things out. Type range(10). Your required stop parameter is 10 and the start parameter defaults to 0, so the integers from 0 to 9 print out, since it âstopsâ before 10. Now type range(1, 10). Since you specified the start of the progression, it prints the numbers from 1 to 9. So if we want the function to print out the sequence, including n, we have to write range(1, n
Introduction to Python
It is day 25 of the month, which is not prime.
Methods
You need to implement the following methods in the primePrinter.py file that was in- stalled earlier.
Testing
Testing is important. Weâll be requiring you to write and submit tests for the Python assign- ments you write in the future. For this problem, write a method testPrimePrinterMethods() to ensure both methods work as expected:
Introduction to Python
Add a call to testPrimePrinterMethods() to your "main" body to actually run the tests when you run your program. When youâre convinced they work, you can comment out or remove this function call from the main body, so that your program can be used to meet its original objective.
Python lists will be used frequently in CS16. Lists are Pythonâs take on Javaâs arrays. You can create them as follows:
myList = [10, 2, 15, 30]
And index into them in much the same way as in Java:
myVal = myList[2] #myVal will now = 15
Unlike Java arrays, Python lists also have methods you can call, which you can read about in the documentation. Hereâs an example that builds a list of the first ten perfect squares:
perfectSquares = [] for i in range(1, 11): perfectSquares.append(i*i) #append adds the specified parameter to the end of the list
You can read about addition Python data structures, (like dictionaries!) at: http://docs.python.org/tutorial/datastructures.html
Python supports a concept called âlist comprehensionsâ which can help you create lists very easily. Here a few examples:
>>> vec = [2, 4, 6] >>> [3x for x in vec] [6, 12, 18] >>> [3x for x in vec if x > 3] [12, 18] >>> [3x for x in vec if x < 2] [] >>> [[x,x2] for x in vec] #x2 in Python is xx [[2, 4], [4, 16], [6, 36]]
Introduction to Python
coverage.stop() coverage.report(myaddmodule)
You nest all of your testing code between calls to start() and stop(). coverage will keep track of which lines of code in myaddmodule (the module youâre testing) are executed, and display the results when you call report().
Letâs revisit the program you wrote earlier to incorporate your new knowlege of checkexpect and coverage.
If all of your tests pass, check_expect wonât print anything to the shell. Add a test you know will fail to see what happens when one of your tests fail. coverage will print out a report of how many lines of code were exercised during the testing procedure. It will also show you which lines did not get exercised. You can use this information to write additional tests and make sure all code paths are exercised. Note: coverage will never fully 100% exercise your code, because it will always skip the lines that contain your tests. Whoa â meta, man.
Python supports object-oriented programming as you learned in CS15 with Java. To do so, you declare a class with properties (instance variables) and capabilities (methods) as follows:
Introduction to Python
class Student: """The student class models a student with a name, ID number, a graduation year, and a concentration. """
def init(self, name, idNumber, graduationYear, concentration): self._name = name self._idNumber = idNumber self._graduationYear = graduationYear self._concentration = concentration
def setConcentration(self, concentration): self._concentration = concentration
def printStudentInfo(self): print "Student named " + self._name + " has ID number " + str(self._idNumber) + ", is graduating in " + str(self._graduationYear) + " and is studying " + self._concentration + "."
To actually create an instance of this class, and call methods on it, we do the following:
if name == "main": stephen = Student("Stephen", 1002354, 2012, "Mathematics") stephen.setConcentration("Computer Science") #sophomore year stephen.printStudentInfo()
Create a file called student.py and test this out for yourself. What does this example show us?
Introduction to Python
Python on your own computer, you can get Python 2.6, but pelase make sure your programs run as expected on the department machines. Python versions from 2.4 to 2.6 tend to be compatible with one anothter. Please do NOT use Python 3 because Python 3 is not compatible with Python 2.5.
For reasons explained here: http://pyfaq.infogami.com/tutor-what-is-if-name-main-for you should always put all code you wish to execute directly (i.e. code not part of a specific class or function definition) under a big if statement. The Python syntax for the condition is: if name == "__main". Hereâs an example:
def function():
if name == "__main":
All your Python handins are required to follow this convetion. We will deduct points from your grade if your code does not include this, so donât forget!
We require you to follow the CS16 coding conventions for Python assignments throughout the semester. We expect you to read and follow it. You can find the coding conventions here: http://cs.brown.edu/courses/cs016/Info/PythonStandards.pdf
This introduction to Python only scratches the surface of what Python is and what it can do. You can find the official tutorial here: http://docs.python.org/release/2.5.2/tut/tut.html. The sections that will be most useful for CS16 are: 1, 3, 4.1-4.6, 4.7.6, 5, 6, 7.1, 8.1-8.5 and 9.3.
Python supports the ability to define one-line miniature functions on the fly. A traditional function definition looks like this:
def f(x): return x*
f(3) # evaluates to 6
Introduction to Python
Hereâs lambda function that accomplishes the same thing:
g = lambda x: x* g(3) # evaluates to 6
Note the abbreviated syntax. There are no parentheses around the parameter list. Thereâs also no return statement. The return keyword is implied, since the entire function can only be one expression. The function itself has no name. Thatâs why lambda functions are sometimes called anonymous functions. We can call the function through the variable it has been assigned to (in this case, g). Hereâs one more example:
(lambda x: x*2)(3) # evaluates to 6
In this example, we use the function without even assigning it to a variable. When you call check_expect and provide the first argument as a lambda, it defers the evaluation of the function. That is, you wrap up the function name and parameters in a variable, and give us that variable. We can then call the function in our support code at a later point in time.