Description
CSCI 141 Lab 2 Linux, Type Conversions, Operators and Operands, Print Formatting, Errors Solved
1 Logging into Linux
Linux is an operating system with much of the same functionality as the Windows or Mac
operating systems, but with a slightly different feel.
The lab computers are dual boot computers,
and when the computer boots up you can specify which of the operating systems (Windows or
Ubuntu, which is a flavor of Linux) you want to use.
To log into your CS Linux account, reboot your CS computer; when a menu appears, use the
arrow keys to select Ubuntu from the set of options, and press enter to select it. The login
window should look similar to what is shown in Figure 1.
You can click on the circular gnome
icon to the right of ”Login” to view a menu where you can customize the look and feel of your
Linux session.
For now, we’ll assume that you’ve left it on Ubuntu (Default). Provide your CS
account username and password (the same credentials as you used for your Windows account
in lab 1) to log in.
Once logged in, the overall look and feel of your desktop will vary depending on which environment you have selected. To access system settings for your desktop environment, click on
the power icon in the upper right hand corner and select System Settings… To find Thonny,
click the Ubuntu icon (the top-most icon in the bar on the left side of the screen.
If Thonny
doesn’t appear among the applications there, you can type Thonny in the search bar and it
should appear. Once Thonny starts, it should look very similar to the Windows version you
used in last week’s lab.
1
Figure 1: A typical linux Login prompt and desktop environment selector
2 Linux Command Line Basics
Windows, Mac OS, and Linux all provide graphical interfaces such as those you’re used to using,
that allow you to open programs and accomplish tasks using the mouse, icons, windows, and
so on. All of these operating systems also provide another way of interacting with them, called
a Command Line Interface (CLI).
Although there is a steeper learning curve for knowing how
to accomplish things using the command line, for certain tasks it can be more powerful once
you know how to use it.
In this lab, you will learn the very basic elements of how to interact with the Linux command
line and learn how to run Python code without the help of an IDE such as Thonny. What you
will learn here is only a tiny fraction of the commands available; you can find a helpful ”cheat
sheet” of many commonly used Linux commands on the course website1
i you want to learn
more.
1. Begin by opening a command line window (also called a Terminal). Click on the Ubuntu
icon in the upper left corner and type terminal to initiate a search; click on the Terminal
icon from the results to launch a new terminal window.
2. In the terminal, the $ sign and the space to the right of it where you type is called the
command line. Commands that you issue are interpreted by a program called a shell (the
default shell, or command line language, in the lab machines is bash). It is one of the
many shells available in Linux.
3. You’ll notice that the $ is prepended with your username and an @ followed by the name
of the computer that you are logged into. For example, wehrwes@linux-11:~$ specifies
the user wehrwes logged into the linux-11 machine.
4. All of the things that you can do with the mouse when interacting with a windows
environment you can also accomplish via the command line. In the following steps you
will create a new directory (folder), navigate into that folder, and run python from the
command line.
For these instructions, code and/or sample file content or output are
1Direct link: https://facultyweb.cs.wwu.edu/~wehrwes/courses/csci141_19s/labs/linuxref.pdf
2
shown in boxes. Type commands EXACTLY as they provided, and press return/enter to
issue the command. For example:
whoami
is instructing you to type the command whoami on the command line and execute it by
pressing return/enter. Try it out. What does the whoami command do?
5. Commands can take arguments, similarly to how functions in Python take arguments,
except here they are not surrounded by parentheses. To create a directory, use the mkdir
command with a single argument that is the name of the directory (folder) that you want
to make. Create the directory Lab2.
mkdir Lab2
6. To confirm that you have made your directory, issue the ls command, which will list all
contents of the directory where you are currently in.
ls
You should see a list with multiple items, which are the files and/or directories in your
account. If done correctly, Lab2 should be listed.
7. In graphical interface, you would double click on a folder to access that folder. In Linux,
you open a directory using the command cd, for change directory. Enter the Lab2 directory.
cd Lab2
8. Launch Thonny via the command line :
thonny &
The & is important: this allows you to continue using the terminal window AFTER you
launch Thonny. Use Thonny to create a new file, helloWorld.py, with a single print
statement : print(“hello world”).
Save the file in your Lab2 folder. Return to the
terminal, and again issue the ls command, and you should see the just-created file listed.
9. Just as you can run a Python program using Thonny by pressing the green Run button,
you can also run a program from the command line.
In the terminal window (make sure
you are in your Lab2 folder, which contains your Python program), run the helloWorld
program by invoking the python3 interpreter :
python3 helloWorld.py
You should see the output of your program printed to the terminal console line.
For this lab, you must invoke the helloWorld.py program from the command
line. To provide proof that you have done so, either upload a screenshot
showing that you invoked helloWorld from the command line (use the screenshot tool available on Linux), or show your TA how you execute the program
helloWorld from the command line so they can give you credit on Canvas for
those points right away.
For the remaining sections of this lab, you can run python either via Thonny or via the
command line.
3
3 Errors, comments, and the sep argument of print
Inevitably, you will write code that will have bugs, or errors, no matter how experienced of a
programmer you might be. Knowing how to find and fix bugs is a critical skill for all programmers.
Using a browser such as Firefox, go to the course website:
https://facultyweb.cs.wwu.edu/~wehrwes/courses/csci141_19s/#schedule)
download the file badCode.py, and save it in your Lab2 folder. The contents of that file are
shown in the following figure.
Open the file badCode.py in Thonny. Read over the code, paying particular attention to the
comments. Proper commenting is crucial to writing good code, so that it is easy to read by you
and others. In python all comments begin with the # character.
As a general rule:
• Include your name (the author) and a short description at the top of each .py file
• For every few lines of code, include a descriptive comment
• Use white space (blank lines) to chunk your code into logical sections
For all the labs and assignments in this course, commenting is a portion of the rubric. Get into
the habit now of commenting your code well!
Notice that this code contains a brand new way of using print. Adding sep=”” (short for
“separator”) as the last argument to the print function will prevent print from adding spaces
between items that you want printed.
If you use sep=””, the only spaces that are included in
the output are the spaces that you place explicitly into the Strings. For example:
print(“Taking”, “CSCI”, 141, “woo-hoo!”)
would print the following:
Taking CSCI 141 woo-hoo!
4
but
print(“Taking”, “CSCI”, 141, “woo-hoo!”, sep=””)
would print the following:
TakingCSCI141woo-hoo!
In general, the print function defaults to ” ” as the separator between the arguments it prints.
If you want a different separator, you can give any string to the sep argument, such as the empty
string (sep=””) or a comma (sep=”,”), or any other string you’d like (e.g., sep=”, uhh, “).
Try out a few calls to print with different separators in the interactive Shell pane in Thonny.
badCode.py has a single intentional error. Run the code to see the error (following Figure).
Look closely at the error message.
On what line number is the error? Fix the error. Hint: Refer
to the lecture slides for fixing an error that uses the conversion function int. Be sure that
you modify ONLY the line of code that says numReindeer = int(approxNumReindeer).
You may not modify any other line of code, nor add nor delete any line of code.
4 Additional errors
Download faultyCode.py from the course webpage and save it in your Lab2 folder. The contents
of that file are shown in Figure 2. Take a close look at the code. Notice again the good
commenting. The program faultyCode.py has intentional MULTIPLE errors.
Run the code
(either using Thonny or via the command line), and look closely at the error message.
Fix the errors in faultyCode.py. Go back and forth between fixing an error and trying to run
the program. Ultimately, the goal is that the output of the program is as shown in Figure 3.
5 Operands and Operators
In lecture we have discussed operands and operators. Make sure that you know the definition
of both. If you do not recall, review the lecture slides.
5
Figure 2: contents of faultyCode.py
Figure 3: Output of the corrected faultyCode.py program.
In this section, you’ll solve the following programming problem: The period key on your
keyboard is broken, but you would like to want to multiply two numbers with a
decimal digit.
Let’s look at an example. Suppose you want to calculate 20.4 × 17.7, but can only enter 204
and 177. The desired result is 361.08. If the user inputs the values 204 and 177, how can
you convert them to 20.4 and 17.7?
By using the modular and integer division operators! For
example, 204 modulus 10 has a remainder of 4, which gives the decimal value .4, while 204
integer division 10 gives 20, which is the number before the decimal in 20.4.
The Math: Suppose that for the input values 204 and 177 you have successfully extracted
the whole and decimal values (i.e., 20, 4, 17 and 7). How can you calculate the result of 20.4 x
17.7? Multiplication of decimal values requires you to sum the following four parts:
• The first integer times the second integer
• The first integer times the second decimal
• The first decimal times the second integer
• The first decimal times the second decimal
Notice that for each decimal, we also multiply in a factor of 0.1 to make sure that it is correctly
6
weighted in the final product. In our example, the calculation looks like this:
20.4 ∗ 17.7 = (20 ∗ 17)
+ (20 ∗ 7 ∗ 0.1)
+ (4 ∗ 0.1 ∗ 17)
+ (4 ∗ 0.1 ∗ 7 ∗ 0.1)
= 340 + 14 + 6.8 + 0.28
= 361.08
1. Download brokenCalculator.py from the course webpage and save it to your Lab2 folder.
2. That file is incomplete. Only two lines of code have been written, which you are not
allowed to edit. The rest are comments.
Lines of code that say # COMPLETE THE CODE
you will need to write. Read the comments for each section to get a sense of what code
you need to write. Also, the number of COMPLETE THE CODE comments in that file
is how many lines of python code I (Scott) wrote in my solution. It’s okay if your solution
uses fewer lines of code, or more, but each block of code should accomplish what the
comment above it specifies.
For the lines of code that you write, you are only allowed to use the print
function, the assignment operator, and the following mathematical operators:
• //
• %
• *
• +
For the lines of code that you write, you cannot use float(), nor int(), nor /.
3. There are 7 parts to the code, labeled A through G. Here are hints for each of them:
• A: This requires a single use of the print function
• B: Use only the // and % operators. Follow the logic in the description above
• C: This requires a single use of the print function
• D: Do the same for the second integer as you did for the first integer (step B). Use
only the // and %operators
• E: The same as step C, but for the second integer
• F: Use the Hint above for explanation on how to do this
• G: This requires a single use of the print function.
In your python code, you CAN make use of periods, but when the program is
RUN, the user CAN ONLY enter integer (non decimal) numbers.
7
A sample output for the completed code is shown in the following figure:
Submission
Either show your working code to your TA, who will post your lab grade scores right away, else
upload the following files:
• Screenshot (.png, or .jpg file) showing you invoking your helloWorld program from the
command line
• Your fixed faultyCode.py code file
• The completed brokenCalculator.py file that can reproduce the output shown in the above
figure
Rubric
Screenshot showing execution of helloWorld from the linux command line 5 points
faultyCode.py has been fixed, and is properly commented 3
brokenCalculator.py uses only %, //, + and ∗ operators for the lines of code
that you have written
3
brokenCalculator.py has no syntax errors 3
brokenCalculator.py produces the correct output 3
brokenCalculator.py is properly commented 3
Total 20 points
8
CSCI 141 Lab 3 Conditionals and Boolean Logic Solved
Introduction
This lab gives you practice with if statments (also sometimes called conditionals, or selection.
In the process,you’ll also get some more experience with Boolean operators. The idea is the
following: your goal is to write a program that recommends what clothing items to wear based
on the weather conditions indicated by a user.
If you have questions, be sure to ask the TA: your TA is there to help you! By now you’ve
seen how to use Thonny on both your Windows and Linux accounts. You are free to select
whichever operating system you want to use.
1 Setup
We recommend creating a new directory/folder called lab3 on your N drive (Windows) or in
your home directory (Linux). In your lab3 directory, create a new Python file clothingPicker.py.
2 Unary Selection
Unary selection is a fancy name for a simple if statement. You’ve seen these already in lecture:
the if statement allows you to execute a sequence of statements (or a code block) if a given
boolean expression evaluates to True, or skip over the code block if the expression evaluates
to False.
The code block inside an if statement must contain one or more statements. In Python,
the code block associated with an if statement is distinguished by indenting lines of code
immediately underneath the line containing the if keyword of the selection statement. The
syntax and structure of a unary selection statement are shown below:
if boolean_expression :
statement 1
statement 2
statement 3
For this first version, write a single unary selection statement that checks whether the user has
specified whether it is windy or not. If it is windy, the program should output, “Be sure to not
bring an umbrella because it is windy.” Pseudocode and sample input and output for this first
version of your program are given below.
• Ask the user if it is windy
1
Figure 1: Sample output for the initial version.
• Save user input into a variable
• If it is windy, print “Don’t bring an umbrella because it’s windy.”
• If it is not windy, do nothing
3 Binary Selection
We’ve also discussed binary selection, which is a fancy name for an if/else statement. It has
an if clause and an indented code block just as in unary selection, but it also has an else clause
and code block that is executed whenever the Boolean expression in the if clause evaluates to
False.
The syntax and structure of a binary selection statement are shown below below, where
Statements 1 through 3 are the code block for the if clause, and Statements 4 and 5 constitute
the code block for the else clause.
if boolean_expression :
statement 1
statement 2
statement 3
else:
statement 4
statement 5
Next, modify your code so that it still prompts the user to answer whether it is windy, but this
time if the answer is “no”, then have the program output, “It is not windy. Bring an umbrella
if you wish.” If it is windy, the program should output the same as before. Sample input and
output for this second version of your program is shown below.
Figure 2: Sample output, Binary Selection
2
4 Boolean expression with logical operators
We’ve discussed in lecture how to use more complicated boolean expressions; specifically, the
logical operators or, and, and not were presented. Modify your code to also prompt the user to
for whether it is sunny or cloudy.
Retain the if, else code as you’ve already written, except
change the Boolean expression to check if it is windy and sunny. If the user specifies yes, then
the output should be “It’s windy and sunny, so bundle up and don’t bring an umbrella.” If it
is not both windy and sunny, have the program output, “It is not both windy and sunny.”
Pseudocode for the revised version of your program is shown below. Sample output is shown
in Figure 3.
• Ask user if it is windy, save input into a variable
• Ask user if it is sunny or cloudy, save input into a second variable
• If it is windy and sunny, output “It’s windy and sunny, so bundle up and don’t bring an
umbrella.”
• Otherwise, output “It is not both windy and sunny.”
Note: Here and in all further parts of the lab, you may assume that the user responds to the
sunny/cloudy prompt with the exact input “sunny” or “cloudy”; you do not need to handle
other inputs. Also notice that the instructions above are phrased only in terms of sunny and
not sunny.
Figure 3: Sample output for boolean expression with logical operators
5 Nested if statements
As shown in lecture, it is possible to nest an entire selection statement (if statement with
an else clause) inside of a code block of an existing if statement. The syntax is shown in
below. To make it easier to see, a box has been drawn around the outer-most and inner most
if statements.
if boolean_expression_1 :
if boolean_expression_2 :
statement_1
else:
statement_2
else:
statement 4
statement 5
3
Modify your code so that the outer condition (boolean expression1 ) checks if it is windy,
and the inner condition (boolean expression1 ) checks whether it is sunny. If it is windy and
sunny, print “It is windy and sunny,”; if it is windy and not sunny, print ”It is windy and not
sunny”; if it is not windy, print “It is not windy.” Sample output is shown In Figure 4.
Figure 4: Output of program with nested conditionals
6 Clothing picker: chained conditionals
One more possible clause in a conditional statement an elif clause. An elif, which is short of
else if, contains a Boolean expression that is checked ONLY if the first if’s condition, and all
preceding elif conditions all evaluate to False.
Unlike an else, whose code block is ALWAYS
executed if the if condition evaluates to False, the code block of an elif is executed only if the
conditional of the elif evaluates to True. Note that including an else is always optional; an if
statement can have zero or more elif clauses and zero or one else clause.
This time, have your program prompt the user to ask if it is sunny, and also ask for the
temperature. Modify your program so that the else code block has a nested if statement as
well. Both of the nested if statements will now have if, elif, and else clauses (see sample
below).
The outer condition should check whether it is sunny, and inner if/elif/else should
make recommendations according to the temperature and whether or not it is sunny. Don’t
forget to convert the temperature input to an int and recall that you can use comparison
operators like <= and >= to get the boolean result of numerical comparisons.
Write appropriate conditions that rely on the user’s input (whether it is sunny and the temperature), and write appropriate print statements that produce the clothing recommendations
indicated in Figure 5.
Table 1 shows the sunny/temperature combinations and their corresponding output value
(clothing recommendation) that your program should print. Sample output is shown in Figure 6.
4
Figure 5: Schematic of logic for clothing picker
Table 1: Sample input/output combinations
Sunny Temperature Output
Yes Less than 60 degrees Wear a sweater
Yes 60 degrees exactly Woo hoo, it is 60 degrees. Wear what you want
Yes More than 60 degrees Wear a tee shirt and flip flops
No Less than 40 degrees Wear a coat and hat
No Between 40 and 50 degrees Not quite freezing, but close. Bundle up
No 50 degrees exactly A jacket is best
No More than 50 degrees Wear a long sleeved shirt
Figure 6: Sample clothing picker program output. Note that this does not display all possible
cases in the table above, but your program must work for all of them.
Submission
Upload clothingPicker.py to Canvas for grading.
5
Rubric
Your file is called clothingPicker.py 1 point
The top of clothingPicker.py has comments including your name, date, and a
short description of the program’s purpose.
Comments placed throughout the
code explain what the code is doing.
3
Your program makes use of if, elif, and else. 6
Your program correctly prompts the user and stores the user’s input. 3
Your code provides unique clothing combinations for each of the
sunny/temperature combinations in the table in this lab handout.
7
Total 20 points
6
CSCI 141 Lab 4 Drawing with Loops and Turtles Solved
Introduction and Setup
This lab gives you practice with Python loops and Turtle graphics. You’ll complete three
programs that draw pictures: the first two are so-called “ASCII art”, which refers to pictures
made from text characters; the third one is made using a turtle.
If you have questions, be
sure to ask the TA: your TA is there to help you! Log into your operating system of choice
and make a lab4 directory in your N drive or home directory. You will write three programs:
triangle.py, triangle.py, and turtledraw.py.
1 triangle.py
Your first task is to write a program that asks the user for a width, then prints a sideways
isosceles triangle made of asterisks (“*”) with the given maximum width. For example, a width
of 3 would print:
*
**
***
**
*
A width of 8 would print:
1
*
**
***
****
*****
******
*******
********
*******
******
*****
****
***
**
*
A triangle of width 1 would print a single asterisk, and width 0 should print no asterisks.
Your solution should use at least one for loop. Here’s a suggested way to approach this problem:
1. Create an empty file triangle.py in your lab4 directory. Write a comment at the top
listing the code’s author, date and a short description of the program.
2. Write a code snippet that prints a given number of asterisks in a row, followed by a
newline. Hint: there are ways to do this with or without using a loop.
3. Draw the top half of the triangle by putting the code you wrote in Step 2 in the body of
a loop that changes the number of asterisks drawn.
4. Draw the bottom half of the triangle using a similar approach.
5. Test your code on widths 2 and 3 first, then check 0 and 1, then try a larger number such
as 8.
2
2 flag.py
The purpose of this program is to print an ASCII art approximation of the American flag.
Figure 1: The true American flag
Some things to notice:
• We have to get a bit approximate with ASCII art, because the rows of stars in the true
flag don’t line up with the stripes. Our version lines them up, and thus has only 4 stripes
below the stars, instead of 6 as in the true flag.
• The whole flag has 13 rows.
• The whole flag is 55 characters wide.
• The 9 rows of stars alternate between having 6 and 5 per row, with two spaces in between.
The 6-star rows have no spaces at the beginning and two before the stripes begin; the
5-star rows have two spaces at the beginning and thee spaces before the stripes begin.
Here are some guidelines and suggestions:
• You must control structures (loops, if statements, etc.) to print the rows of the flag.
• You may use no more than 6 print function calls
3
* * * * * * ======================================
* * * * * ======================================
* * * * * * ======================================
* * * * * ======================================
* * * * * * ======================================
* * * * * ======================================
* * * * * * ======================================
* * * * * ======================================
* * * * * * ======================================
========================================================
========================================================
========================================================
========================================================
Figure 2: An ASCII art approximation of the American flag.
• All print function calls must be inside the body of a loop.
• The characters must be printed exactly as displayed in the Figure above.
• Try to write this program as concisely as possible. I (Scott Wehrwein) wrote a solution
that has 7 lines of code, not counting comments. If you’re looking for a challenge, see
if you can fit your program in a space smaller than the flag it prints (13 lines long, 55
characters wide).
3 turtledraw.py
In this section, you’ll write a program turtledraw.py that creates a picture like the one shown
in Figure 3. This may seem intimidating at first! But the code you’ll need to write isn’t actually
that complicated. There’s a lot of repetition in the picture, and you’ll use loops to perform this
repetition effortlessly.
You’ll also get some practice looking at the documentation for a module; the turtle module
has tons of functionality, most of which you won’t use or understand—that’s fine! The ability
to sift through unfamiliar documentation and find out how to use the pieces relevant to solving
your problem is a valuable skill.
Each pattern is identical, and is simply composed of many squares with side length 100, each
drawn with one corner in the center of the pattern, but at different angles.
4
Figure 3: The result of running turtledraw.py
3.1 Drawing a Square
Start by writing code to draw a square with side length 100. Recall that you saw an example
like this in lecture. After this step, your program should generate the picture shown in Figure
4.
3.2 Drawing one pattern with many squares
Next, you’ll create a single one of the patterns. To draw 60 squares that go all the way around
a circle (360 degrees), you’ll need each one to be different by 6 degrees from the previous one.
Put the code for drawing a square inside a for loop that draws all 60 squares. When it works
correctly, you should get a picture like the one in Figure 5.
3.3 Speeding up the drawing
At this point, you’re probably sitting around waiting for the turtle to finish drawing, and
thinking “wow, CS is boring”. Most programs we write run very quickly, but you can see that
loops make it easy to write short programs that still take a long time to finish! Fortunately,
5
Figure 4: Drawing a square with side length 100
the turtle module has some features to speed up the drawing. Start by looking in the turtle
module’s documentation (https://docs.python.org/3.3/library/turtle.html). There’s a
lot there, but don’t worry about all the stuff you don’t understand!
Find the section on the
speed method, and read the description to see if you can figure out how it’s used. In your code
above where your turtle starts drawing anything, call the speed method on your turtle object
(e.g., scott.speed(arg )) with the correct argument to make the turtle move as quickly as
possible. Try running your program again – do the squares draw faster now?
That helps some, but it still takes a few seconds to draw 60 squares! The reason for this is that
Python is re-drawing the entire picture every time the turtle moves. You can think of this as
Python having to loop over all 120,000 pixels and re-color each one.
We can speed things up
even more by telling the turtle not to re-draw between moves, and to draw once at the end.
Near the top of your code, before your turtle starts drawing, add the following line:
turtle.tracer(0, 0)
Notice that this a turtle module function, not a method of your turtle object. This disables
re-drawing after each move. Next, at the end of your program, add the following line:
6
Figure 5: Drawing a single radial pattern.
turtle.update()
This tells Python to re-draw the picture to the screen. Now we’re not wasting effort re-drawing
each time the turtle moves! When debugging your code, you may find it helpful to keep the
animations to see the sequence of moves the turtle makes. Make sure that the submitted verision
of your code has the above lines and draws the whole picture in less than a couple seconds.
3.4 Repeating the pattern four times
The last thing we need to do is draw the pattern four times, near each corner of the window. In
particular, draw the pattern centered at all four corners 200 units away from the middle of the
screen (at coordinates (0,0), where the turtle starts).
Start by looking at the documentation
for the penup, pendown, and goto methods. Start by using these methods to move your turtle
to position (-200, -200) before drawing the pattern. Make sure the turtle doesn’t draw a line
when it’s moving from the middle of the screen to the corner.
Finally, we need to move the turtle to each of the four corners and repeat the same pattern.
You could copy/paste the same code four times and change the coordinates, but that wouldn’t
be ideal if we wanted to draw 400 of these patterns instead. So let’s use loops instead!
7
The coordinates where we want to draw the pattern are:
(-200, -200)
(-200, 200)
( 200, -200)
( 200, 200)
Notice that this is just all possible ordered pairs of -200 and 200. You saw an example of how
to print all possible pairs of 1 through 6 in lecture; this is similar, but with -200 and 200 instead
of 1 through 6, and instead of printing them, you’re moving the turtle to those coordinates and
drawing the pattern.
In class we used while loops, but for loops could also work (and might
be a more natural choice). You may choose whichever loop you like. The pseudocode I’d write
for this is something like:
for i = each of {-200, 200}:
for j = each of {-200, 200}:
move to (i,j) without drawing a line
draw the pattern
3.5 Color the drawing (optional)
Look up the turtle’s color method and figure out how to make your drawing more colorful.
You can color the drawing however you want, but don’t change the pattern drawn. An example
coloring is shown in Figure 6.
Preparing your files for submission: creating a zip file
For this lab and future labs and assignments with multiple files to submit, you will submit a
single zip file containing all your programs. Instructions on how to do this depend on your
platform; here are the steps for Linux, Windows, and Mac:
8
Figure 6: Sample colored pattern.
Linux
Using the terminal (command line):
1. Navigate to the directory containing your files:
cd lab4
2. run the zip command, giving it the zip file name as the first argument, and all the files
you want to submit as the reamining arguments. For example:
zip lab4.zip triangle.py flag.py turtledraw.py
3. Verify that the zip file (e.g., lab4.zip) has been created by listing the files in the directory:
ls
9
You can also use the graphical file manager. Navigate to the directory with your submission
files, select all the files you wish to submit (hold CTRL and click on each file to select multiple
files). Right click on one of the selected files and select Compress…. Name the zip file and
make sure to select the .zip option.
3.6 Windows
Navigate to the directory containing your code using the file explorer. Select all the files you
wish to submit (hold CTRL and click on each file to select multiple files). Right-click on one
of the files, hover over Send to, and choose Compressed (zipped) folder. Rename the
resulting zip file to your desired filename (e.g., lab4.zip).
3.7 Mac
Follow the terminal (command line) instructions under Linux.
Alternatively, navigate to your code in Finder and select all the files you wish to submit. Select
multiple files by holding down Command and clicking each file. Right click one of the files
and select Compress 3 items (the number will depend on how many files you have selected).
Rename the resulting Archive.zip to your desired filename (e.g., lab4.zip).
Submission
Submit a zip file called lab4.zip containing triangle.zip, flag.zip, and turtledraw.zip
to the Lab 4 assignment on Canvas.
10
Rubric
You submitted a single zip file called lab4.zip, containing three Python files
called triangle.py, flag.py, and turtledraw.py
1 point
The top of each program has comments including your name, date, and a short
description of the program’s purpose. Comments placed throughout the code
explain what the code is doing.
3
triangle.py produces the correct output 6
flag.py produces the correct output 5
flag.py uses 6 or less print statements, and no print statements outside a
loop
5
turtledraw.py draws at least one instance of the pattern. 4
turtledraw.py draws four copies of the pattern in the correct corner positions
using loops.
4
turtledraw.py draws the pattern quickly and without animation. 2
Total 30 points
CSCI 141 Lab 5 Functions Turtle Shape Functions Solved
Introduction
This lab introduces you to the art of writing your own functions, the concept of local variables
and parameters, and the importance of documenting the behavior of the functions you write.
You will write a handful of functions that draw various shapes using a turtle, and use them to
make complex drawings with ease.
1 Functions
This section of the handout reviews the basics of functions. Please read through it before
getting started, and refer back to it if you encounter confusion or unfamiliar terminology when
completing the activity. If you have any questions, your TA is there to help.
Basics
As we’ve seen in lecture, functions provide a way to assign a name to a given procedure, or
a sequence of statements. We’ve been using (calling) functions that have been written for us
since early in the course, such as
print(“Hello, world!”)
A function can take zero or more input arguments, have effects, and optionally return a value.
For example,
print(“Hello world!”)
takes one or more arguments as input, has the effect of printing them to the screen, and does
not return a value.
1
Writing your own functions is an extremely powerful ability, because it gives you a way to create
customizable pieces of code that you can then use as building blocks for creating more complicated programs. Recall from lecture that the syntax for declaring a function looks something
like this:
def function_name(arg1, arg2):
“””An example function that demonstrates the syntax for
writing your own functions.”””
statement_1
statement_2
statement_3
return a_value
Here’s an example program that declares a function that takes two inputs, computes their sum,
and then prints the sum before returning it. The program then declares two variables and calls
the function to print and return their sum.
# example of a function definition:
def calc_sum(num_1, num_2):
“”” Print, then return, the sum of num_1 and num_2
Precondition: num_1 and num_2 are numbers. “””
the_sum = num_1 + num_2
print(the_sum)
return the_sum
a = 4
b = 6
# example call to the function:
ab_sum = calc_sum(a, b)
Notice that printing a value and returning it are two different things: printing is an effect that
causes it to show up on the screen. Returning it means that the expression calc sum(num 1,
num 2) evaluates to the resulting sum. This means when we execute the assignment statement
after the function definition, the returned value pointed at by the sum will get assigned to the
variable ab sum.
2
Triple-Quoted Strings
Notice that the lines directly after after the function header (the line with the def keyword)
contain a triple-quoted string. Enclosing a string in triple quotes is like using single or double
quotes, except that newlines are allowed in triple-quoted strings.
my_str = “a normal string
with a newline” # will cause an error
triple_quoted_string = “””A string in
triple-quotes””” # will not cause an error
print(triple_quoted_string)
# would print the following:
# A string in
# triple-quotes
Otherwise, a triple-quoted string behaves just like any other string.
Specifications
When writing functions in any language, it’s standard practice to write a specification (or
spec, for short): a description of what someone needs to know to use it. In particular, the spec
typically includes a description of any parameters, effects, and the return value, if any, of the
function.
This makes it possible for other programmers to make use of your function without
having to read through the function’s code to figure out how it works. This is what you’ve been
doing all along when calling functions like print: you know what it does, but you don’t know
how the code is written to accomplish its behavior.
Docstrings
In Python, the convention is to write function specifications in docstrings: triple-quoted strings
that appear just after the function header (the line with the def keyword).
The triple-quoted
string is not technically a comment: it’s actual Python syntax; but an expression (or a value) on
a line by itself has no effect when executed by the Python interpreter, so it’s presence doesn’t
change the behavior of the program.
Consequently, it is not a syntactic requirement of the
language to include a docstring in every function. However, it is a requirement of this course
3
to include a docstring in every function you write, unless you are told otherwise. Take a look
at the docstring in calc sum for an example.
What information should you include in your docstrings? Generally speaking, a programmer
should know the following after reading your function’s specification:
• The meaning of each parameter that the function takes
• Any effects that the function has
• The return value (and its type), if any, of the function
• Any preconditions: Assumptions that your function makes about the state of the program, or about the arguments passed to it.
• Any postconditions: Assumptions that can be made once the function call is finished
about the program state or return value.
Note that it’s a good idea to keep specifications as concise as possible. For example, the
spec for calc sum does not specify as a postcondition that the return value is the sum of the
two inputs, because that’s already stated in the description.
However, it is worth including the
precondition that the arguments are numerical, because otherwise an error might result. A user
of your function is now aware that they shouldn’t call calc sum with non-numeric arguments.
If they do and an error occurs, it’s their mistake, not yours!
Local Variables
Notice that in the definition of calc sum, we created a new variable called the sum1
. Because it
was created inside a function definition, the sum is what is known as a local variable, meaning
that it doesn’t exist (or isn’t “visible”) anywhere in the program except inside the calc sum
function definition.
A variable’s scope refers to the set of statements in a program where it is
accessible; in this case, the sum’s scope is within the calc sum function. If we tried to refer to
the sum outside that indented code block, we’d get an error.
Variables such as a, b, and ab sum are called global variables because once they are defined
using an assignment statement, they are visible for the entire remainder of the program.
1
I didn’t call it sum because that’s already the name of a builtin function; it’s syntactically valid to create a
variable with that name, but it “hides” the builtin function so you can’t use it anymore because sum now refers
to a varaible.
4
Parameters Are Local Variables
When defining a function, we need a way to refer to the arguments that are passed in when
it’s called. Parameters serve this purpose: in the calc sum function definition, num 1 and
num 2 are the function’s parameters.
When the function is being executed, num 1 points to the
value of the first argument and num 2 points to the value of the second one. Consequently,
parameters are simply special local variables that are automatically assigned the values passed
to the function as arguments.
Like any other local variable, their scope is limited to the function
definition to which they belong. Referring to num 1 or num 2 outside of the function definition
will result in an error for the same reason that trying to refer to the sum will cause an error.
2 Shape Functions for Turtles
You’ll now write some functions that will make it easier to make complicated drawings using
Python’s turtle module. For now, you’ll be provided with the function header and specification, and it is your job to make sure that the function implements (or adheres to) the spec
exactly and in all cases.
2.1 Setup
Create a lab5 directory in your lab environment of choice. Fire up Thonny, create a new
file, and save it as turtleshape.py. Write a comment at the top with author, date, and a
description of the program. Download turtleshape test.py from the course webpage and
save it in your lab5 directory alongside turtleshape.py.
2.2 Testing
One of the many benefits of writing small, self-contained functions is the ability to test them
independently of other code that uses them. Once you’ve tested a function thoroughly, you can
safely use it without fear of a bug lurking somewhere inside.
It’s a good idea to test functions
one at a time, as you write them. Start by making calls to your function in the interactive shell
(the bottom pane in Thonny) to see if they’re working correctly.
Once you believe a function behaves as specified, open up turtleshape test.py, and look
toward the bottom for a commented-out call to a function named test function name. For
example, for draw square, the corresponding function is called test draw square. Remove
5
Figure 1: The correct output of turtleshape test.py after all functions are completed.
the # from the beginning of the line to enable the test function, then hit the green Run button
to run turtleshape test.py.
Each of the functions draws one piece of the drawing shown in
Figure 1. For example, the black squares of increasing size in the bottom left should appear
exactly as in the figure once your draw square function works correctly.
To make sure that everything’s set up correctly, first run the test program unmodified: you
should see the drawing with only the green dot in the middle.
6
2.3 draw square
In last week’s lab, you wrote a loop to make a turtle draw a square. Now, let’s do the same
thing, but wrap it in a draw square function so we can draw a square with a simple function
call.
Header and Specification:
def draw_square(t, side_length):
“”” Use the turtle t to draw a square with side_length.
Precondition: t’s pen is down
Postcondition: t’s position and orientation are the same as before
“””
Type the function header and specification (docstring) into turtleshape.py, then write code
in the function body to make the turtle draw a square.
Try out your draw square function in the interactive pane, something like this:
>>> import turtle
>>> scott = turtle.Turtle()
>>> draw_square(scott, 100)
2.4 draw rectangle
Next, write a more general function to draw a rectangle of any size. Notice that once we have a
rectangle function, we can use it to draw a square by calling the rectangle function with equal
side lengths.
def draw_rectangle(t, width, height):
“”” Draw a rectangle using turtle t with size width x height
Precondition: t’s pen is down
Postcondition: t’s position and orientation are the same as before
“””
After uncommenting test draw rectangle in turtleshape test.py, the orange spiral of rectangles should appear as in Figure 1.
7
2.5 draw triangle
Another way to generalize the square function would be to draw different equilateral polygons (i.e., shapes with different numbers of equal side lengths). To get started, implement a
draw triangle function that draws a triangle with equal length sides:
def draw_triangle(t, side_length):
“”” Draw an equilateral triangle using turtle t with side_length
Precondition: t’s pen is down
Postcondition: t’s position and orientation are the same as before
“””
When completed and the corresponding test function is uncommented, the purple bowtie-like
figure should appear as in Figure 1.
2.6 draw polygon
You’ve now figured out how to draw a square (4-sided polygon) and a triangle (3-sided polygon).
Now, write a function that draws an n-sided polygon:
def draw_polygon(t, side_length, num_sides):
“”” Draw a polygon with num_sides sides, each with length side_length
using turtle t
Precondition: t’s pen is down; num_sides > 2
Postcondition: t’s position and orientation are the same as before
“””
The red pattern with nested n-gons should appear as in the Figure when this function works
correctly.
2.7 draw snowflake
One of the reasons that functions are so powerful is that we can compose them; in other words,
one function can call another. Now that we have a function that draws polygons, it’s pretty
simple to make a function that uses it to create variations on the snowflake-like pattern from
last week’s lab:
8
def draw_snowflake(t, side_length, num_sides):
“”” Use t to draw a snowflake made of ngon-sided polygons. The snowflake
contains 10 copies of a polygon with num_sides and side_length, each
drawn at a 36-degree angle from the previous one.
Postcondition: t’s position and orientation are the same as before
“””
The teal, green, and blue snowflakes in the bottom right corner should appear as in the Figure
once this function is working correctly.
2.8 teleport
Finally, write a function that implements a convenient ability: teleport the turtle to a given
location without drawing, but leaving the pen state unchanged afterwards. This is similar to
the turtle object’s goto method, except it never draws.
To accomplish this, you’ll need to
pick up the pen first, then put it down only if it started out down. You may find it helpful to
look at the turtle documentation for methods that could be useful here.
def teleport(t, x, y):
“”” Move the turtle to (x, y), ensuring that nothing is drawn along the
way. Postcondition: the turtle’s orientation and pen up/down state is
the same as before.
“””
When basic movement is working, the gradient-colored grid of dots should appear. When the
pen is correctly restored to its previous state, the vertical red lines should appear as in the
Figure.
2.9 Screenshot
Take a screenshot of the Turtle window when you have everything working, and name the file
turtleshape.png.
9
3 Drawing
Your final task will be to write a short program that uses your drawing functions to make some
interesting drawing.
Importing Local Files; Writing “Main” Functions
You may have noticed that the code in turtleshape test.py calls functions from turtleshape.py.
To make this possible, turtleshape test.py had to execute import turtleshape; this is just
like importing a module (like math or turtle, except the module is located right in the same
directory. Python looks first in the local directory for a module with name turtleshape.py,
then it imports the code if it is found.
What happens when importing code? Basically, it’s like pasting the imported module’s code
into your file: it all gets run. So far, your turtleshape.py contains only function definitions,
so importing it simply defines those functions.
But if you wrote code outside the functions, it
would get executed when you import turtleshape. Often, we want to separate the behavior
of a file as a program versus as a module, so importing it causes functions to be defined but
doesn’t run the program, but you can still run the program, e.g., with python turtleshape.py
or by clicking the Run button.
The way to do this is to use a so-called “main function” or “main guard”. turtleshape test.py
contains an example of this. Basically, any code you want to run as a program but don’t want
to execute when you import your file as a module, you can put inside the following if statement:
if __name__ == “__main__”:
# code here will not run when this file is imported
# but will run if the file is run as a program
print(“Hello, world!”)
You don’t need to worry about the details of why this happens, but it’s a good thing to
remember how to do. You can always google it if you forget the syntax.
A common way to use this is to have one function that contains your program code, usually
called main(), and place a single call to that function inside the main guard:
10
def other_function():
“”” Return the number 4 “””
return 4
def main():
“”” Main program: print hello, world! “””
print(“Hello, world!”)
if __name__ == “__main__”:
main()
If this were in a file called prog.py, then running python prog.py would print ”Hello, world!”,
whereas executing import prog would make other function and main available for use, but
wouldn’t execute the call to main().
Make a Drawing
Below all your function definitions in turtleshape.py, write some code that creates a drawing.
Put your code in a main function and call it inside a main guard as illustrated above, so that
running the test program (which imports your code) does not cause your main function to be
called.
Your code should use at least one loop and make use of at least two of the functions you wrote
in this lab. Feel free to also use other functions from the turtle module. Take a screenshot
of your drawing and save it as drawing.png.
Your drawing should complete in under a few
seconds (use turtle.tracer(0,0) and turtle.update() as in Lab 4), and should match your
screenshot.
Submission
At this point, show the output of the test program and your drawing to your TA
so you can be immediately awarded points for it. Unless you do not finish during the
lab period, do not leave until your TA has verified that your output is correct.
Create a zip file called lab5.zip containing turtleshape.py, turtleshape.png, and drawing.png.
Upload your zip file to the Lab 5 assignment on Canvas. Even if your TA has checked you off,
you still need to submit to Canvas.
11
Rubric
You submitted a single zip file called lab5.zip, containing the correct files 1
The top of your program has comments including your name, date, and a short
description of the program’s purpose. Comments placed throughout the code
explain what the code is doing.
1
draw square works correctly 3
draw triangle works correctly 3
draw rectangle works correctly 3
draw polygon works correctly 3
draw snowflake works correctly 3
teleport works correctly 3
Your drawing code is is inside a main guard 2
Your drawing code uses at least one loop and two of the functions you wrote. 6
Your drawing code runs in under a few seconds. 2
Total 30 points
12
CSCI 141 Lab 6 Functions and Function Composition Solved
Introduction
By this time in the quarter you’ve seen functions in lecture, in lab, and from here on they will
be required in the coding portions of the homework assignments, including A4 which is due this
week.
In this lab, you’ll write a program that calculates the total square footage in a home. Imagine
you are working for a construction company that builds homes with only square or rectangular
rooms. The houses vary in size, with as little as 1 room and up to 100s.
Your task is to
write a program that will prompt the user to input the number of rooms and their
dimensions, and which then calculates the total square footage of the home. Two
invocations of such a program are shown below.
Figure 1: Two sample invocations
The figure on the left is the program running where a user specifies a house with 3 rooms – a
square room and two rectangle rooms. The image on the right is the calculation for a house
with 4 rooms – three square rooms and a rectangular room.
You’ll create such a program from scratch. You’ll be asked to follow good coding conventions
– if you find yourself typing similar code over and over again, create a function for performing
that repeated task (as was shown in lecture).
Look at the above program invocations, and notice the following:
• To calculate the size of a square room, you need only the dimension of one of the walls
• To calculate the size of a rectangular room, you need both dimensions, the width and
length
• There are repeated print statements that are very similar, but not identical. However,
they all begin with “What is the”, and end with a question mark.
From these observations, your supervisor (boss) has decided that your program can have ONLY
3 functions:
1. room_square_feet, which takes a single argument to designate whether the room is a
square or rectangular room. If the room is a square room, the function room_square_feet
1
invokes the prompt_user function once to retrieve the single dimension needed to calculate
the size of the room. If the room is a rectangular room, the function room_square_feet
invokes the prompt_user function twice to retrieve the two dimensions needed to calculate
the room’s size. The function room_square_feet returns the square footage of a room.
2. main, which prompts the user for the count of rooms and calls room_square_feet for
each room, using the accumulator pattern (refer to Section 6.4 of the textbook) to keep
a running total of the square footage of the house.
3. prompt_user, which receives two arguments and returns one value. The first parameter,
of type str, is the text of the question that the user is prompted. In the examples above,
“length of the room” and “width of the room” and “shape of room 1, square or rectangle”
would be the three Strings that are provided as input on three separate occasions to the
function prompt_user.
The second argument designates the return type of the function.
Hint: use type conversion function(s) to convert the user’s input into the appropriate
type of data to be returned.
A diagram showing two example usages of the prompt_user
function for two sample inputs is included below.
prompt_user “number of rooms”
“integer”
Prompt user : What is
the number of rooms?
User inputs : “4”
inputs outputs
4
(type int)
prompt_user “shape of room 2”
“string”
Prompt user : What is
the shape of room 2?
User inputs :
“rectangle”
inputs outputs
“rectangle”
(type str) 1 Setup
Create a lab6 folder and in it create a Python file called squarefootage.py.
2 Example Program Flow
The steps below illustrate an example of the program’s behavior when prompting for the information and calculating the square footage of a single room. Recall that your main program
will do this once for each room in the house. Notice that main uses prompt_user twice, then
calls room_square_feet, which itself calls prompt_user once or twice depending on the shape
of the room.
2
Step 1: prompt_user is invoked with first and second arguments “shape of room 1” and “string”
both of type string.
Step 2: prompt_user prompts the user with the question “What is the shape of room 1?”
Step 3: The user responds to the prompt and types “square”
Step 4: prompt_user returns the string “square”, which is then passed to the function room_square_feet
Step 5: The function room_square_feet calls prompt_user with two arguments, “side length of
square room” and “integer”
Step 6: The function prompt_user prompts the user with the question “What is the side length
of square room”
Step 7: The user responds to the prompt and types “12”
Step 8: The function prompt_user returns the integer 12, which is saved in a variable in the
function room_square_feet
Step 9: The function room_square_feet calculates the size of the room (12 ∗ 12) and returns the
integer 144.
3 Game Plan and Guidelines
• All three functions are fairly simple, taken by themselves. You should be able to write
each one in less than about 10 lines of code.
• Start by writing a header and specification for the prompt_user function based on the
description above. Then implement the function and test it using the interactive shell.
Test it for both integer and string output types.
• Write a header and specification for room_square_feet. Implement it, using your alreadytested prompt_user function, and test its functionality in the interactive shell.
• Write the main function, noting that it takes no arguments and has no return value; when
the total square footage is calculated, print the total.
• Finally, at the bottom of your program, call your main function in a main guard so that
running the program calls the main function:
if __name__ == “__main__”:
main()
• As usual, you are not required to check for and handle input from badly behaved users:
you may assume the user enters numbers when they’re supposed to, and that they enter
either square or rectangle for the shape of each room.
• We test your programs with automated scripts, so the prompts must be made in exactly
the order shown in the sample outputs to receive full credit. The text of the prompts
does not need to match exactly, but the order must match.
3
Submission
Submit squarefootage.py via Canvas.
Rubric
Your file is called squarefootage.py and has a comment specifying author, date,
and purpose at the top.
1 points
Your program uses good, descriptive variable names 2
main, room_square_feet, and prompt_user have headers and docstrings consistent with the description in the lab handout
6
Each function is at most 10 lines of code (not counting comments) 6
prompt_user prompts the user and returns the correct type 4
room_square_feet uses prompt_user to prompt for the dimensions 2
main uses prompt_user to specify how many rooms 2
main calls prompt_user to prompt for shape of the room 2
main calls room_square_feet for each room and the return value is added to an
accumulator variable
2
main function prints correct final square footage 3
Total 30 points
4
CSCI 141 Lab 7 Strings Solved
Introduction
In this lab you’ll gain practice using and manipulating strings. In lecture you’ve seen how to
iterate over the characters in a string, access individual characters by index, and how to slice
out substrings.
We also touched on a few of the multitude of methods that can be called on
string objects, including upper, lower, find, and replace.
Suppose you are an employee at a software company called Lotter.io. You have been tasked
with writing a Python program that will simulate the drawing of a winning lottery pick, then
prompt a user to guess the lottery pick, and inform the user if their pick is the winning pick.
Your company’s secret sauce that will guarantee its explosive growth into a billion dollar startup
is that the lottery doesn’t just involve guessing numbers: Instead, this lottery involves both
words and digits.
A lottery pick is made up of one of three words (monkey, dragon, or snake),
and one of three digits (1, 2 or 3), arranged either with the word first or the number first. For
example, monkey1, and 2dragon are both possible winning picks. The user only wins if the
correct word and the correct digit are guessed in the correct order.
The program consists of three main tasks:
1. Generate a winning pick.
2. Get a valid pick from the user.
3. Check the user’s pick against the winning pick and tell them how they did.
Three sample invocations are shown in Figure 1.
1 Generate a winning pick
Random pick generation is to be implemented in the generate winner function. The function
header, specification, and some of its implementation have been written for you.
Easter Egg
Our lottery game will have a secret easter egg, a hidden feature that’s only accessible to those
who have read the code, or users who somehow stumble upon it. Our easter egg behavior is as
follows.
1
Figure 1: Three sample invocations
The welcome message tells the user to press enter to continue; however, if the user enters
something that looks like a valid pick and then presses enter, generate winner will simply use
their input as the correct pick.
The functionality for this easter egg has been implemented for you: the begin input variable
captures what the user enters, and is passed into the generate winner function, which first
checks to see if it should return the cheat pick.
This “cheater mode” may help you more
thoroughly test your program’s behavior by giving you the option to choose the winning pick
without any randomness involved. It will also make grading easier for us, for the same reasons,
so be sure not to modify the code that implements this feature.
Your task is to write the code after this part of the function that generates and
returns a truly random winning pick. Pseudocode for your portion of the function is
provided as comments in the skeleton code.
2 Get a valid pick from the user.
Implement the get_valid_guess function to prompt the user, repeatedly if necessary, until
they enter a guess that contains one of the words and begins or ends with one of the numbers.
Notice that these criteria do make it possible to enter an invalid pick (e.g., dragoncat3 contains
one of the words and ends with one of the numbers. This is fine: cases such as these will be
handled later in the program. The function header, specification, and pseudocode for this part
are provided in the skeleton code.
2
3 Check the user’s pick
Now, we need to tell the user whether any or all aspects of their pick were correct. Here’s
what the program should do once it has determined the winning pick and the user’s pick. Your
messages do not need to match mine exactly, but should convey the same content. Feel free to
decide on your own prize for guessing the winning pick.
• If the user inputs a pick that exactly matches the winning pick character for character,
the program outputs a message telling the user they’ve won.
• If the user’s word and number both match the winning pick, but their pick doesn’t match
the winning pick exactly, print You guessed the correct number and word in the wrong
order!
• If the number matches but the word doesn’t, print You guessed the correct number but
not the correct word.
• If the word matches but the digit isn’t correct: print You guessed the correct word but not
the correct number.
• If neither the word nor number are correct, print You guessed neither the correct word
nor the correct number.
The main method includes calls to the two functions you completed in the prior tasks, followed
by pseudocode for this step. You may want to, but are not required to, create a separate
function to accomplish this task.
Getting Started
Download the skeleton code lottery.py from the course webpage. Open up and read through
the skeleton code, making sure that you understand the provided code and function specifications. We recommend completing the three tasks in the order described above.
You may find the in and not in operators useful on strings, as well as indexing individual
characters of a string and slicing substrings. Review the lecture slides for details on the syntax
for these operators.
Don’t forget that when a program’s logic gets complicated, it can be helpful
to define boolean variables to keep the conditions of if/elif statements short and easy to read.
Submission
Submit your completed program lottery.py file via Canvas.
3
Rubric
Submitted a file called lottery.py 1
Comment at the top of program specifies author, date, and description 1
Easter egg code is unmodified 1
Random pick is generated 5
User is prompted again if guess doesn’t contain one of the words 5
User is prompted again if guess doesn’t begin or end with one of the numbers 5
Message printed for correct pick 5
Message printed for correct word and number but incorrect order 5
Message printed for correct word but not number, and vice versa 5
Message printed for neither correct 5
Coding style (commenting, variable names, etc.) 2
Total 40 points
4
CSCI 141 Lab 8 Putting it all together Solved
Introduction
In this lab, you’ll write a program to read historical earthquake data from a file and plot each
earthquake on a map using turtle graphics. An example output is shown in Figure 1.
Figure 1: The output from my solution code.
1 Setup
Create a lab8 directory in your lab environment of choice. Download the following files from
the course webpage and place them in your lab8 folder:
• plot earthquakes.py – this file contains skeleton code and pseudocode
• earthquakes.csv – this file contains the data you’ll be reading
• earth.png – this will be set as the background image in the turtle graphics canvas (this
is done for you by the turtle setup function given in the skeleton code).
1
2 Approach and Guidelines
Implement the parse row function and the remainder of the main function according to the
pseudocode included in comments. Follow the same coding style conventions we’ve been using
up to this point: comment at the top, good variable naming, and so on.
You’ll find that you need many of the structures and concepts we’ve covered in this course to
complete this task—ask your TA if you encounter any problems, and use this opportunity to
take note of any topics you need to brush up on before the final exam.
Some hints:
• The code to read the csv file will look pretty similar to the code I provided in A5 to read
the cancer data files.
• The first line of the file contains column headers, so you’ll need to skip over it before
starting to read data.
• Plotting earthquakes on the map is quite simple: the map image (and turtle canvas) is
720×360 pixels, with (0,0) in the center. Longitude (the x axis) goes from -180 to 180 and
latitude (y axis) goes from -90 to 90, so (0,0) is in the center. To get the canvas (x, y)
coordinates based on a given (lon, lat) coordinate, simply multiply each coordinate by 2.
• The skeleton includes an implementation of the teleport function from Lab 5.
• You can use a turtle object’s circle method to draw a circle. See the documentation for
details on how it is called.
• Coloring the circles is optional. In my color scheme, the red channel is proportional to
magnitude, while the green and blue channels are inversely proportional to magnitude.
For an extra challenge, try coloring the circles based on the date instead of the magnitude.
Submission
Take a screenshot of your program’s output and save it as earthquakes.png. Zip your screenshot and completed plot earthquakes.py file in a file called lab8.zip and submit to Canvas.
2
Rubric
You submitted a single zip file called lab8.zip, containing the correct files 2
The top of your program has comments including your name, date, and a short
description of the program’s purpose.
3
The program reads the earthquake data into a list of dictionaries 15
A circle is drawn for each earthquake 5
The circle’s size varies with the earthquake’s magnitude 5
Total 30 points
3



