For quick search
Coursera can be found here

This Specialization covers much of the material that first-year Computer Science students take at Rice University. Students learn sophisticated programming skills in Python from the ground up and apply these skills in building more than 20 fun projects. The Specialization concludes with a Capstone exam that allows the students to demonstrate the range of knowledge that they have acquired in the Specialization.

# An Introduction to Interactive Programming in Python (Part 1)

Lecture slides can be found here
Coursera can be found here

About this course: This two-part course is designed to help students with very little or no computing background learn the basics of building simple interactive applications. Our language of choice, Python, is an easy-to learn, high-level computer language that is used in many of the computational courses offered on Coursera. To make learning Python easy, we have developed a new browser-based programming environment that makes developing interactive applications in Python simple. These applications will involve windows whose contents are graphical and respond to buttons, the keyboard and the mouse.

In part 1 of this course, we will introduce the basic elements of programming (such as expressions, conditionals, and functions) and then use these elements to create simple interactive applications such as a digital stopwatch. Part 1 of this class will culminate in building a version of the classic arcade game “Pong”.

Who is this class for: Recommended Background - A knowledge of high school mathematics is required. The class is designed for students with no prior programming experience.

## Week 1 Statements, expressions, variables

Understand the structure of this class, explore Python as a calculator

### Week 0b - Variables and Assignments

#### Quiz: Quiz 0 10 questions

QUIZ
Quiz 0
10 questions
To Pass70% or higher
Attempts3 every 8 hours
October 22, 11:59 PM PDT

1 point
1.Which of the following are syntactically correct strings?

Try each of them in CodeSkulptor.

1 point
2.To display a value in the console, what Python keyword do you use?

1 point
3.In the following code, there is one line starting with $$\color{red}{\verb|#|}$$. What does this line mean to Python?

1 point
4.Which of the following arithmetic expressions are syntactically correct?

Try each of them in CodeSkulptor.

1 point
5.You would like to make it so that the variable $$\color{red}{\verb|ounces|}$$ has the value 16, thus representing one pound. What simple Python statement will accomplish this?

1 point
6.A gram is equal to 0.035274 ounces. Assume that the variable $$\color{red}{\verb|mass_in_ounces|}$$ has a value representing a given mass in ounces. Which Python statement below uses the variable $$\color{red}{\verb|mass_in_ounces|}$$ to compute an equivalent mass $$\color{red}{\verb|mass_in_grams|}$$ expressed in grams?

Think about it mathematically, but also test these expressions in CodeSkulptor3. If you are still confused, you might check out this student tutorial video by Kelly on unit conversions.

1 point
7.Which of the following can be used as a variable name?

Try using each in CodeSkulptor.

1 point
8.Assume you have values in the variables $$\color{red}{\verb|x|}$$ and $$\color{red}{\verb|y|}$$. Which statement(s) would result in $$\color{red}{\verb|x|}$$ having the sum of the current values of $$\color{red}{\verb|x|}$$ and $$\color{red}{\verb|y|}$$?

1 point
9.Python file names traditionally end in what characters after a period? Don’t include the period.

1 point
10.We encourage you to save your CodeSkulptor Python files where?

### Mini-project #0 - “We want… a shrubbery!” (optional)

#### Mini-project Description10 min

Mini-project development process

in the CodeSkulptor console. Your program should consist of a single line of Python. Before submitting your program, we suggest that you review the grading rubric given below.

#### Practice Peer-graded Assignment: “We want… a shrubbery!”2h

url can be found here

## Week 2 Week 1 - Functions, logic, conditionals

Learn the basic constructs of Python programming, create a program that plays a variant of Rock-Paper-Scissors

### Week 1a - Functions

#### Functions15 min

http://www.codeskulptor.org/#examples-functions.py

#### Visualizing Functions12 min

http://www.codeskulptor.org/#examples-functions.py

### Week 1b - Logic and Conditionals

#### Conditionals10 min

http://www.codeskulptor.org/#examples-conditionals.py

#### Quiz: Quiz 110 questions

QUIZ
Quiz 1
10 questions
To Pass70% or higher
Attempts3 every 8 hours
October 29, 11:59 PM PDT

1 point
1.An if statement can have at most how many else parts?

Unlimited, i.e., 0 or more

1 point
2.Consider the Boolean expression not (p or not q). Give the four following values in order, separated only by spaces:

the value of the expression when p is True, and q is True,

the value of the expression when p is True, and q is False,

the value of the expression when p is False, and q is True,

the value of the expression when p is False, and q is False,

Remember, each of the four results you provide should be True or False with the proper capitalization.

1 point
3.A common error for beginning programmers is to confuse the behavior of print statements and return statements.

print statements can appear anywhere in your program and print a specified value(s) in the console. Note that execution of your Python program continues onward to the following statement. Remember that executing a print statement inside a function definition does not return a value from the function.
return statements appear inside functions. The value associated with the return statement is substituted for the expression that called the function. Note that executing a return statement terminates execution of the function definition immediately. Any statements in the function definition following the return statement are ignored. Execution of your Python code resumes with the execution of the statement after the function call.
As an example to illustrate these points, consider the following piece of code:

Note that this code calls the function do_stuff in the last print statement. The definition of do_stuff includes two print statements and one return statement.

Which of the following is the console output that results from executing this piece of code? While it is trivial to solve this question by cutting and pasting this code into CodeSkulptor, we suggest that you first attempt this problem by attempting to execute this code in your mind.

1 point
4.Given a non-negative integer n, which of the following expressions computes the ten’s digit of n? For example, if n is 123, then we want the expression to evaluate to 2.

Think about each expression mathematically, but also try each in CodeSkulptor.

1 point
5.The function calls random.randint(0, 10) and random.randrange(0, 10) generate random numbers in different ranges. What number can be generated by one of these functions, but not the other?

(Refer to the CodeSkulptor documentation.)

By the way, we (and most Python programmers) always prefer to use random.randrange() since it handles numerical ranges in a way that is more consistent with the rest of Python.

1 point
6.Implement the mathematical function f(x)=−5x5+69x2−47 as a Python function. Then use Python to compute the function values f(0), f(1), f(2), and f(3). Enter the maximum of these four values calculated.

1 point
7.When investing money, an important concept to know is compound interest.

The equation FV=PV(1+rate)periods relates the following four quantities.

The present value (PV) of your money is how much money you have now.
The future value (FV) of your money is how much money you will have in the future.
The nominal interest rate per period (rate) is how much interest you earn during a particular length of time, before accounting for compounding. This is typically expressed as a percentage.
The number of periods (periods) is how many periods in the future this calculation is for.
Finish the following code, run it, and submit the printed number. Provide at least four digits of precision after the decimal point.

future_value(500, .04, 10, 10) should return 745.317442824

1 point
8.There are several ways to calculate the area of a regular polygon. Given the number of sides, n, and the length of each side, s, the polygon’s area is

ns24tan(πn)
For example, a regular polygon with 5 sides, each of length 7 inches, has area 84.3033926289 square inches.

Write a function that calculates the area of a regular polygon, given the number of sides and length of each side. Submit the area of a regular polygon with 7 sides each of length 3 inches. Enter a number (and not the units) with at least four digits of precision after the decimal point.

Note that the use of inches as the unit of measurement in these examples is arbitrary. Python only keeps track of the numerical values, not the units.

1 point
9.Running the following program results in the error

SyntaxError: bad input on line 8 (‘return’).

Which of the following describes the problem?

1 point
10.The following code has a number of syntactic errors in it. The intended math calculations are correct, so the only errors are syntactic. Fix the syntactic errors.

Once the code has been fully corrected, it should print out two numbers. The first should be 1.09888451159. Submit the second number printed in CodeSkulptor. Provide at least four digits of precision after the decimal point.

### Mini-project #1 - Rock-paper-scissor-lizard-Spock

#### This item will be unlocked when the session begins.

http://www.codeskulptor.org/#user43_2OiD0caumf_0.py

## Week 3 Week 2 - Event-driven programming, local/global variables

Learn the basics of event-driven programming, understand difference between local and global variables, create an interactive program that plays a simple guessing game

### Week 2a - Interactive Applications in Python

#### Quiz: Quiz 2a10 questions

QUIZ
Quiz 2a
10 questions
To Pass70% or higher
Attempts3 every 8 hours
November 5, 11:59 PM PST

1 point
1.What typically calls an event handler?

Some code that you didn’t write which generates the event.

The code you write.

1 point
2.In CodeSkulptor, how many event handlers can be running at the same time?

Unlimited, i.e., 0 or more

1

0

1 point
3.What are the three parts of a frame?

Refer to the video on SimpleGUI.

Status Area

Control Area

Mouse

Title

Keyboard

Background Area

Canvas

Border

Options Area

1 point
4.For the SimpleGUI-based programs in this course, we recommended breaking down an interactive Python program into seven parts. Below, these parts are listed alphabetically.

Create frame
Define classes
Define event handlers
Initialize global variables
Define helper functions
Register event handlers
Start frame and timers
However, in lecture, we recommended a particular ordering of these parts.

Enter 7 numbers in the range 1–7, separated only by spaces, to indicate the recommended ordering of the preceding elements of an interactive Python program. For example, if you think that the first action in your program should be to register your event handlers, enter 6 as the first number in the sequence.

1 point
5.Assume the following global definition is part of your program.

If each of the following function definitions are also part of your program, which of them needs a global x declaration? You can try each definition in CodeSkulptor.

1 point
6.Consider the following code.

What is the value of count at the end? Enter a number. (You can double check your answer in CodeSkulptor if you wish.)

1 point
7.Consider the following code.

Which names occur in the global scope?

c

f

b

a

1 point
8.Consider the following code.

Which names occur in a local scope?

f

b

a

c

1 point
9.Which of the following are valid calls to create_frame?

Look at the documentation for SimpleGUI frames, but also try the code in CodeSkulptor.

1 point
10.Which of the following are valid ways of making a canvas with a red background?

Look at the documentation for SimpleGUI constants, but also try the code in CodeSkulptor.

### Week 2b - Buttons and Input Fields

#### Buttons10 min

http://www.codeskulptor.org/#examples-buttons.py

#### Input Fields9 min

http://www.codeskulptor.org/#examples-input_fields.py

#### Visualizing Events5 min

http://www.codeskulptor.org/viz/#examples-input_fields.py

#### Quiz: Quiz 2b10 questions

QUIZ
Quiz 2b
10 questions
To Pass70% or higher
Attempts3 every 8 hours
November 5, 11:59 PM PST

1 point
1.In the following code, what does the number 100 represent?

Use the CodeSkulptor documentation to look it up.

Horizontal position of the button in pixels

Height of the button in pixels

Width of the button in pixels

Vertical position of the button in pixels

1 point
2.How many control objects are allowed in a frame?

1

0

Unlimited, i.e., 0 or more

1 point
3.In SimpleGUI, one kind of object can be added to the control panel that doesn’t allow any handler. Thus, this object can’t respond to anything. What kind of object is that?

Look at the documentation for SimpleGUI control objects.

Label

Frame

This should not be selected
That isn’t a control object.

Button

Title

Canvas

Input field

1 point
4.When you enter text into an input field and press enter, the text is passed to the input field’s event handler. What is the data type of the text?

A string

A number

A string or a number, depending on the text entered

1 point
5.Consider the following conditional statement.

That is equivalent to which of the following simpler statements?

Try to reason logically about each of the statements, but also try each in CodeSkulptor.

1 point
6.Which of the following describes the mistake in the following code?

The call to volume_cube shouldn’t be within a print statement. More generally, function calls usually shouldn’t be within print statements.

All of the printing should be done within the function.

The function should return, not print, its result.

1 point
7.What kind of errors can happen if you are missing a needed global declaration in one of your function definitions? For this question, you need only consider the case where the problem is in the function that is missing the global declaration.

If you are having trouble with this question, watch this week’s Programming Tips video again.

NameError

An incorrect computation that generates no error message

AttributeError

SyntaxError

Error: local variable ‘…’ referenced before assignment

1 point
8.Which of the following function definitions are in the recommended code style?

1 point
9.Cut and paste the following code into CodeSkulptor. Run it and make an attempt to understand how it works.

We’d like to modify the code so that the count is reset to zero whenever a new message is entered. Where would you need to modify this code to implement this change?

Add an assignment to count at the end of this code.

Add an assignment to count in the event handler for the input field. Also add a global count declaration there.

Add an assignment to count in the event handler for the button.

Add an assignment to count in the initialization of global variables.

1 point
10.In the game “Guess the number”, what is the minimum number of guesses necessary to guarantee that the guesser can always win if the secret number is chosen in range(0, 400)?

Review the mini-project description for “Guess the number” if you are having trouble with this problem.

8 guesses

9 guesses

10 guesses

This should not be selected

12 guesses

This should not be selected

It’s impossible to guarantee that you can always win at “Guess the number“.

This should not be selected
That’s clearly wrong. If nothing else, you could use the strategy of guessing each number from 0 to 399, thus needing 400 guesses.

### Mini-project #2 - “Guess the Number!”

#### Mini-project Video6 min

http://www.codeskulptor.org/#examples-guess_the_number_template.py

#### Peer-graded Assignment: “Guess the Number!”2h

http://www.codeskulptor.org/#user43_h8ZiuoEmml_0.py

## Week 4 Week 3 - Canvas, drawing, timers

Create a canvas in Python, learn how to draw on the canvas, create a digital stopwatch

### Week 3a - Drawing Canvas

#### Quiz: Quiz 3a10 questions

QUIZ
Quiz 3a
10 questions
To Pass70% or higher
Attempts3 every 8 hours
November 12, 11:59 PM PST

1 point

1. What Python operator takes two strings (e.g., “sun” and “rise”) and forms the combination of these two strings, one followed by the other (e.g., “sunrise”)?

+

concat

append

concatenate

*

1 point
2.What does the draw handler parameter represent?

If you’ve forgotten, refer to the documentation.

The canvas

Nothing — it doesn’t have a parameter

The object to be drawn

The frame

The location of the object to be drawn

1 point
3.What happens if you draw text outside the canvas coordinates?

Try it in CodeSkulptor.

The text coordinates are implicitly “wrapped” around using modular arithmetic, so that the text appears on the canvas

Some or none of the text is shown. Conceptually, the text is drawn at whatever coordinates are given, but only whatever text fits within the canvas coordinates is shown.

The text appears in the frame, but some or all of the text is shown outside the canvas area.

Causes an error

1 point
4.Assume we have a canvas that is 200 pixels wide and 300 pixels high. We want to draw a green line between the upper left corner of the canvas and the lower right corner of the canvas. Which of the following calls will accomplish this?

Try the code in CodeSkulptor.

1 point
5.Consider the following function definition.

This definition leads to an error. To fix it, what Python expression should replace the question marks below?

string(month + “/“ + day)

string(month) + “/“ + string(day)

str(month / day)

str(month + “/“ + day)

str(month) + “/“ + str(day)

string(month / day)

1 point
6.How many instances of the letter “l” are there in the following:

Although it might be hard to tell, that string contains ones (1) and lower-case L’s (l). Create a small CodeSkulptor program, and use copy-and-paste to insert this string in your code. Your program should only need one function or method call.

1 point
7.Where should your draw_text, draw_line, and similar drawing calls be?

In a draw handler, or a helper function called from it

In the handlers for the control objects that create or change the drawing, or their helper functions

1 point
8.Which of the following function calls are valid, i.e., don’t lead to an error?

Read the documentation for these functions, and also try the code in CodeSkulptor.

float(“5 five”)

int(“5.4”)

float(“5.4”)

int(“5”)

1 point
9.Turn the following description into a CodeSkulptor program, and run it.

Create a 300-by-300 canvas.
Draw two circles with radius 20 and white lines of width 10. One is centered at (90,200) and one at (210,200).
Draw a red line of width 40 from (50,180) to (250,180).
Draw two red lines of width 5 from (55,170) to (90,120) and from (90,120) to (130,120).
Draw a red line of width 140 from (180,108) to (180,160).
The resulting picture is a simple diagram of what?

A person

A house

A computer

A motorcycle

An automobile

1 point
10.The following is a diagram of an archery target.

To draw this in CodeSkulptor, we can put a small yellow circle with a black border on top of a slightly bigger yellow circle with a black border, … on top of a big white circle with a black border. In what order should your code draw these circles?

Smallest first

Largest first

### Week 3b - Timers

#### Quiz: Quiz 3b9 questions

QUIZ
Quiz 3b
9 questions
To Pass70% or higher
Attempts3 every 8 hours
November 12, 11:59 PM PST

1 point
1.When the following code is executed, how many times is timer_handler called?

The body of timer_handler isn’t given, as it is irrelevant for this question. You may want to finish the code and run it before submitting your answer.

0 — The code hasn’t been written correctly.

1

10

Unlimited — It is called repeatedly until you stop the program.

1 point
2.You want a timer to create exactly 1000 events. Which of the following solutions are possible?

In the timer handler, have a local counter for the number of timer calls.
In the timer handler, increment the counter. In the timer handler, check the count and possibly stop the timer.

Have a global counter for the number of timer calls.

In the timer handler, increment the counter. In the timer handler, check the count and possibly stop the timer.

Specify the number of timer events when creating the timer.

Have a global counter for the number of timer calls.

Outside the timer handler, increment the counter. Outside the timer handler, check the count and possibly stop the timer.

1 point
3.How do you change the frequency of a running timer, either increasing or decreasing the frequency? E.g., in the code below, we want code at the question marks that changes the timer.

Just use set_timer_interval.

You can’t. But, you can stop this timer, and start a new one with a different frequency and same handler.

Create and start the timer again.

Just run create_timer. It will change the timer.

1 point
4.How many timers can you have running at once?

0

1

Unlimited

1 point
5.The function time.time() is used in Python to keep track of time. What unit of time is associated with the value returned by time.time()? Hint: Look in the documentation.

Milli-second

Second

Minute

Hour

1 point
6.In Python, the time module can be used to determine the current time. This module includes the method time which returns the current system time in seconds since a date referred as the Epoch. The Epoch is fixed common date shared by all Python installations. Using the date of the Epoch and the current system time, an application such as a clock or calendar can compute the current time/date using basic arithmetic.

Write a CodeSkulptor program that experiments with the method time.time() and determines what date and time corresponds to the Epoch. Enter the year of the Epoch as a four digit number. (Remember to import time.)

1 point
7.The Python code below uses a timer to execute the function update() 10 times, computing a good approximation to a common mathematical function. Examine the code, and run it while varying the input value n.

What is the common name for what this computes?

Multiplication by 2: 2n

Exponentiation: 2n

Cosine of n

Logarithm base 2

Square: n2

Multiplicative inverse: 1/n

Square root of n

1 point
8.Given any initial natural number, consider the sequence of numbers generated by repeatedly following the rule:

divide by two if the number is even or
multiply by 3 and add 1 if the number is odd.
The Collatz conjecture states that this sequence always terminates at 1. For example, the sequence generated by 23 is:

23, 70, 35, 106, 53, 160, 80, 40, 20, 10, 5, 16, 8, 4, 2, 1

Write a Python program that takes a global variable n and uses a timer callback to repeatedly apply the rule above to n. Use the code from the previous question as a template. I suggest that your code prints out the sequence of numbers generated by this rule. Run this program for n = 217. What is the largest number in the sequence generated by this starting value?

To test your code, starting at n = 23 generates a sequence with a maximum value of 160.

1 point
9.CodeSkulptor runs your Python code by converting it into Javascript when you click the “Run” button and then executing this Javascript in your web browser. Open this example and run the provided code. If the SimpleGUI frame is spawned as a separate window, you should see an animation of an explosion in the canvas for this frame. If the SimpleGUI frame is spawned as a separate tab on top of the existing window containing the code (as happens in some browser configurations), the animation will “freeze” and a single static image is displayed. (If the SimpleGUI frame spawns as a separate window, you can also cause the animation to freeze by opening a new tab on top of the code window.)

As explained in the FAQ (check the Resources tab on the left), what is the explanation for this behavior?

Modern browser don’t support running Javascript in multiple windows simultaneously. This situation causes the animation to freeze.

To save resources, modern browsers only execute the Javascript associated with the topmost tab of a window. The animation freezes since the code tab and its associated Javascript is no longer the topmost tab.

Javascript and Python are incompatible languages. As a result, the Python in one tab can’t run at the same time as the Javascript in the SimpleGUI frame.

## Week 5 Week 4 - Lists, keyboard input, the basics of modeling motion

Learn the basics of lists in Python, model moving objects in Python, recreate the classic arcade game “Pong”

### Week 4a - Basics of Lists

#### Quiz: Quiz 4a9 questions

QUIZ
Quiz 4a
9 questions
To Pass70% or higher
Attempts3 every 8 hours
November 19, 11:59 PM PST

1 point
1.One of the tasks that you will engage in when learning a new programming language is locating the name of a built-in function that performs a common, simple operation. While you might be tempted to write your own code that performs this operation, locating a built-in function is usually preferable since the built-in version is automatically correct and others that read your code will immediately recognize what your code is doing.

Python has a built-in function that adds up the numbers in a list. For example, given the list [1, 2, 5, 4], this function returns 1 + 2 + 5 + 4 = 12. Use your search skills to find the name of this built-in function. Enter the name of the built-in function below, without any parentheses or arguments.

(Note that we could just tell you the name of this function. However, the point of this problem is for you to start learning how to locate useful language features on your own.)

1 point
2.Let my_list be the list [“This”, “course”, “is”, “great”].

What is len(my_list)?
What non-negative number is the index of “great”? I.e., how would you replace the question marks in my_list[???] so that the resulting value is “great”?
Submit two numbers, one for each of these two questions, separated by spaces.

1 point
3.Let my_list be the list [“This”, “course”, “is”, “great”].

We can use Python’s slice notation to get part of this list. What non-negative numbers can be used to get the slice [“course”, “is”]? I.e., what two non-negative numbers should we put in my_list[??? : ???] to get that result?

Submit the two numbers in order, separated only by spaces.

1 point
4.If we want to split a list my_list into two halves, which of the following uses slices to do so correctly?

More precisely, if the length of my_list is 2n, i.e., even, then the two parts should each have length n. If its length is 2n+1, i.e., odd, then the two parts should have lengths n and n+1.

my_list[: len(my_list) // 2] and my_list[len(my_list) // 2 :]

my_list[0 : len(my_list) // 2] and my_list[len(my_list) // 2 + 1 : len(my_list)]

my_list[: len(my_list) // 2 - 1] and my_list[len(my_list) // 2 :]

my_list[0 : len(my_list) // 2] and my_list[len(my_list) // 2 : len(my_list)]

1 point
5.What is the distance between point [4, 7] and the nearest point on the circle centered at [2, 9] with radius 2? Provide at least 4 digits of accuracy.

Hint: The distance between a point and a circle is the distance between the point and the center of the circle minus the radius of the circle. You can use the point-to-point distance code described in this week’s videos.

1 point
6.A ball with velocity [4, 2] reflects off a vertical wall. What is its new velocity?

[-4, 2]

[4, -2]

[4, 2]

[-4, -2]

1 point
7.Which of the following illustrate how to properly structure a keydown or keyup event handler? (For more advanced Python programmers, assume that you have just imported simplegui and haven’t used from.)

1 point
8.Assume you have a program with a keydown handler. You run it, and press a single key and hold it down continuously. How many times does the keydown handler get called?

Experiment in CodeSkulptor to find out.

2 — once at the beginning and once when you release the key

1

Unlimited — i.e., repeatedly until you finally release the key

1 point
9.Several keys on the keyboard, such as Shift, CapsLock, and Ctrl, typically act to modify what happens when you press other keys, rather than doing anything on their own. When using the SimpleGUI keydown handler, how are such keys treated?

Experiment in CodeSkulptor to find out.

Independent key press events — e.g., pressing Shift by itself creates an event

No effect — e.g., pressing the Shift key does not create or modify the behavior of any event.

Modify other key presses — e.g., pressing the ‘a’ key creates an event with a different value than pressing Shift and ‘a’ together.

### Week 4b - Keyboard Control

#### Quiz: Quiz 4b9 questions

QUIZ
Quiz 4b
9 questions
To Pass70% or higher
Attempts3 every 8 hours
November 19, 11:59 PM PST

1 point
1.In Python, [1, 2, 3] is of type list. What is the name of the type of (1, 2, 3)?

Pair

Triple

Array

Tuple

Set

1 point
2.Which of the following types of data are immutable in Python?

Tuples

Strings

Numbers

Lists

Booleans

1 point
3.Which of the following functions must include a global point declaration in order to change the global variable point?

function2

function1

1 point
4.Consider the following three similar programs. Read them carefully to observe their differences.

We would like to know whether these all accomplish the same thing. What are the three values, respectively, printed by these three pieces of code? Separate the values only with spaces.

1 point
5.In our program, the variable position represents a 2D position on the canvas. We want to be able to change the position by some amount in variable delta. Why is the following code snippet incorrect?

Note that the ellipses represent that we might have code in between what is shown, but such code is irrelevant and omitted.

The numbers in position cannot be changed.

One of the elements of delta is negative.

The + operator on lists does not mean addition of the numbers in a list.

Lists do not support the + operator.

1 point
6.Consider the following program.

At the end of this code, to how many list objects do the variables refer?

If you run the code and print the variables’ values, you can begin to answer this question. After all, if two variables print differently, they certainly can’t refer to the same object. However, if two variables print the same, you still need to determine whether they refer to the same object. One way is to step through the code while drawing reference diagrams. Another is to mutate one and see if others also mutate.

1 — The four variables each refer to the same list.

3

2

4 — The four variables each refer to different lists.

1 point
7.Convert the following specification into code. Do the point and rectangle ever overlap?

A point starts at [10, 20]. It repeatedly changes position by [3, 0.7] — e.g., under button or timer control. Meanwhile, a rectangle stays in place. Its corners are at [50, 50] (upper left), [180, 50] (upper right), [180, 140] (lower right), and [50, 140] (lower left).

To check for overlap, i.e., collision, just run your code and check visually. You do not need to implement a point-rectangle collision test. However, we encourage you to think about how you would implement such a test.

Yes

No

1 point
8.Assume we are using acceleration control for a spaceship in a game. That is, we regularly have the following updates:

The position is incremented by the time interval multiplied by the velocity. This happens on each draw event.
The velocity is incremented by the time interval multiplied by the acceleration. This happens on each draw event.
The acceleration is periodically incremented by some fixed vector (the same vector for each step). This could happen on keyboard or timer events.
Assume that, initially, the ship is stationary and subject to no acceleration. What sort of trajectory will the spaceship fly in?

Either figure this out mathematically, or implement it in CodeSkulptor and see what happens.

Unpredictable

A non-linear, smooth curve

Spiral

A straight line

1 point
9.Write a Python program that initializes a global variable to 5. The keydown event handler updates this global variable by doubling it, while the keyup event handler updates it by decrementing it by 3.

What is the value of the global variable after 12 separate key presses, i.e., pressing and releasing one key at a time, and repeating this 12 times in total?

To test your code, the global variable’s value should be 35 after 4 key presses.

# An Introduction to Interactive Programming in Python (Part 2)

Lecture slides can be found [here]
Coursera can be found here

About this course: This two-part course is designed to help students with very little or no computing background learn the basics of building simple interactive applications. Our language of choice, Python, is an easy-to learn, high-level computer language that is used in many of the computational courses offered on Coursera. To make learning Python easy, we have developed a new browser-based programming environment that makes developing interactive applications in Python simple. These applications will involve windows whose contents are graphical and respond to buttons, the keyboard and the mouse.

In part 2 of this course, we will introduce more elements of programming (such as list, dictionaries, and loops) and then use these elements to create games such as Blackjack. Part 1 of this class will culminate in building a version of the classic arcade game “Asteroids”. Upon completing this course, you will be able to write small, but interesting Python programs. The next course in the specialization will begin to introduce a more principled approach to writing programs and solving computational problems that will allow you to write larger and more complex programs.

## Week 5 - Mouse input, list methods, dictionaries

### Week 5a - Mouse Input and More Lists

#### Quiz: Quiz 5a9 questions

QUIZ
Quiz 5a
9 questions
To Pass70% or higher
Attempts3 every 8 hours
November 19, 11:59 PM PST

1 point
1.What is the type of the parameter for a mouseclick handler?

Refer to the CodeSkulptor documentation.

There is no parameter.

Boolean

String

Number

List

Tuple

1 point
2.Which of the following expressions mutate, i.e., change, list my_list? If you’ve forgotten what the operations do, you can look in the CodeSkulptor documentation.

my_list + [10, 20]

my_list.reverse()

my_list.append(10)

another_list.extend(my_list)

my_list.extend([10, 20])

1 point
3.We want to remove the element at the front of a list. For example, we want the following code to print “apple” and [“pear”, “blueberry”], respectively. What function or method call should replace the question marks?

fruits.remove(0)

fruits[1:]

fruits[0]

fruits.pop(0)

fruits.pop()

fruits.remove(“apple”)

1 point
4.Which of the following uses of range() will generate the list [2, 5, 8, 11, 14]?

First, think about what each of these returns, but also try each in CodeSkulptor.

range(2, 15) * 3

range(1, 15, 3)

range(2, 15, 3)

1 point
5.To correctly compute the product of a list numbers of numbers, what statement should replace the question marks?

product = numbers[1]

product = numbers[0]

product = 1

product = []

product = 0

1 point
6.We can loop over strings, too!

The following incomplete function is a simple, but inefficient, way to reverse a string. What line of code needs to replace the questions marks for the code to work correctly?

result = []

result = “”

result = 0

result = “ “

1
point

1. Imagine a game on a map. At the beginning, we might want to randomly assign each player a starting point. Which of the following expressions may we use in place of the question marks to correctly implement this functionality?

point.append(points)

points.append(point)

points + point

points += point

points.extend(point)

point.extend(points)

1 point
8.The following function is supposed to check whether the given list of numbers is in ascending order. For example, we want is_ascending([2, 6, 9, 12, 400]) to return True while is_ascending([4, 8, 2, 13]) should return False.

However, the function doesn’t quite work. Try it on the suggested tests to verify this for yourself. The easiest fix is to make a small change to the highlighted code. What should it be replaced with?

range(len(numbers)) - 1

range(len(numbers) - 1)

range(len(numbers - 1))

range(1, len(numbers))

1 point
9.Turn the following English description into code:

Create a list with two numbers, 0 and 1, respectively.
For 40 times, add to the end of the list the sum of the last two numbers.
What is the last number in the list?

To test your code, if you repeat 10 times, rather than 40, your answer should be 89.

### Week 5b - Dictionaries and Images

#### Quiz: Quiz 5b9 questions

QUIZ
Quiz 5b
9 questions
To Pass70% or higher
Attempts3 every 8 hours
November 19, 11:59 PM PST

1 point
1.Which of the following expressions corresponds to a dictionary with no elements?

()

{}

None

[]

<>

dict()

1 point
2.Given an existing dictionary favorites, what Python statement adds the key “fruit” to this dictionary with the corresponding value “blackberry”?

favorites{“fruit” : “blackberry”}

favorites[“fruit” = “blackberry”]

favorites[“fruit” : “blackberry”]

favorites[“fruit”] = “blackberry”

favorites = {“fruit” : “blackberry”}

1 point
3.Keys in a dictionary can have which of the following types?

Lists

Booleans

Strings

Dictionaries

Numbers

Tuples

1 point
4.Values in a dictionary can have which of the following types?

Strings

Booleans

Tuples

Dictionaries

Numbers

Lists

1 point
5.We often want to loop over all the key/value pairs in a dictionary. Assume the variable my_dict stores a dictionary. One way of looping like this is as follows:

However, there is a better way. We can instead write the following:

What code should replace the question marks so that the two forms are equivalent?

Refer to the video on dictionaries or the CodeSkulptor documentation.

list(my_dict)

my_dict.values()

my_dict.items()

my_dict.keys()

my_dict.keys_values()

items(my_dict)

1 point
6.Conceptually, the purpose of a dictionary is to represent a relationship between two collections of data — each key in the dictionary is related to one value. Which of the following situations are instances of such a relationship?

Do not include situations where you have to introduce additional information in order to fit them into such a relationship.

Storing where each person lives

Storing a sensor’s data samples

Storing x and y coordinates of an arbitrary collection of 2-dimensional points

Storing x and y coordinates of 2-dimensional points taken from a function, so that each x coordinate occurs at most once.

1 point
7.In the previous quiz, you were asked to complete the following code:

Now, we want to rewrite starting_points using a list comprehension. Which list comprehensions could replace the following question marks?

Refer to this week’s “Visualizing iteration” video for examples of list comprehensions. Also, try each example in CodeSkulptor before answering the question.

[random_point for players]

[random_point(player) for player in players]

[for player in players: random_point()]

[random_point() for player in players]

[random_point() for p in players]

[random_point for player in players]

1 point
8.You have the following code. The goal is to display a portion of the image, rescaling it to fill the canvas.

Run it, and observe that nothing is displayed in the frame. What is the problem?

The source arguments in draw_image are incorrect. We are trying to load pixels that are not within the image, and thus the draw fails.

The destination arguments in draw_image are incorrect. We aren’t specifying values that would draw the image on this size canvas.

The file doesn’t exist.

The file is not an image.

One or more of the draw_image arguments are of the wrong type.

1 point
9.Write a CodeSkulptor program that loads and draws the following image:

with a source center of [220, 100] and a source size of [100, 100]. What one word appears in the canvas? If a letter is capitalized in the image, enter it as a capital.

Note that you do have to position the image as stated to see the correct word.

## Week 6 - Classes and object-oriented programming

Learn the basics of object-oriented programming in Python using classes, work with tiled images

### Week 6a - Classes

#### Quiz: Quiz 6a8 questions

QUIZ
Quiz 6a
8 questions
To Pass70% or higher
Attempts3 every 8 hours
November 26, 11:59 PM PST

1 point
1.Every class definition should include an initializer method. What is the name of the initializer method?

Refer to the first object-oriented programming video.

Note: While you can get away with not having an initializer method, doing so almost always implies using techniques beyond the scope of this course or bad program design. So, beginners should always define an initializer method.

init

The same as the name of the class

init (1 underscore on each side)

init (2 underscores on each side)

1 point
2.In Python, what is the main difference between a function and a method?

Methods are defined in built-in library modules, while functions are defined in your own code.

There is no difference. They are interchangeable terms.

Functions are defined outside of classes, while methods are defined inside of and part of classes.

Methods have a parameter named self, while functions do not.

1 point
3.As an example class, consider the following code from one of the videos:

What does the self parameter represent?

An object (instance) of the Character class

Whatever happens to be passed to it.

The method that is being defined

The Character class

1 point
4.Assume you have the following class and method definition, parts of which have been omitted.

The last line defines the variable my_object as an object of My_Class class. Which of the following is proper syntax for using the method on this object?

My_Class.my_method(my_object, 1, 2)

my_method(my_object, 1, 2)

My_Class.my_object.my_method(1, 2)

my_object.my_method(1, 2)

my_method(My_Class, 1, 2)

1 point
5.We want to have balls that move around. Which of the following designs represents encapsulation best?

1 point
6.A common feature in many object-oriented languages is method overloading. In this quiz question, you will learn by example what overloading is and whether or not Python supports it.

Turn the following English description into code.

Start a class definition. We’ll call the class Overload.
Define an init method. Along with the standard self it has one parameter. The method does nothing useful for this example — use the Python do-nothing statement pass for the body.
Define a second init method. Along with self it has two parameters. This method also does nothing useful.
Outside of the class, we want to create two Overload objects. If Python supports overloading, you will be able to create an Overload object with one argument, and create another Overload object with two arguments. Does Python support overloading?

No

Yes

1 point
7.First, complete the following class definition:

The deposit and withdraw methods each change the account balance. The withdraw method also deducts a fee of 5 dollars from the balance if the withdrawal (before any fees) results in a negative balance. Since we also have the method get_fees you will need to have a variable to keep track of the fees paid.

Here’s one possible test of the class. It should print the values 10 and 5, respectively, since the withdrawal incurs a fee of 5 dollars.

Copy-and-paste the following much longer test. What two numbers are printed at the end? Enter the two numbers, separated only by spaces.

1 point
8.We will again use the BankAccount class from the previous problem. You should be able to use the same definition for both problems.

Of course, a bank with only one account will go out of business, so we want our BankAccount class to work correctly with many accounts. Naturally, each bank account should have its own balance, with deposits and withdrawals going to the appropriate account. Similarly, the penalty fees for each account should be kept separate.

Here’s one possible test with multiple accounts. It should print the values 10, 5, 5, and 0.

Copy-and-paste the following much longer test. What four numbers are printed at the end? Enter the four numbers, separated only by spaces.

### Week 6b - Tiled Images

#### Quiz:Quiz 6b8 questions

QUIZ
Quiz 6b
8 questions
To Pass70% or higher
Attempts3 every 8 hours
November 26, 11:59 PM PST

1 point
1.What is the position of the center of the top-left card (Ace of Clubs, A♣) in the tiled image discussed in the “Tiled images“ video? Remember that each card in this tiled image has size 73 x 98 pixels.

(Note that the tiled image used in the current version of your Blackjack mini-project is slightly smaller.)

(36.5, 49)

(5 73 + 36.5, 1 98 + 49)

(0, 0)

(73, 98)

1 point
2.What is the position of the center of the bottom-right card (King of Diamonds, K♦) in the tiled image discussed in the “Tiled images” video? Again, remember that each card in this tiled image has size 73 x 98 pixels.

Enter two numbers, separated only by spaces.

1 point
3.When using Dropbox to store images for use with CodeSkulptor, what should the www portion of the DropBox URL be replaced by?

Refer to the video on tiled images.

dl

jpg

www

html

gif

1 point
4.Within the init method, the new object should be returned with what code?

return whatever_the_object_is_named (Use the appropriate variable name.)

No return statement is needed in init.

return

return self

1 point
5.One way of understanding code is to think about other code that accomplishes the same thing — i.e., given the same starting values, it returns and/or mutates the same values.

This following defines one way to concatenate multiple lists. For example, list_extend_many([[1,2], [3], [4, 5, 6], [7]]) returns [1, 2, 3, 4, 5, 6, 7] and doesn’t mutate anything.

Which of the following definitions are equivalent? I.e., which always produce the same output for the same input, and never mutate the input or any global variable?

1 point
6.Which of the following programs would never end if it weren’t for CodeSkulptor’s timeout? Assume no break or return statement is used in the elided loop bodies.

You might want to add a print statement to each loop to better understand the behavior.

1 point
7.Convert the following English description into code.

Initialize n to be 1000. Initialize numbers to be a list of numbers from 2 to n but not including n.
With results starting as the empty list, repeat the following as long as numbers contains any numbers.
Add the first number in numbers to the end of results.
Remove every number in numbers that is evenly divisible by (has no remainder when divided by) the number that you had just added to results.
How long is results?

To test your code, when n is instead 100, the length of results is 25.

1 point
8.We can use loops to simulate natural processes over time. Write a program that calculates the populations of two kinds of “wumpuses” over time. At the beginning of year 1, there are 1000 slow wumpuses and 1 fast wumpus. This one fast wumpus is a new mutation. Not surprisingly, being fast gives it an advantage, as it can better escape from predators. Each year, each wumpus has one offspring. (We’ll ignore the more realistic niceties of sexual reproduction, like distinguishing males and females.). There are no further mutations, so slow wumpuses beget slow wumpuses, and fast wumpuses beget fast wumpuses. Also, each year 40% of all slow wumpuses die each year, while only 30% of the fast wumpuses do.

So, at the beginning of year one there are 1000 slow wumpuses. Another 1000 slow wumpuses are born. But, 40% of these 2000 slow wumpuses die, leaving a total of 1200 at the end of year one. Meanwhile, in the same year, we begin with 1 fast wumpus, 1 more is born, and 30% of these die, leaving 1.4. (We’ll also allow fractional populations, for simplicity.)

Beginning of Year Slow Wumpuses Fast Wumpuses
1 1000 1
2 1200 1.4
3 1440 1.96

Enter the first year in which the fast wumpuses outnumber the slow wumpuses. Remember that the table above shows the populations at the start of the year.

## Week 7 - Basic game physics, sprites

Understand the math of acceleration and friction, work with sprites, add sound to your game

### Week 7a - More Classes

#### Quiz: Quiz 7a7 questions

QUIZ
Quiz 7a
7 questions
To Pass70% or higher
Attempts3 every 8 hours
December 3, 11:59 PM PST

point 1. Question 1
Let’s define a class for 2-dimensional points.

Which of the following code snippets are valid usages of the Point2D initializer and its translate method? For your first attempt at this problem, we suggest that you try to answer without using CodeSkulptor.

point 2. Question 2
Let’s continue to use the same class for 2-dimensional points.

Which of the following code snippets are valid usages of the Point2D initializer and its translate method? For your first attempt at this problem, we suggest that you try to answer without using CodeSkulptor.

point 3. Question 3
Now, let’s make this class definition for 2-dimensional points more specific.

For the Point2D class above, having only the three methods shown, which of the following code snippets are valid usages of the Point2D class? For your first attempt at this problem, we suggest that you try to answer without using CodeSkulptor.

point 4. Question 4
In SimpleGUI, the function draw_image takes an optional sixth parameter that determines the angle of rotation of the destination rectangle around its center. Do positive values for the angle rotate the image clockwise or counterclockwise? Is the angle specified in degrees or radians?

Refer to the CodeSkulptor documentation.

counterclockwise, degrees

clockwise, degrees

point 5. Question 5
One interesting extension of Rice Rocks would be to have two ships, with each controlled by a separate player, instead of one single ship. Using the provided class definitions, what is the best way to represent the two ships in this new variant?

Add another call to the Ship constructor, assigning the result to another global variable.

In the Ship class definition, change the variables pos, vel, angle to be lists of two values each. Then, change each method to take an additional number argument that indicates which ship should be used.

Thus, when we call the constructor now, we are creating both ships.

Copy the Ship class code, e.g.,

Then create two ship objects, one of each class, assigning each to a global variable.

In the Ship class definition, duplicate every method. For example, Ship.draw1(…) would be used to draw the first ship, while Ship.draw2(…) would be used to draw the second ship.

point 6. Question 6
Which of the following browsers fully support MP3 audio files? Refer to the CodeSkulptor documentation.

Chrome

Firefox

Safari

point 7. Question 7
Consider a spaceship where the ship’s thrusters can accelerate the ship by 10 pixels per second for each second that the thrust key is held down. If the friction induces a deceleration that is 10% of the ship’s velocity per second, what is the maximal velocity of the ship? If you are having trouble, consider writing a short program to help understand this problem.

Around 100 pixels per second

Around 10 pixels per second

The ship has no maximal velocity. It can reach any velocity the player desires if you hold the thrust key down long enough.

Around 1000 pixels per second

Correct
At a velocity of 100 pixels per second, friction would induce a deceleration of 10 pixels per second. This deceleration would exactly cancel an acceleration of 10 pixels per second from the thrusters. We used “around” here since the true maximal velocity depends on the rate at which the frame is drawn.

### Week 7b - Sprites

#### Quiz: Quiz 7b9 questions

QUIZ
Quiz 7b
9 questions
To Pass70% or higher
Attempts3 every 8 hours
December 3, 11:59 PM PST

1 point

1. Question 1
The class code provided for this week’s mini-project supports an ImageInfo class to organize the data associated with the image. Consider an ImageInfo object of the following form:

What is the radius of the shape associated with this ImageInfo object?

1 point 2. Question 2
Consider the provided ImageInfo and Sprite class code. Assume we want ten asteroids on the screen, each looking exactly alike and using the same image file. How many ImageInfo objects and how many Sprite objects should we create?

ten ImageInfo objects, ten Sprite objects

ten ImageInfo objects, one Sprite object

one ImageInfo object, ten Sprite objects

one ImageInfo object, one Sprite object

1 point 3. Question 3
The version of Rice Rocks that we will implement uses only a single asteroid image and spawns multiple instances of the provided Sprite class using this image. In the original Asteroids, a large asteroid split into two medium asteroids which themselves split into two small asteroids.

If we only had one image and wanted to implement asteroids of varying sizes in our version, how should we do this?

Store the size in a global variable. Use this variable when drawing a sprite.

Add a size attribute in the Sprite class and a size parameter to Sprite.init. Use the size attribute when drawing the sprite.

Add a size attribute in the ImageInfo class and a size parameter to ImageInfo.init. Use this attribute when drawing the sprite.

Store a list of sizes for each asteroid in a global variable. Use the corresponding size when drawing a sprite.

1 point 4. Question 4
What is the supported range of sound volumes in set_volume? You can find out in the CodeSkulptor documentation.

0 to 1

0 to 10

-1 to 1

1 to 100

1 point 5. Question 5
Assume you have code that loads and plays a sound. Unfortunately, you don’t hear anything. Which of the following could be a reason?

The given URL exists, but is inaccessible due to network problems.

A file found with the given URL isn’t a sound file recognized by your browser.

You have set the volume level to 0.

No file is found with the given URL.

1 point 6. Question 6
Which of the following are valid HTML representations of the color blue?

“#0000FF”

“rgb(0, 0, 255)”

“purple”

“#FFFF00”

“Blue”

1 point 7. Question 7
Imagine we are writing code for something like Rice Rocks, where things are moving in 2D toroidal space, i.e., the wrap around all four sides of the screen. How can we eliminate the duplicated code in the following function?

1 point 8. Question 8
What is the primary reason for not duplicating code? It was the only reason mentioned in the Programming Tips #7 video.

You only need to get the code correct once.

It takes less time to write the code.

1 point 9. Question 9
What is Mike Massimino’s greatest accomplishment?

Fixing the Hubble Space Telescope in space

Being the first person to use Twitter in space

Receiving his PhD from MIT

Appearing on The Big Bang Theory

Appearing on An Introduction to Interactive Programming in Python

## Week 8 - Sets and animation

Learn about sets in Python, compute collisions between sprites, animate sprites

### Week 8b - Animation

#### Quiz: Quiz 89 questions

QUIZ
Quiz 8
9 questions
To Pass70% or higher
Attempts3 every 8 hours
December 10, 11:59 PM PST

Question 11 point
1.Question 1
Which of the following is valid notation for a set in CodeSkulptor?

{1,2,3}

set([1, 2, 3])

set([])

Question 21 point
2.Question 2
Which of the following operations can mutate set s? You may want to try some examples in CodeSkulptor and refer to the documentation.

s.intersection_update(s)

t.symmetric_difference(s)

s.update(t)

t.update(s)

s.difference(t)

Question 31 point
3.Question 3
Which of the following always give the same result as s.union(t)?

Refer to the CodeSkulptor documentation or try them on examples.

s.intersection(s.union(t))

s.union(s.symmetric_difference(t))

s.update(t)

s.union(t.difference(s))

Question 41 point
4.Question 4
A set is an unordered collection of distinct elements. Which of the following problem contexts represent instances of this idea?

Names for everyone taking this course

Group of distinct cities

Alphabetized names

1 point
5.Question 5
How many frames per second are typically projected in modern movies? How many times per second is the draw handler typically called in CodeSkulptor?

Enter two numbers representing these frame rates in frames per second. Use only spaces to separate the numbers.

Question 61 point
6.Question 6
For this week, the mini-project defines and uses a Sprite class to support animations. What attribute (also known as a field) can be used to help index the sub-images forming an animated sprite? (If you are stuck, review the bonus phase in the mini-project description.)

image_center

lifespan

animated

angle

pos

sound

age

image

image_size

angle_vel

imagecenter imagesize pos

Question 71 point
7.Question 7
Consider a horizontally-tiled image where each sub-image has the same size. If each sub-image is of size 60×90 (in pixels), what is the horizontal distance (in pixels) between the centers of adjacent sub-images?

90

180

120

60

1 point
8.Question 8
How many distinct numbers are printed by the following code? Enter the count.

Hint: Consider how editing the code to use a set could help solve the question.

Question 91 point
9.Question 9
Which instructor exhibits the best coding style?

Scott

Joe

John

Stephen

### Post-class

#### Beyond CodeSkulptor15 min

https://www.python.org/

#### Class Wrap-up4 min

https://www.coursetalk.com/providers/coursera/courses/an-introduction-to-interactive-programming-in-python/write-review

https://www.class-central.com/review/new/408

##

Learn the basics of object-oriented programming in Python using classes, work with tiled images

# Principles of Computing (Part 1)

Lecture slides can be found [here]
Coursera can be found here

About this course: This two-part course builds upon the programming skills that you learned in our Introduction to Interactive Programming in Python course. We will augment those skills with both important programming practices and critical mathematical problem solving skills. These skills underlie larger scale computational problem solving and programming. The main focus of the class will be programming weekly mini-projects in Python that build upon the mathematical and programming principles that are taught in the class. To keep the class fun and engaging, many of the projects will involve working with strategy-based games.

In part 1 of this course, the programming aspect of the class will focus on coding standards and testing. The mathematical portion of the class will focus on probability, combinatorics, and counting with an eye towards practical applications of these concepts in Computer Science.

Recommended Background - Students should be comfortable writing small (100+ line) programs in Python using constructs such as lists, dictionaries and classes and also have a high-school math background that includes algebra and pre-calculus.

#

Lecture slides can be found [here]
Coursera can be found here

primary

#

Lecture slides can be found [here]
Coursera can be found here

primary

#

Lecture slides can be found [here]
Coursera can be found here

primary