Lab 3 Getting Started with Python

vetinnocentSoftware and s/w Development

Nov 7, 2013 (3 years and 9 months ago)

70 views

CPSC 301: Lab
3

1

Version:
7
-
Nov
-
13

CPSC 301:
Computing in the Life Scien
ces

Term 2, Winter 2011

2012


Lab 3

Getting Started

with Python

Due : Wednesday,
Feb 1
, 6:00pm

MARK:

/ 30


1.

Objectives

After this lab you will be able to:



Write basic programs in Python



Read code other people have written to evaluate its purpose



Understand the idea behind ciphers and encryption



Use the built in
help() function



Use functions other people have written



Write a small program from scratch


2.

[ / 5
]
Python

We will now translate your dancing cat
you did in L
ab 1 in a scripting language called Python.
Python is a powerful language that allows for more fine
-
grained control of your programs.
Unfortunately, adding a graphical element is beyond the scope of this lab, so we will use text
printouts instead. If you w
ould like to work on Python at home, you can download and install
Python
on your machine. The Python version we have installed in the lab is Enthought Python
Submitting
Student

Name


Number


Account


Email


Partner

Name


Number


Account


Approximate
time
to finish

Before Lab


In Lab


After Lab


CPSC 301: Lab
3

2

Version:
7
-
Nov
-
13

Distribution
EDP 7
.
1
-
2. We have chosen this distribution because it comes with a number of
librar
ies we plan to use in the course. To download this distribution
(actually version
7
.
2
-
1
)
you can visit

http://www.enthought.com/products/getepd.php

,
click the ACADEMIC button at
the end of t
he page , choose the operation system
, fill in the information and click Download.

For most of the work you will do in this course
you

will ru
n Python through an Integrated
Development Environment (IDE) which is called Wing IDE 101. This IDE is designed specifically
for use in teaching introductory programming classes. The IDE makes it easier to create Python
programs run them and see the resul
ts. If you like to use this IDE at home, you can download it
by visiting the Wingware site:
http://www.wingware.com/downloads/wingide
-
101

and

choosing the
link that corresponds to your operat
ion system.


Enthought
Python
and Wing IDE 101 are
already installed on the lab computers, so you do not
have to do this step during your lab.

1.

Start
Wing IDE 101
. From the lab computers, click Start


Wing IDE 101
. You should see
a new window called “
Wing
IDE
” open.

2.

T
he Wing IDE window is divided into three areas: The large
E
ditor area at the top, a
Search/Stack Data area at the bottom
-
left

and the Python Shell at the bottom
-
right
.
Click


New

in

t
h
e
tool
-
bar at the
top of
the “
Wing IDE
” window

to

open the

text editor

and create a new program
. You can now type in the

Edit
o
r area.

This is where you will
write your code!

Note:

Shells


are simply programs that read commands and display the output of these
commands. The Python Shell can execute a variety of c
ommands, such as the
print

command we will soon be using. Python programs consist of a set of commands that are
executed in the shell quickly and in order.

3.

Type the following code in

the Editor area
:

print “Hello World!”

To
run your script
, click


Run

at the top of the Wind IDE window
. You should see “Hello
World!” print out in your “Python Shell”
area
. Congratulations! You’ve just written your
first Python program!

To s
ave your

program to a
file
click Save at the top of the Wing IDE window, find your
Z
drive and save the program
to
Z:
\
cs301
\
lab
3
\
hello
.py
. Make new folders if
you have to. Note that all python files should be saved with the “.py” extension.

CPSC 301: Lab
3

3

Version:
7
-
Nov
-
13

4.

Now let’s translate your dancing cat to Python. The code below will simulate your cat’s
initial m
ovements, minus the drums.
Close your hello world script

(by right
-
clicking at its
name at the top of the edit area and select the close

option from the drop
-
down menu
)
,
open a new
program
(repeat step 2),
copy and
paste the following code into your editor

and save it as
cat.py

(in the same directory as
hello.py
)
. Can you figure out what
each line does? Don’t worry if you can’t figure it out

every single line, you’ll learn more
later in the course!

import time # Don't worry about this line for now.

position

= 0

forever = True

while(forever):


position = position + 10


print
"The cat is now at position: ", position


time.sleep(0.5) # This waits for 0.5 seconds.


position = position
-

10


print "T
he cat is now at position: ", position


time.sleep(0.5) # This waits for 0.5 seconds.

As you may have noticed this program has an infinite loop, i.e. a sequence of sentences
that will run for ever. Wing IDE does not allow the users to run such loops as they may
keep going for ever if the user does not
manually stop them. Therefore you canno
t run
this program

using the
Run
button. Instead you can test the program using the
Start/Continue command from the
Debug button

(the one that looks like a bug)

in the
tool
-
bar at the top of the Wing IDE window. Test the program
and watch the output in
th
e Python Shell area.

Important note:

You can stop your infinite loop by pressing

the Stop button at the top
of the Wing IDE window. If for any reason you st
a
rted the program with the Run button
an
d

the program looks idle, you can reset
the Python shell

b
y clicking on the Option
button at the top
-
right corner of the shell panel and selecting Restart Shell
.

5.

Now change your Python code so that it matches your Scratch code
in Lab 1:

a.

Change the movement to 30 steps forwards and backwards,

b.

P
rint “Hello” after
moving forwards and “Goodbye” after moving backwards.


Show your TA

your dancing “cat”!
Hint: the indents in your code matter. The
indents

create blocks of code

like the blocks in Scratch and tell Python that the indented lines of
code belong under the
while(forever)

block.


You
will learn

more about Python

in the lectures.
A
nother

good source of information is the
official Python tutorials website, which can be found at
http://docs.python.org/tutorial/
.

You
can also find many great resources by simply searching for “Python tutorial” or “Python, getting
started” on Google.

CPSC 301: Lab
3

4

Version:
7
-
Nov
-
13

3.

[ / 5 ]
The Caesar Cipher

In this part of the lab we’re going to look at a very basic method of encryption using a cipher
called the

Caesar Cipher.

The purpose of a cipher is simply to take some input, and change it in a (reversible) way to
make it unintelligible; the idea is to protect the input from being read by anyone that does not
know how to undo the cipher.


This is not a new

idea at all,

it has

been around for thousands of years, but encryption is a very
important part of computing in a world where most of our information travels along public
networks (i.e. the Internet). A good cipher should be
extremely

difficult to break
without the
correct key, even if the cipher is known to everyone. This is how most encryption schemes for
data work; anyone can go and look at how the data is encoded, but without knowing the key,
a.k.a. password, the cipher is still impenetrable.

The Cae
sar Cipher is very straightforward: given some message and some integer
n
, for each
letter in the message, change it to the letter that is
n

places further in the alphabet (wrapping
around from z to a if you need to). For example, the word “candy” with
n

= 3 becomes “fdqgb”.

Similarly, if you have an encoded message and a key
n
, you can produce the original message by
replacing each letter in the encoded message with the letter that is
n

places back in the
alphabet (wrapping around from a to z if you need

to).

Implementing the Caesar Cipher in Python isn’t too terrible, but it requires some tricks that
haven’t been covered in this class, so for this lab we’re going to give you a function that
performs encoding and decoding using the Caesar Cipher

and you w
ill write a program that
uses this function
.

1.

Download the file caesar.py, and put it in your
lab
3

folder.

If you’d like, you can open
this file from
Wing IDE
(
click
Open

at the top of the window
, then navigate to the
correct folder) and take a look at
it. You
are not

expected to be able to understand all
of this code, but
it’s good to take a peek anyway
.


2.

G
o back to the “Python Shell”
area
. You’ll notice a flashing cursor next to “>>>
”. This is
the interactive shell where you can execute single commands. It’s very useful for testing
out one
-
line pieces of code, or just messing around with new ideas. Also, it’s where we
are going to be using one of the most important Python functions
: help().

At the prompt (that’s what the “>>>” is called), type
import
caesar
and hit enter.
This command has told Python to load the
caesar.py

file so that you can use the
function we’ve given you. To refer to a function within a loaded file in Python w
e use
CPSC 301: Lab
3

5

Version:
7
-
Nov
-
13

names of the form module.function, so in this case we use caesar.caesar, because both
the module (the file we loaded) and the function are called caesar.

3.

Now we need to figure out how to use this function. At the prompt type
help(caesar.caesar)

and
hit enter.

In the shell
,

you will get a help message that
tells you about and how to use the caesar.caesar function.


4.

T
ry the example
from the help output
in the shell. Just type in the command and hit
enter. The output should match the return given in t
he help output. Now modify the
command to decrypt “ifmmp” back to “hello”.


5.

Now, pick some message and encrypt that with an offset of your choice then use the
function in decrypt mode to undo the cipher. Make sure you get your message back!


Show your
TA
.


4.

[ / 10]
An Encoding Program


Once you’re familiar with the caesar.caesar function, it’s time to build it into a little
program. This program will prompt you to input a message and a key, and it will return the
encoded version of the message

or vice
-
versa
. The idea is to have the program keep asking
for messages until the user gives it a blank message, indicating that s/he wants to stop using
the program.

To save you some time, we’ve written part of the code for you.


1.

Download
encode_decode
.py
and p
ut it in your
lab3
directory.


2.

Open
encode_decode
.py

in Wing101 and look at the code

(not much) and the
commented lines. The commented lines tell you what you’ll need to do at each
step, and
they are in the correct order.


3.

Add the necessary code,
replace anything surrounded by *’s (i.e. the while loop
condition)
and test your program.
For making it go forever, look at the dancing cat
example again. For calling the caesar.caesar function, remember what you learned
in part 3.

CPSC 301: Lab
3

6

Version:
7
-
Nov
-
13


4.

Try messages/keys that

you know the answer to (i.e. the example from the help()
output). If these aren’t working out there are bugs in your code. Find them and
fix

them.


Once your

program is running properly, play with it a bit. You’ll quickly realize that this little
progr
am saves a lot of typing: you don’t have to type caesar.caesar(...) every time anymore,
you can just give it the message and a key. Pick a message, and try a couple different keys.
Make sure the encodings seem reasonable.

Now for something a little trick
y:
find
at least two

offset
s that produce

the same output
when encrypting your message (
Hint: Think about how it wraps around the end of the
alphabet
).

Write these two keys in the
s
pace below
.

Answer


Show your TA.


5.

[ / 10 ]
Write a
Simple
Program
(f
rom s
cratch
)


In
-
Lab or After
-
Lab
:
Write a program which will add any number of floating point numbers
which are provided by the user and prints their sum. The program should do the following:



initialize the

sum of the number to its initial value (which is the right initial value for
the sum?)



keep asking the user to provide the next number



read the number and add it to the sum of the numbers it has seen so far



if the number provided by the use is 0
, the pro
gram should stop and display the sum of
the numbers which have been entered by the user.


A typical run of your program may look like the following:

CPSC 301: Lab
3

7

Version:
7
-
Nov
-
13

Enter a number:
20

Enter a number:
-
30.5

Enter a number:
50.5

Enter a number:
0

The sum is: 40.0

Where the
items in blue are typed in by the user and the rest is provided by the program.

T
he
code in
encode_decode program of part 4 and the pint cost program we discussed in the
lectures
can give you

some ideas on how to write this program.

Save your program in
a file named
add_numbers.py

in the
lab3

directory. Test your
program with a variat
y

of positive and
negative numbers as well as with no numbers at all, that
is w
hen the first number entered by

the user is 0.

In that case the program should return 0.

If
you complete this part in the lab
,
show it to your TA.


6.

Submission Checklist


Only one person in each group will submit the lab using the handin tool.

The assignment name you should use with handin to submit this assignment is:



lab
3
_L2A

if you are in lab

section L2A,



lab
3
_L2B

if you are in lab section L2B, or



lab
3
_L2C

if you are in lab section L2C.

While you may submit multiple times using handin (before the deadline), only your last
submission will be graded. Therefore, you must submit all the relevant

files in a single zip
archive.
Make sure that none of the files is opened when you zip them up.
For this lab your
submission archive should include



A completed version of this lab document. Do not forget to fill in the table at the top.




Your file with the solution to part 2 of the lab:
cat.py



Your python program that uses the caesar function (solution for part 4) :
encode_decode
.py

CPSC 301: Lab
3

8

Version:
7
-
Nov
-
13



Your program that
adds the numbers provided by the user
(solution for part
5
) :
add_numbers
.py

Note that o
nly the person who submits the lab has to provide an email address, to which we
will send our feedback when we mark your lab. This person should forward our feedback to
her/his partner
.