Introduction To Python - 2018
Introduction To Python - 2018
Introduction To Python - 2018
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...
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.
3 Day 1
Your journey through Python begins today...
4.1 Setting up
Run cs0160 install pythonIntro from the command line. This will install a folder
pythonIntro in your cs0160 directory. It should contain two files primePrinter.py and
sectionOne.py.
Before we begin programming, we need to configure the editor you will use to write
your Python code. While you are free to use any editor of your choice, we recommend
you use Atom. If you are working from a computer in the Sunlab or MSlab, complete
Section 4.2, which will tell you how to configure Atom universally for Python code, and
skip over Section 4.3. If you have Atom locally on your personal computer, you can follow
the same instructions to configure it, although some of the instructions may be a little
different depending on how you work locally. If you are working remotely, jump right to
section 4.3 to learn how to set up Gedit, which performs better over SSH. Either way, be
sure to begin again at Section 4.4, where you will write your first Python program!
2. Change the Tab Length to be 4 and make sure the Tab Type is set to soft.
3. Close this tab and you’re ready to go!
Type gedit & into a terminal and press Enter to open Gedit.
First we will make the .py file you will write your program in.
1. Save the current (blank) new file: File > Save as...
2. Name the file helloWorld.py. The .py is very important!! Make sure the file is saved
in your ~/course/cs0160/pythonIntro directory.
Next, we have to configure Gedit to work well with Python.
1. Go to Edit->Preferences
2. Click on the Editor tab
3. Ensure that Tab width is set to 4
4. Check the box that says Insert spaces instead of tabs
Close out of the preferences window. You’re all set!
#! /usr/bin/python
at the top of your helloWorld.py file. This tells your machine to use Python to interpret
the file when executed. Then save the file, go back to your terminal, and type chmod +x
helloWorld.py to make the file an executable. (If you haven’t used chmod before, it’s a
terminal command used to change file permissions, in this case to make your Python file
executable. The +x argument adds executability for the owner of the file, you!) Now if
you type ./helloWorld.py into your terminal your program prints Hello world! to the
terminal. From now on, all of your Python files should start with #! /usr/bin/python.
5 Python Syntax
Let’s say that instead of wanting to write a program that just prints “Hello world!” and
then ends, you wanted to write a program with a function that takes in a string with your
name as the parameter, and prints “Hello <name>!” Following the CS16 Python coding
conventions, the function would look like this:
def say_hello(name):
"""say_hello: string -> nothing
Purpose: prints a greeting of the form "Hello <name>!"
Example: say_hello("Seny") -> "Hello Seny!"
"""
print "Hello " + name + "!" #this is the function body
When you define a function in Python, you simply write def (which is short for define),
followed by the name of the function, with all words lowercase and separated by underscores,
then the parameters in parentheses, and lastly a colon. Note that you do not need to
specify the type of your parameters in Python! Next, document your function with a block
comment! Use triple quotes (""" to create block comments much like /* would in Java. For
an in-line comment, use #, instead of the // from Java. This block comment should include
a description of the parameters and return type, the purpose of the method, and an example
of the method in use. This type of block comment is called a docstring and is crucial
to writing readable code that is easy to understand later. There is a detailed handout on
coding conventions on the course website that you can read for more information on writing
good Python.
The actual body of this function is simple. First off, it is indented four spaces from
the function declaration. This is crucial. If you do not indent your code correctly, it will
not work. Whitespace indentation is used in Python to nest blocks of code, rather than
curly braces. Each subordinating code block must be indented four spaces relative to the
code on which it depends. As you get used to programming in Python, this will become
second nature. The code here prints the concatenated string of "Hello" + str + "!"
to the shell. Note that the print statement doesn’t require that you enclose the string in
if __name__ == "__main__":
say_hello("Seny") #substitute your name
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 Seny.
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:
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 from 1 to n
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 -> 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:
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 one of the reasons Python is so 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 under-
stand this a bit better by just running python from your terminal (just type ‘python’ into
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
+ 1). When you’re finished trying things out in the interactive shell, type exit() to quit,
or use ctrl+D.
There is a lot more to Python syntax, but these are some basics to get you started.
Here is a super nifty Java to Python conversion table, which will be a boon to you in the
coming weeks:
6 Testing
In future Python assignments, we’ll be expecting you to write thorough test cases to exercise
your code and ensure it is correct. Testing is a very important part of software engineering.
When new features are added to a software package, or when code is refactored to improve
design/readability, developers need a way to make sure none of the old functionality breaks.
Tests will allow you to make sure your functions do precisely what they say they do. They
can also help in debugging — if you know from your tests which functions are working, you
won’t waste time looking for bugs in the wrong place. Let’s take a look at assert.
if __name__ == "__main__":
assert add(2, 3) == 5, "Arithmetic failure"
assert will check that both sides of the equality are equal. If the evaluation of the first ar-
gument does not equal the second argument, an AssertionError exception will be thrown,
printing the (optional) message. More generally, if the statement following assert eval-
uates to False, then the exception will be thrown and print out the (optional) message.
We will be putting a lot of emphasis on testing throughout this course, in homeworks and
projects. Testing should not be considered an additional aspect of a problem or project,
but rather a core part of it. Given this, we want you to write your tests before you write
your code. This practice is known as Test-Driven Development (TDD for short). We’ll be
walking you through the steps of TDD that will help you write code for is prime.
def is_prime(n):
"""is_prime: int → boolean
Purpose: Test whether the given number is prime or not
Example: is_prime(3) -> True
"""
3. Use the method signature and your examples to write test cases. You should write
another function called test is prime in the file and add in all of your test cases in
that function. For example:
assert is_prime(5) == True, "Test failed: 5 is prime"
Add in your other examples as assertions.
4. Implement the method is prime now! (more hints in the next section)
5. Run your test cases by calling test is prime in the main call and then executing
the Python file.
To test get today, print the result of the get_today method. If your code returns
today’s date, you’ve probably implemented it correctly. Also try testing your is_prime at
least on all the days of any month. Suggestion: write a for loop to loop through all of
those numbers and print out whether they are prime.
or
Methods
You need to implement the following methods in the primePrinter.py file that was in-
stalled earlier.
• is_prime: This method must take one non-negative integer argument and return a
boolean stating whether that number is a prime or not. (This method should work
for all non-negative integers, not just those between 1 and 31.) To test whether a
number is prime, simply check whether it has any divisors. Hint: Remember the
mod operator (%) from Java? It works the same in Python. This method should also
raise an exception if invalid input is given (see “Raising Exceptions” below for more
details).
• get_today: This method takes no arguments and it returns an integer in the range
1-31 representing the day of the month. This should not be a hard-coded value (if you
invoke the same method tomorrow, it should return tomorrow’s day-of-the-month!).
• is_today_prime: This method takes no arguments and prints out a sentence that
says the day of the month and whether or not it is prime, just like in the example
above.
Raising Exceptions
When you get to the next Python problem to be done in sectionOne.py, you’ll see that
there is some code at the beginning of the function body of factorial that looks like this:
if n < 0:
raise InvalidInputException("input must be greater than or equal to 0")
This is called raising (or throwing) an exception. You may be familiar with some excep-
tions (e.g. the dreaded NullPointerException or ArrayIndexOutOfBoundsException)
from your work in CS15 last semester. Exceptions are used to detect various errors during
program execution. Now, you will learn how to raise your own exceptions! Woohoo!!
Open sectionOne.py and examine the code above. When computing the factorial of a
number, that number must be an integer greater than or equal to 0. But what if the user
of your program doesn’t know that, and they try to run factorial(-3)? The above if
statement will be entered, and an InvalidInputException will be raised. If this if state-
ment was not present in the code, there would be some pretty big issues, as your base case
would never be reached, and the method would infinitely recur.
As you write your is prime method, your job is to ensure that the input given is valid
before continuing on with your program. What sort of input is your is prime method
expecting to receive? Using an if statement with a similar structure to the one above,
check for valid input, and if the input is invalid, raise an InvalidInputException that
prints out an informative message regarding why the exception was raised. You don’t have
to worry about writing your own InvalidInputException class, and, for now, don’t worry
about determining whether a number is an integer or decimal.
Hints
• You’ll notice at the top of the file there’s a line that reads:
from datetime import date.
This imports the datetime module, which has already been written by someone else.
Modules in Python are similar to libraries you used in Java (e.g. javaFX). But it
doesn’t import the entire module, just the date component, which you can read about
more here: http://docs.python.org/library/datetime.html#date-objects. Us-
ing the date object should help you implement get_today.
• If you want to print out an integer value concatenated with a string, you can use
the built-in Python function str(). str(myInt) will convert the integer value to a
string.
• If you want to concatenate two strings together, you can simply use the + operator.
before it, and the first and second numbers of the series are both one.
Once you complete this assignment, create a second method which recursively calculates
and returns n! where n is the input value. Make sure to follow the testing design recipe for
this problem.
Methods
You need to implement the following methods in the sectionOne.py file that was installed
earlier.
• fibonacci: This method takes no arguments and returns nothing. It prints out the
first one hundred Fibonacci numbers, with one number per line.
• factorial: This method takes a non-negative integer n as an argument and it returns
the n!. This method should be implemented in a recursive fashion. Remember that
0! is 1!
Raising Exceptions
You may notice that there is already some code written in the definition for factorial.
This was explained in the previous section of the lab.
9 Handing In
You’re done with day one of the Python intro! Feel proud, for you are now a snake-
charmer...kind of. Hand in primePrinter.py and sectionOne.py by running cs0160 handin
pythonIntro. Be sure your code is well-tested and commented!
10 Day 2
While you may have charmed many a snake already, future perils await on Day 2 of the
Python Intro!
10.1 Setting up
Run cs0160 install pythonIntro2 from the command line. This will deposit the stencil
files in a pythonIntro2 directory within your cs0160 directory. This should contain files
demo.txt, pieCount.txt and pieCounter.py.
11 Python lists
Python lists will be used frequently in CS16. Lists are Python’s version of Java arrays. You
can create them as follows (try them out in the interactive interpreter using the python
command):
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:
>>> erfectSquares = []
>>> for i in range(1, 11):
... perfectSquares.append(i*i)
#append adds the specified parameter to the end of the list
If you need to instantiate a list of a certain length (i.e. you want to use it as an array), the
following syntax will be very helpful:
“But what if I need a multi-dimensional list/array?” you ask. Great question! Python
handles this data structure as a list of lists:
This may seem strange at first, but as long as you remember “lists within lists,” you’ll be
fine. You can read about addition Python data structures, (like dictionaries!) at:
http://docs.python.org/tutorial/datastructures.html
class Student:
"""The student class models a student with a name, ID number,
a graduation year, and a concentration.
"""
# Other accessors/mutators...
def print_student_info(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__" :
dara = Student("Dara", 1002354, "Physics", 2018)
dara.set_concentration("Computer Science")
dara.print_student_info()
Create a file called student.py and test this out for yourself. What does this example
show us?
1. The constructor for a class is defined using a special method named __init__, which
can take any number of parameters. To create an instance of the class, we call the
constructor and pass in the appropriate parameters. Note we do not use a “new”
operator like we did in Java.
2. The instance variables belonging to a class do not need to be explicitly defined at the
top of the file like they do in Java. Like local variables, we don’t need to specify their
types, and they spring into existence when they’re first assigned a value. If we try to
use a variable that has not yet been given a value, we’ll get an AttributeError that
looks like this: AttributeError: Student instance has no attribute ‘_idNumber’.
Try this for yourself by eliminating the assignment, self._idNumber = idNumber
from the constructor, and re-running the program. When we re-run the program, the
print_student_info() method attempts to print out _idNumber, but _idNumber
has not been created because it has never been given a value. (This is kind of like a
Java null pointer in that initializing your variables is important).
4. The methods belonging to a class should take in self as their first parameter. When
you call dara.print_student_info(), it calls the print student info method of
the Student class, and passes in dara as the first parameter. So when you define the
method, it must take in a reference to the object it’s modifying, and when you call the
method, you don’t supply that first parameter. For this reason, method definitions
will always have one more formal parameter (in the method definition) than actual
parameters (when we invoke the method).
This tells Python to set the default value of graduationYear to 2018 if no parameter
is supplied. Often you have a function that uses lots of default values, but you rarely want
to override the defaults. Default argument values provide an easy way to do this, without
having to define lots of functions for the rare exceptions. Also, Python does not support
overloaded methods/functions and default arguments are an easy way of ”faking” the over-
loading behavior. (Note: once you use a default parameter, all subsequent parameters must
have default values as well.)
12.1 Inheritance
The syntax for subclassing is as follows:
class SubclassName(SuperclassName):
The class SuperclassName must have already been defined. Inheritance works approx-
imately the same as it does in Java. One major difference is the way to call methods of
your parent class. Instead of using super.methodName(arguments), just call
SuperclassName.methodName(self, arguments).
13 File I/O
13.1 Reading a .txt file
File I/O is very simple in Python, and is one of the tools we’ll expect you to become familiar
with this semester. You can manipulate files from JPEGS to spreadsheets, but we’ll start
off working with a simple text file. Open up the demo.txt file, to see what you’ll be working
with. Now, open up Python in your terminal, and try out the following commands:
The \n character is called a “newline” and represents a carriage return in a file. We use
the strip() method to remove unneeded whitespace from our strings. Always make sure
to close the files you open to avoid eating up system resources.
The file pieCounter.py in your stencil folder is an almost empty .py file that you’ll fill up
with code! YAY!
14.2 Testing
As usual, we expect you to use asserts to test your functions. Refer to the Student class
for help on the syntax to call class methods. Write method signatures for methods you
might need for the class you are about to write and follow the testing design recipe from
day 1 to write test cases. Read the hints section that follows for ideas on how to factor
code into test-able methods.
Do not yet worry about testing for invalid file names given to the open() method. You
will learn how to test exceptions on a future homework. We do expect that you will test
the functionality of the string parsing you do on the contents of the file.
14.3 Hints!
1. Characters of text files are strings in Python! To cast a string to an integer, use the
int() function. int(‘5’) returns 5.
2. Opening and closing files is expensive! Do you want to open and close the file ev-
ery time a user calls count pies? Or should you read in the file’s contents in the
constructor and never have to open the file again?
3. If you don’t need a counter when iterating through a list, you shouldn’t use range.
Use the following syntax instead:
4. You can get all the lines from a file in one list by calling myfile.readlines().
5. split is a super cool method of Python strings! Here’s an example use: "Samuel -
L. - Jackson - loves - pretzels!!!".split(‘-’) returns ["Samuel ", " L. ",
" Jackson ", " loves ", " pretzels!!!"]. That is: given some delimiter as a
parameter, it breaks a string up into chunks, separated in the original by that delim-
iter.
6. Consider how you might want to factor your code in order to make it easier to write
tests. As an example, consider the task of creating a list of the colours of the rainbow,
reversing it and testing the order of the reversed list.
def create_rainbow():
rainbow = ["violet","indigo","blue","green","yellow","orange","red"]
return rainbow
def reverse_rainbow(colours):
reversed_rainbow = []
for i in range(len(colours),-1,-1):
reversed_rainbow.append(colours[i])
return reversed_rainbow
if __name__ == "__main__":
"""If you were only wanting to test that
your reverse method will work with any
given list, you can do that because it is
factored out from the actual creation of
the rainbow
"""
test_list = [1,2,3,4,5]
reversed_list = reverse_rainbow(test_list)
assert reversed_list[0] == 5
assert reversed_list[4] == 1
Think about how this example relates to the pie counting problem and how you might
want to deal with the list you get from reading in the pieCount file and make sure
you are testing it properly using asserts
14.4 Handing in
To hand in your code for this lab run cs016 handin pythonIntro2 from your pythonIntro2
directory.
def function():
# Function definition goes here.
if __name__ == "__main__":
# Code to be executed when you run this program
All your Python handins are required to follow this convention. We will deduct points
from your grade if your code does not include this, so don’t forget!
15.4 Lambdas
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*2
f(3) # evaluates to 6
g = lambda x: x*2
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:
In this example, we use the function without even assigning it to a variable. We will learn
more about these lambda expressions in our unit on functional programming!