Test 1 Review Guide

Test date: Wednesday, September 28, 2016
Test location: normal lecture hall (you MUST go to your assigned section)
Test duration: 50 minutes (for 1110 and 1111)
Test format: writing on paper; bring pen/pencil (and nothing else)
Review session: Tuesday, September 27, 5:00-6:00 PM in Chem 402 (TA Office Hours are canceled during the review session)

Review Guide

General Points:

  • There will be several coding questions; problem solving will be involved.
  • One coding question will be a "big" coding question, along the lines of a simple POTD.
  • Other coding questions will ask for a couple lines of code, such as an if else statement.
  • You should be able to read code and interpret what it is doing.
  • There will be a mix of other types of questions: multiple choice, short answer, fill-in-the-blank, etc.

Not on the test:

  • Drawing with the turtle will not be on the test
  • You do not have to know what to import to get access to various things (we will provide this for you)

CS in General:

  • Where do we see computers in the world?
  • What is ambiguity? What has that got to do with CS?
  • Why is it important for people to have a basic understanding of computing?

Primitives and Types:

  • Know the basic primitive types (int, float, bool, str)
  • Know the basic mutable collection types (list and dictionary)
  • Know how casting works (i.e., how to turn a str into an int)
  • Know the operators, including %, +=, /, //, and the various comparison and boolean operators (!=, not, or, and)
  • Know how to declare a variable and change what is inside it
  • Know how to get a random integer
  • Know how to get input from the user
  • Know the basic methods for use with lists and dictionaries
  • Know how to split a string into a list
  • Know how to access items in a list or dictionary

Decision structures:

  • Know how to write if, if-elif, and if-elif-else statements
  • Know how to interpret code that uses if, if-elif, and if-elif-else statements, including ifs inside of other ifs
  • Know how scope works: a variable declared inside an if cannot be seen if that if statement never executes

Loops:

  • Know how to write while loops - checking for a condition and also for verifying user input
  • Know how to write for loops - both using range() and over a list

Study Hints

Practice problems

Here are some problems you can practice with (however, we do not have the solutions available - you can probably Google for them):

  • Chapter 3 (p. 116): 5, 8, 9, 12, 13, 14
  • Chapter 4 (p. 161): 1, 2, 8, 11, 12
  • Chapter 7 (p. 334): 1, 2, 4, 6

Practice coding on paper

You'll be writing code on paper. This feels different than writing it in PyCharm. You don't want to be surprised by how different it feels. Practice writing code by hand.

A few small syntax errors is OK. But if you are really off we will take off points. Try to write correct code.

We'll give you any imports you might need - so don't worry about memorizing those.

Try re-solving the POTD and Lab problems on paper without looking at your code or textbook.

You can find more sample problems in Programming Challenges in the textbook. We do not, however, have the answer key to share with you.

Also remember that speed matters. 50 minutes is not a long time.

Practice reading code

We will show you code and ask you what it does. Practice thinking through code without running it.

Review the Lectures

Not everything in the book is equally important. Review the lecture notes to see what we emphasized. If you are confused by some point, check the audio. You might want to listen to the audio of the other instructor (the one you didn't hear in class) so that you can get a different perspective on the material.

more ...

Lecture 14 (Sherriff) - Loops 2

Lecture Date: Friday, September 23

Today, we are going to do a bit more with loops and get ready for the test by looking at a some more uses for loops.

Some things we might try:

  • Old MacDonald
  • Calculating the trace of a matrix
  • Improving our grade calculator

Some example code:

animals = ['dog', 'cow', 'pig']
sounds = ['woof', 'moo', 'oink']

number_of_animals_left = len(animals)

while number_of_animals_left > 0:
    print("Little Sammy had a farm, E I E I O")
    print("And on that farm, she had a", animals[0], ", E I E I O")
    print("With a", sounds[0], sounds[0], "here, and a", sounds[0], sounds[0], "there")
    print("Here a", sounds[0], ", there a", sounds[0], ", everwhere a", sounds[0], sounds[0])
    print("Little Sammy had a farm, E I E I O")
    print()
    del animals[0]
    del sounds[0]
    number_of_animals_left -= 1

more ...

Lecture 13 (Sherriff) - Loops

Lecture Date: Wednesday, September 21

Often there is code that we want our programs to repeat. This could be to have the program process all the items in a list, or do a number of tasks in order, or any number of other reasons. Along with if statements, loops are a core decision and control structure to write effective programs.

There are several ways to write loops in Python. We'll discuss those all today.

  • while loop - a condition-controlled loop
  • for loop using the range operator- a count-controlled loop
  • for loop using the in operator with a list
  • while loops for input validation
  • nested loops

Here are some things we might try to build:

  • a shopping cart
  • the worst roman.py solution ever
  • average of a list of numbers
  • printing a square

Some code we did today in class:

num = int(input("number? "))
roman = ""
while num > 0:
   roman += "I"
   num -= 1
print(roman)


x = 10
while x > 5:
    print(x)
    x -= 1

word = ""
while not word == "stop":
    word = input("Give me a word (stop to stop): ")
    print("You said: " + word)

ask for number between 1 and 100 (inclusive)
if not in range, ask for another
if in range, print

number = -1
while number < 1 or number > 100:
    number = int(input("Give me a number between 1 and 100: "))
print(number)

number = -1
while number not in range(1,101):
    number = int(input("Give me a number between 1 and 100: "))
print(number)   
    for i in range(0,4): # [0,1,2,3]
       print(i)

students = ['Mark', 'Colin', 'Sammy', 'Sarah', 'Laurie']

for student in students:
   print(student)

for i in range(100,21,-5):
   print(i)

square = [[1,2,3],[4,5,6],[7,8,9]]

# print this:
# 1 2 3
# 4 5 6
# 7 8 9

row_to_print = ""

for row in square:
   for col in row:
       row_to_print += str(col) + "\t"
   print(row_to_print)
   row_to_print = ""

more ...

Lecture 12 (Sherriff) - Decisions

Lecture Date: Monday, September 19

More on if and else today.

Let's build a grade calculator!

Consider a few different ways of figuring out the letter grade:

  • several if statements
  • if-elif statement
  • by looking at the individual digits of the grade

Here's something to consider:

# Prompt the user

grade = int(input("What's your grade? "))

tens = grade // 10
ones = grade % 10

For example, we can intentionally leverage integer division to get the tens place of the grade. To get the ones place, we can use the modulus operator, which gives us the remainder after division.

Let's build a simple program together. Write a program called letter_grade.py that will take a list of grades, separated by spaces, and then calculate the average of those grades. Print to the screen the average along with the letter grade (according to our letter grade system found in the syllabus). The scores are not weighted in any way - just do a straight up average.

So, a run of the program might look like this:

Input your scores, separated by spaces: 90 80 78
Average: 82.667
Letter: B-

We will spend time today touching on the following:

  • Scope (and scope errors)
  • Reviews the logical operators: == != < > <= >= and or not
  • tracing code

Then, we'll start on loops if we have time, specifically while loops.

index = 1
while index < 10:
    print(index)
    index = index + 1 # or index += 1

# infinite = 1
# while infinite > -1:
#     print(infinite)
#     infinite += 1

value = 5
while value >= 0 and value <= 10:
    value = int(input("Give me a number less than 0 or greater than 10:"))

value2 = -1
while value2 <= -1 or value2 > 10: # this is the bad case
    value2 = int(input("Give me a number between 0 and 10: "))

list_of_names = ["mark" , "tom"]
while len(list_of_names) > 0:
    # do something

more ...

Lecture 11 (Sherriff) - Decisions

Lecture Date: Friday, September 16

Programs that start and then end without any choices to make are boring. If we are going to write a program to do anything interesting, it has to be able to make decisions based on the data it is seeing.

Enter the if statement.

Consider this situation:

ifstatement.png

Pretty straight forward. But how do we make the computer do something different based on the input?

First, how do we decide whether it is cold outside or not?

Well, we could ask the user:

temp = input("What is the temperature outside?: ")

This is good, but this doesn't yet tell us whether it is specifically cold or not. And that's different for everyone. So let's add this:

cold_threshold = 30

So, now let's test whether it is cold or not!

if temp <= cold_threshold: 
    wear_coat()
    wear_hat()
    wear_gloves()

There's another way we could do this - and that's with what's called a flag variable. A flag variable is a bool that we use to determine some sort of state. In this case, we would write it like this:

is_cold = False

if temp <= cold_threshold:
    is_cold = True

if is_cold:
    wear_coat()
    wear_hat()
    wear_gloves()

This makes the code a bit more readable, and is_cold can be easily reused later on.

Now, what if we had to make more of a decision here:

ifelsestatement.png

We could use our flag variable again, but now we will add another option to our if statement:

is_cold = False;

if temp <= cold_threshold:
    is_cold = True

if is_cold:
    wear_coat()

else:
    wear_shorts()

In this case, we must do one or the other. A simple if statement either will or will not execute. Here, if the if is not executed, then the else will be.

We can string more of these together as well!

if is_cold:
    wear_coat()

elif today_is_sunday:
    wear_blazer()

else:
    wear_shorts()

Now you are guaranteed to execute one of these three paths.

Let's improve our translation program from before. Here's where we left it:

dictionary = {"hello":"Yarrr!!"}

word = input("What word would you like translated?: ")
print(word + " translates to " + dictionary.get(word.lower(), 'N/A') + " in pirate speak")

Other points for today:

  • How to indent your code properly
  • Relational operators (<, >, ==, >=, <=, !=)
  • Nested if statements
  • How to test for your letter grade in the class
  • How to deal splitting an input
  • Adding to a dictionary

More code from today:

cold_threshold = int(input("What is your cold threshold? "))
current_temp = int(input("What is the current temp? "))
is_cold = False
pants_day = False

if current_temp < cold_threshold:
   is_cold = True

if is_cold and pants_day:
   print("Wear coat")
   print("Wear scarf")
   print("Wear pants")

if is_cold:
   print("Wear more pants")
else:
   print("Who needs pants?")

if is_cold:
   print("Wear more pants")
elif pants_day:
   print("Must wear pants on pants day!")
elif True:
   print("Yup, that's 1 == 1...")
else:
   print("Who needs pants?")

# < >
# <= >=
# ==
# not

Pirate Translator:

# 1. Ask the user for a word to translate
word = input("Word to translate: ")
# 2. Look up that word in a dictionary of words
pirate_dictionary = {"hello" : "yarr", "hi" : "ahoy!"}
# 3. Print the translation OR print that it does not exist

word_to_add = input("Give me a word and translation to add: ").split()
# if word exists, tell user it is already there
if word_to_add[0] in pirate_dictionary:
   print("That is already here")
else:
   pirate_dictionary[word_to_add[0]] = word_to_add[1]
# if word does not exist, add the word and translation

if word.lower() in pirate_dictionary:
   print("The translation is:", pirate_dictionary.get(word.lower(), "Not here!"))
else:
   print("I cannot translate that...")

more ...

Lecture 10 (Sherriff) - Dictionaries

Lecture Date: Wednesday, September 14

A dictionary is another mutable collection, like the list. However, there are some key differences that make it more useful in certain situations.

  • A dict is not ordered.
  • A dict is made up of key/value pairs.

Let's consider a phone book (remember those?). You look up someone's name and find out their phone number.

So:

phonebook = {'Mark':'434-982-2688', 'Amanda':'434-234-2566', 'Samantha':'434-877-3434'}

A typical thing you would do with such a data type is to search it for certain information and add and remove items. Let's look at some more example code and then we'll build a more interesting program together.

# Mark Sherriff (mss2x)

gradebook = {'mss2x':[99,98,80], 'tbh3f':[89,90,78], 'asb2t':[70,66,73]}

print(gradebook)
print(gradebook['mss2x'])

print('mss2x' in gradebook)
print('lat7h' in gradebook)

test_average = sum(gradebook['asb2t'])/len(gradebook['asb2t'])
print(test_average)
print(format(test_average, "0.2f"))

# Also consider a dictionary as a representation of an entity

employee = {'compid':'mss2x', 'name':'Mark Sherriff', 'dob':'11/09/79', 'year':10, 'room':401}

# methods you should probably know

# clear() - empties the dict
# get() - gets a particular value based on key
# items() - gets all the keys and values
# keys() - gets all the available keys
# pop(key) - gets a value, and deletes the key/value pair
# values() - gets all the values

# print(gradebook['mst3k']) - Throws an error since it's not there!
print(gradebook.get('mst3k', 'Key not available'))
print(gradebook.keys())

Let's build a language translator!

more ...

Lecture 9 (Sherriff) - Lists

Lecture Date: Monday, September 12

We pick up today with the data types that can hold other data types. Specifically, lists. Tons to get through today! Let's look at the code and learn as we go!

# Mark Sherriff (mss2x)

animals = ['cow', 'horse', 'sheep', 'dog', 'chicken', 'llama'] # make a new list!

print(animals) # you can print the list

print(animals[0]) # you can get particular items from the list using []
print(animals[1])
print(animals[0] == 'cow') # == checks to see if two things contain the same data
print(animals[0] is 'cow') # is checks to see if two things are actually the same thing (more later)
print(animals[-1]) # negative numbers start from the end of the list
print(animals[-2])

print('The ' + animals[0] + ' and the ' + animals[2] + ' sleep in the barn.') # concat also works!

list_of_lists = [['cow', 'horse'], [4, 5, 6, 7]] # You can have a list of lists!

print(list_of_lists[0]) # here's how you get a particular list
print(list_of_lists[0][1]) # here's how you get a particular item
print(animals[2:4]) # this is called a slice and returns part of a list
print(type(animals[2:4]))
print(animals[0:-1])
print(animals[3:]) # you can shortcut some of the numbers here
print(animals[:3])
print(len(animals)) # len tells you how many things are in a list
print(len(list_of_lists))
print(len(list_of_lists[1]))

letters = ['A', 'B', 'C']
numbers = [1 , 2, 3]
both = letters + numbers # you can concatenate lists together, even if they have different things in them!
print(both)
print(letters * 3) # you can also repeat lists!
del animals[3] # if you know the index, you can delete a particular item
print(animals)

print('cow' in animals) # in checks for whether something is in an list
print('dog' not in animals) # or is not in a list
print(animals.index('sheep')) # lists have methods to get the index...
animals.append('duck') # ... append ...
animals.insert(3,'pig') # ... insert ...
print(animals)
animals.remove('duck') # note this can use the item and not the index like del
print(animals)
animals.sort() # and sort!
print(animals)
animals2 = animals
animals2.append('goat')
print(animals) # note same as animals2 - points to same place in memory!

import copy # making copies can be hard...
animals3 = copy.copy(animals)
animals3.append('farmer')
print(animals3)
print(animals)

# Reading in a list of numbers from the user

names = []
names.append(input("Give me a name: "))
names.append(input("Give me another name: "))
print(names)

more ...

Lecture 8 (Sherriff) - Data Types

Lecture Date: Friday, September 9

Writing a program is like building with Legos.

Follow me on this: a program can be a large, complex thing, or a relatively small, compact thing. So can the things you build out of Legos. However, even the biggest Lego sculpture has something in common with the smallest little Lego building - they are both made with the same kinds of individual pieces. Sure, there are special pieces that only do certain things, but for the most part, it's (pardon the pun) all the same building blocks.

What are the component building blocks of writing programs? Data types. Specifically, each different type of block is a different data type. Each data type is a category that specifies what kind of data is stored within it.

In most programming languages, there is a set of built-in data types. The built-in data types for Python that we'll care most about include the following (there are others not included in this list as they are used for more specialized functions):

  • int - used for whole integer numbers
  • float - used for decimal numbers, also called floating point numbers (hence the float name)
  • str - used for strings, which is a sequence of characters
  • bool - short for boolean, used to hold either True or False
  • list - used to store multiple values of other data types in an ordered sequence
  • set - like a list, but unordered
  • dict - short for dictionary, this data type stores info in key/value pairs

int, float, and str are called immutable data types because once they are set, they cannot change their value. This doesn't mean you can't reassign a variable with this type - it just means that it is going to point to somewhere else in memory.

list, set, and dict are called mutable because they can be changed in the same place in memory.

We will review creating variables and how this is handled in memory.

Other topics we'll cover:

  • built-in methods, like len(), type(), int(), float(), str()
  • using mathematical operands with strings
  • checking for equality (name vs. content with is and ==)

Some example code:

# Mark Sherriff (mss2x)

hungry = True
ready_for_weekend = True

print(hungry == ready_for_weekend)

print("Mark" * 7)

string = "This is my name!"

number = 3

print(type(number))
print(type(str(number)))

floater = number + 4.34
print(type(floater))

print(type(number + 3))

print(type(number == 4))
print(number == 4)
print((number == 4) == False)
print(type((number == 4) == False))

print(number < 4)

print(number < 4 and type(number) == type(3))

print(number > 5 or type(number) == type(3))

print(type(type(number == 4)))

print(type(number) is int)

a = 'Mark'
b = "".join(['Ma', 'rk'])
print(a == b)
print(a is b)

more ...

Lecture 7 (Sherriff) - Input and Output

Lecture Date: Wednesday, September 7

Now that we are through the break-neck pace of trying out a lot of stuff with turtle, we're going to slow down and go step-by-step and see how we can put programs together.

Today, we'll focus on input and output with a program.

Let's first start by discussing literals. A literal is a value that appears in a program that is what it is. For instance, if I say:

print("Hello World!")

then "Hello World!" is a literal. It is the actual value of the thing it represents. In this case, we would call this a string. You can print any literal to the screen using the print method as shown above.

When we look at string literals, notice how it is surrounded by quotation marks. We'll examine that a bit more in class.

Next, we'll discuss variables and value assignment with the equals sign. What makes a good variable name? What can variables hold? Can they hold different types of items? We'll touch on dynamic vs. static typing. Then we'll discuss how to print them along with how to combine the printing of multiple items.

How do we get input from the user? Well, with the input command! We'll do some more examples here and do some basic arithmetic using Python.

The information for today's lecture comes from Chapter 2 of the Gaddis book.

# Mark Sherriff (mss2x)

print("Python is awesome!")
print('Python is awesome!')
print('"Python is awesome!"')

statement = "Python is awesomer!!!!"

print(statement)

statement = 4
print(statement)

number_of_slices_of_bacon = 100
badVariableName = "Java"

statement = 3.1419


# Write statements that do the following:
# add two integers
print(5 + 9)
print("Mark " + "Sherriff")

# multiply two floating point numbers
print(3.234243 * 56.2423423)

# divide two floating point numbers
print(9.5 / 2.3)
print(format(9.5 / 2.3, ".7f"))

# raise a integer to an integer power
print(2 ** 3)

# find the remainder of division of 25 / 6
print(25 % 6)

print(6 // 4)
print(6 / 4)

name = input("What is your name? ")
print("Hello, " + name)

number = input("Give me a number between 0 and 100: ")
print(type(number))
print(int(number) + 4)

more ...

Lecture 6 (Sherriff) - Turtles 2: The Fractaling

Lecture Date: Monday, September 5

We'll keep going with turtle today, finishing up whatever we didn't complete on Friday.

We'll also add some more excitement!

  • random colors
  • user input
  • how to draw a circle
  • how to draw a tree

More complete code for drawing shapes:

# Mark Sherriff (mss2x)

import turtle
import random

yurtle = turtle.Turtle()
yurtle.speed("fastest")
colors = ["green", "red", "yellow", "cyan", "orange", "pink"]

def draw_shape(my_turtle, x, y, num_sides, size):
   my_turtle.penup()
   my_turtle.goto(x,y)
   my_turtle.pendown()
   rand_color = random.randint(0, len(colors) - 1)
   my_turtle.color(colors[rand_color])
   my_turtle.begin_fill()
   for i in range(num_sides):
       my_turtle.forward(size)
       my_turtle.left(360/num_sides)
   my_turtle.end_fill()

# Add code to draw 20 squares on the screen at random locations
for i in range(2000):
   rand_x = random.randint(-300,300)
   rand_y = random.randint(-300,300)
   rand_size = random.randint(10,100)
   rand_sides = random.randint(3,12)
   draw_shape(yurtle, rand_x, rand_y, rand_sides, rand_size)

turtle.done()

Drawing a Tree Fractal:

# Mark Sherriff (mss2x)

import turtle

def draw_tree(t, depth, size):

    if depth == 0:
        return

    if depth == 1:
        t.color("green")
    else:
        t.color("black")
    t.forward(size-depth*2)
    t.left(40)
    t.forward(size-depth*2)
    draw_tree(t, depth-1, size-5)
    if depth == 1:
        t.color("green")
    else:
        t.color("black")
    t.back(size-depth*2)
    t.right(80)
    t.forward(size-depth*2)
    draw_tree(t, depth-1, size-5)
    if depth == 1:
        t.color("green")
    else:
        t.color("black")
    t.back(size-depth*2)
    t.left(40)
    t.back(size-depth*2)



tom = turtle.Turtle()
tom.left(90)
tom.penup()
tom.back(150)
tom.pendown()
tom.speed("fastest")
draw_tree(tom, 5, 20)

turtle.done()

Levy C Curve:

import turtle
import random

colors = ["green", "red", "blue", "yellow"]


def draw_levy(t, level, size):

    if level == 0:
        rand_num = random.randint(0,len(colors)-1)
        t.color(colors[rand_num])
        t.forward(size)
        return

    t.right(45)
    draw_levy(t, level-1, size)
    t.left(90)
    draw_levy(t, level-1, size)
    t.right(45)


tom = turtle.Turtle()
tom.up()
tom.goto(0,0)
tom.down()
tom.speed("fastest")
draw_levy(tom, 10, 5)


turtle.done()

more ...