Lab 01
Lab 01
Lab 01
Tools/Software Requirement
Python
Lab Task
Python Basics
Required Files
You can download all of the files associated with the Python mini-tutorial as a zip archive:
python_basics.zip.
Table of Contents
We encourage you to type all python shown in the tutorial onto your own machine. Make sure it
responds the same way.
You may find the Troubleshooting section helpful if you run into problems. It contains a list of
the frequent problems previous students have encountered when following this tutorial.
Python can be run in one of two modes. It can either be used interactively, via an interpreter, or it
can be called from the command line to execute a script. We will first use the Python interpreter
interactively.
Operators
The Python interpreter can be used to evaluate expressions, for example simple arithmetic
expressions. If you enter such expressions at the prompt (>>>) they will be evaluated and the
result will be returned on the next line.
>>> 1 + 1
2
>>> 2 * 3
6
Boolean operators also exist in Python to manipulate the primitive True and False values.
>>> 1==0
False
>>> not (1==0)
True
>>> (2==2) and (2==3)
False
Strings
Like Java, Python has a built in string type. The + operator is overloaded to do string
concatenation on string values.
There are many built-in methods which allow you to manipulate strings.
>>> 'machine'.upper()
'MACHINE'
>>> 'HELP'.lower()
'help'
>>> len('Help')
4
Notice that we can use either single quotes ' ' or double quotes " " to surround string. This
allows for easy nesting of strings.
In Python, you do not have declare variables before you assign to them.
Learn about the methods Python provides for strings. To see what methods Python provides for a
datatype, use the dir and help commands:
>>> s = 'abc'
>>> dir(s)
['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
>>> help(s.find)
find(...)
S.find(sub [,start [,end]]) -> int
Return -1 on failure.
>> s.find('b')
1
Try out some of the string functions listed in dir (ignore those with underscores '_' around the
method name).
Python comes equipped with some useful built-in data structures, broadly similar to Java's
collections package.
Lists
Python also allows negative-indexing from the back of the list. For instance, fruits[-1] will
access the last element 'banana':
>>> fruits[-2]
'pear'
>>> fruits.pop()
'banana'
>>> fruits
['apple', 'orange', 'pear']
>>> fruits.append('grapefruit')
>>> fruits
['apple', 'orange', 'pear', 'grapefruit']
>>> fruits[-1] = 'pineapple'
>>> fruits
['apple', 'orange', 'pear', 'pineapple']
We can also index multiple adjacent elements using the slice operator. For instance,
fruits[1:3], returns a list containing the elements at position 1 and 2. In general
fruits[start:stop] will get the elements in start, start+1, ..., stop-1. We can also do
fruits[start:] which returns all elements starting from the start index. Also fruits[:end]
will return all elements before the element at position end:
>>> fruits[0:2]
['apple', 'orange']
>>> fruits[:3]
['apple', 'orange', 'pear']
>>> fruits[2:]
['pear', 'pineapple']
>>> len(fruits)
4
The items stored in lists can be any Python data type. So for instance we can have lists of lists:
Exercise: Lists
Play with some of the list functions. You can find the methods you can call on an object via the
dir and get information about them via the help command:
>>> help(list.reverse)
Help on built-in function reverse:
reverse(...)
L.reverse() -- reverse *IN PLACE*
Note: Ignore functions with underscores "_" around the names; these are private helper methods.
Press 'q' to back out of a help screen.
Tuples
A data structure similar to the list is the tuple, which is like a list except that it is immutable once
it is created (i.e. you cannot change its content once created). Note that tuples are surrounded
with parentheses while lists have square brackets.
The attempt to modify an immutable structure raised an exception. Exceptions indicate errors:
index out of bounds errors, type errors, and so on will all report exceptions in this way.
A set is another data structure that serves as an unordered list with no duplicate items. Below, we
show how to create a set, add things to the set, test if an item is in the set, and perform common
set operations (difference, intersection, union):
Note that the objects in the set are unordered; you cannot assume that their traversal or
print order will be the same across machines!
Dictionaries
The last built-in data structure is the dictionary which stores a map from one type of object (the
key) to another (the value). The key must be an immutable type (string, number, or tuple). The
value can be any Python data type.
Note: In the example below, the printed order of the keys returned by Python could be different
than shown below. The reason is that unlike lists which have a fixed ordering, a dictionary is
simply a hash table for which there is no fixed ordering of the keys (like HashMaps in Java). The
order of the keys depends on how exactly the hashing algorithm maps keys to buckets, and will
usually seem arbitrary. Your code should not rely on key ordering, and you should not be
surprised if even a small modification to how your code uses a dictionary results in a new key
ordering.
Exercise: Dictionaries
Use dir and help to learn about the functions you can call on dictionaries.
Writing Scripts
Now that you've got a handle on using Python interactively, let's write a simple Python script that
demonstrates Python's for loop. Open the file called foreach.py and update it with the
following code:
At the command line, use the following command in the directory containing foreach.py:
Remember that the print statements listing the costs may be in a different order on your screen
than in this tutorial; that's due to the fact that we're looping over dictionary keys, which are
unordered. To learn more about control structures (e.g., if and else) in Python, check out the
official Python tutorial section on this topic.
If you like functional programming you might also like map and filter:
nums = [1,2,3,4,5,6]
plusOneNums = [x+1 for x in nums]
oddNums = [x for x in nums if x % 2 == 1]
print oddNums
oddNumsPlusOne = [x+1 for x in nums if x % 2 ==1]
print oddNumsPlusOne
Write a list comprehension which, from a list, generates a lowercased version of each string that
has length greater than five. You can find the solution in listcomp2.py.
Beware of Indentation!
Unlike many other languages, Python uses the indentation in the source code for interpretation.
So for instance, for the following script:
if 0 == 1:
print 'We are in a world of arithmetic pain'
print 'Thank you for playing'
if 0 == 1:
print 'We are in a world of arithmetic pain'
print 'Thank you for playing'
there would be no output. The moral of the story: be careful how you indent! It's best to use four
spaces for indentation -- that's what the course code uses.
Tabs vs Spaces
Because Python uses indentation for code evaluation, it needs to keep track of the level of
indentation across code blocks. This means that if your Python file switches from using tabs as
indentation to spaces as indentation, the Python interpreter will not be able to resolve the
ambiguity of the indentation level and throw an exception. Even though the code can be lined up
visually in your text editor, Python "sees" a change in indentation and most likely will throw an
exception (or rarely, produce unexpected behavior).
This most commonly happens when opening up a Python file that uses an indentation scheme
that is opposite from what your text editor uses (aka, your text editor uses spaces and the file
uses tabs). When you write new lines in a code block, there will be a mix of tabs and spaces,
even though the whitespace is aligned. For a longer discussion on tabs vs spaces, see this
discussion on StackOverflow.
Writing Functions
# Main Function
if __name__ == '__main__':
buyFruit('apples',2.4)
buyFruit('coconuts',2)
Object Basics
Although this isn't a class in object-oriented programming, you'll have to use some objects in the
programming projects, and so it's worth covering the basics of objects in Python. An object
encapsulates data and provides functions for interacting with that data.
Defining Classes
class FruitShop:
def getName(self):
return self.name
The FruitShop class has some data, the name of the shop and the prices per pound of some fruit,
and it provides functions, or methods, on this data. What advantage is there to wrapping this data
in a class?
Using Objects
So how do we make an object and use it? Make sure you have the FruitShop implementation in
shop.py. We then import the code from this file (making it accessible to other scripts) using
import shop, since shop.py is the name of the file. Then, we can create FruitShop objects as
follows:
import shop
So what just happended? The import shop statement told Python to load all of the functions and
classes in shop.py. The line berkeleyShop = shop.FruitShop(shopName, fruitPrices)
constructs an instance of the FruitShop class defined in shop.py, by calling the __init__
function in that class. Note that we only passed two arguments in, while __init__ seems to take
three arguments: (self, name, fruitPrices). The reason for this is that all methods in a class
have self as the first argument. The self variable's value is automatically set to the object
itself; when calling a method, you only supply the remaining arguments. The self variable
contains all the data (name and fruitPrices) for the current specific instance (similar to this in
Java). The print statements use the substitution operator (described in the Python docs if you're
curious).
The following example illustrates how to use static and instance variables in Python.
class Person:
population = 0
def __init__(self, myAge):
self.age = myAge
Person.population += 1
def get_population(self):
return Person.population
def get_age(self):
return self.age
In the code above, age is an instance variable and population is a static variable. population is
shared by all instances of the Person class whereas each instance has its own age variable.
This tutorial has briefly touched on some major aspects of Python that will be relevant to the
course. Here are some more useful tidbits:
Use range to generate a sequence of integers, useful for generating traditional indexed for
loops:
for index in range(3):
print lst[index]
After importing a file, if you edit a source file, the changes will not be immediately propagated in
the interpreter. For this, use the reload command:
>>> reload(shop)
Troubleshooting
These are some problems (and their solutions) that new Python learners commonly encounter.
Problem:
ImportError: No module named py
Solution:
When using import, do not include the ".py" from the filename.
For example, you should say: import shop
NOT: import shop.py
Problem:
NameError: name 'MY VARIABLE' is not defined
Even after importing you may see this.
Problem:
TypeError: 'dict' object is not callable
Solution:
Dictionary looks up are done using square brackets: [ and ]. NOT parenthesis: ( and ).
Problem:
ValueError: too many values to unpack
Solution:
Make sure the number of variables you are assigning in a for loop matches the number
of elements in each item of the list. Similarly for working with tuples.
For example, if pair is a tuple of two elements (e.g. pair =('apple', 2.0)) then the
following code would cause the "too many values to unpack error":
(a,b,c) = pair
Problem:
AttributeError: 'list' object has no attribute 'length' (or something similar)
Solution:
Finding length of lists is done using len(NAME OF LIST).
Problem:
Changes to a file are not taking effect.
Solution:
1. Make sure you are saving all your files after any changes.
More References
Autograding
To get you familiarized with the autograder, we will ask you to code, test, and submit solutions
for three questions.
You can download all of the files associated the autograder tutorial as a zip archive: tutorial.zip
(note this is different from the zip file used in Python mini-tutorials, python_basics.zip). Unzip
this file and examine its contents:
The command python autograder.py grades your solution to all three problems. If we run it
before editing any files we get a page or two of output:
Question q1
===========
*** FAIL: test_cases/q1/addition1.test
*** add(a,b) must return the sum of a and b
*** student result: "0"
*** correct result: "2"
*** FAIL: test_cases/q1/addition2.test
*** add(a,b) must return the sum of a and b
*** student result: "0"
*** correct result: "5"
*** FAIL: test_cases/q1/addition3.test
*** add(a,b) must return the sum of a and b
*** student result: "0"
*** correct result: "7.9"
*** Tests failed.
Question q2
===========
*** FAIL: test_cases/q2/food_price1.test
*** buyLotsOfFruit must compute the correct cost of the order
*** student result: "0.0"
*** correct result: "12.25"
*** FAIL: test_cases/q2/food_price2.test
*** buyLotsOfFruit must compute the correct cost of the order
*** student result: "0.0"
*** correct result: "14.75"
*** FAIL: test_cases/q2/food_price3.test
*** buyLotsOfFruit must compute the correct cost of the order
*** student result: "0.0"
*** correct result: "6.4375"
*** Tests failed.
Question q3
Finished at 23:39:51
Provisional grades
==================
Question q1: 0/1
Question q2: 0/1
Question q3: 0/1
------------------
Total: 0/3
Your grades are NOT yet registered. To register your grades, make sure
to follow your instructor's guidelines to receive credit on your project.
For each of the three questions, this shows the results of that question's tests, the questions grade,
and a final summary at the end. Because you haven't yet solved the questions, all the tests fail.
As you solve each question you may find some tests pass while other fail. When all tests pass for
a question, you get full marks.
Looking at the results for question 1, you can see that it has failed three tests with the error
message "add(a,b) must return the sum of a and b". The answer your code gives is always 0, but
the correct answer is different. We'll fix that in the next tab.
Question 1: Addition
The tests called this with a and b set to different values, but the code always returned zero.
Modify this definition to read:
Now rerun the autograder (omitting the results for questions 2 and 3):
Finished at 23:41:01
Provisional grades
==================
Question q1: 1/1
Question q2: 0/1
Question q3: 0/1
------------------
Total: 1/3
You now pass all tests, getting full marks for question 1. Notice the new lines "Passed a=..."
which appear before "*** PASS: ...". These are produced by the print statement in add. You can
use print statements like that to output information useful for debugging. You can also run the
autograder with the option --mute to temporarily hide such lines, as follows:
Question q1
===========
*** PASS: test_cases/q1/addition1.test
*** add(a,b) returns the sum of a and b
*** PASS: test_cases/q1/addition2.test
*** add(a,b) returns the sum of a and b
*** PASS: test_cases/q1/addition3.test
*** add(a,b) returns the sum of a and b
Run python autograder.py until question 2 passes all tests and you get full marks. Each test
will confirm that buyLotsOfFruit(orderList) returns the correct answer given various
possible inputs. For example, test_cases/q2/food_price1.test tests whether:
Run python autograder.py until question 3 passes all tests and you get full marks. Each test
will confirm that shopSmart(orders,shops) returns the correct answer given various possible
inputs. For example, with the following variable definitions:
Task1
Write a program to remove a specific character from a string using Python. Your code should be
able to take string and index (index of the character to be removed) as input, and display the
output string with removed characters from mentioned index.
Task2
Write a program in Python to calculate the time elapsed to execute the code. You may calculate
the elapsed time of any of the task you have performed in this lab. But please specify the full
piece of code in your lab report.
Deliverables and guidelines: Submit the code and screenshots of output in the form of a report.
Do not paste your solutions in the lab manual’s document, do make a lab report from a blank document, also
please don’t submit a zip folder etc.