Skip to content

Instantly share code, notes, and snippets.

@Renddslow
Last active January 31, 2020 18:02
Show Gist options
  • Save Renddslow/2c87d8eb722c9978c4ccbd65c9d6b947 to your computer and use it in GitHub Desktop.
Save Renddslow/2c87d8eb722c9978c4ccbd65c9d6b947 to your computer and use it in GitHub Desktop.
TCA Code Handouts

Week 1

In Class

Machine Code

machine code

  1. Hangman Game
  2. Repl

Take Home

Go back to the Repl we used in class:

  1. Read through the code here (all the files are on the left hand side). I DO NOT expect a lot (if any) of it to make sense yet, so don't be discouraged.
  2. Write down answers to the following questions:
    1. What is one observation you made reading the code?
    2. What is something that looks familiar?
    3. What is one thing that looks foreign?
  3. Figure out what file the random words that you guess in the game are coming from (all the words are in the same place).
  4. Change one of the words and play the game until you find that word.
  5. (Optional) Add a few words to the list and see if you come across them playing the game.

Email me the link to the repl, you can find it in the share menu:

share your repl

In addition to the link, send me the answers to the questions in step 2.

Helpful Reminders

Remember the files are all on the left hand side of the Repl

repl sidebar

To run the game, click on the green run button

run button

To stop the game, click on the stop button where the run used to be

stop button

Week 2

In Class

A variable is a reference to a location in memory that holds a value.

  1. Variables example 1 Repl
  2. Variables example 2 Repl

Take Home

This week you will have 6 exercises to make sure you've got the concept of variables on lock-down. Each exercise has its own Repl and all but the last example will need to have your version emailed to me. Make sure you hit Save before you send me the URL. The URL will not change over to be your URL if you do not hit save.

Specific instructions on how to complete each excercise can be found in the comments in each repl. Remember, in Python, a comment is any line that starts with a hash (#) character.

# This is a comment

foo = "Hello World"
  1. NameError This code has a bug in it. Follow the instructions in the comments to figure out how to fix the bug.
  2. String Concatenation Error Something is breaking when we try to let the user know what their current game score is. Follow the instructions in the comments to figure out how to fix the bug.
  3. Another NameError There is a typo in one of the variable names. A variable is being defined one way, but we're trying to call it with the wrong name. Find and correct the typo so the program will run.
  4. Math Use assign a Math equation to a variable to make each of the print statements return True.
  5. Mad-Libs Variables are named in order to make code readable. In this exercise, the variable names are very unhelpful. Go through and make the variable names more logic. For instance, the first variable asks the user to input an Adjective, but the variable name is foo. A potentially better name would be sentence_one_adjective.
  6. Read through Hangman code and count all of the times a variable is assigned. For instance, game = Hangman(). Don't worry about times these variables are called, just look for the variable name followed by the assignment operator (=).

If you have any questions, have you or your parents send me an email.

Week 3

In Class

A data type that has one of two possible values (true or false) and is meant to represent the truth values.

  1. Equality Repl
  2. Data Type Equality
  3. Conjunctions (and)
  4. Disconjunction (or)
  5. Compound statement

Terms

  • Conjunction - A statement where all equality checks are true. 1 + 1 == 2 and 2 + 2 == 4
  • Disjunction - A statement where any equality checks are true. 1 + 1 == 3 or 2 + 2 == 4
  • and - in Python, conjuctions are done using the keyword and
  • or - in Python, disjunctions are done using the keyword or
  • == - in Python we check equality with double equal signs
  • not - in Python we can check to see if a value is False by putting the not keyword in front of it

Take Home

This week you will have one Repl with 5 exercises to make sure you've got each of the logic checks down.

In the past we've typically done examples in a print() statement. This time around, to simplify things slightly, I've written some code that will test the code you put inside of test.addCase() and print out a message telling you if it passed or failed. It expects that every value it receives will be equal to True.

Follow the instructions written as comments and EMAIL ME the URL to your Repl.

Take Home Repl

If you are curious, you may go ahead and take a peak inside of test.py. You may see a few things that look familiar to you from the Hangman game.

Week 4

In Class

Lesson

Last week we learned about booleans and logic statements. Logic statements are checks to determine if something is True or False. This week we're covering conditional statements. Conditionals allow us to control what code is executed based on the result of a logic statement.

An example I have given in the past is let's say I want to automate my coffee maker. I want my coffee maker to make caffeinated coffee before noon and decaf coffee afternoon. In the past we simply assigned logic checks to variables, like this:

is_afternoon = current_time > 12
should_make_caffeinated_coffee = not is_afternoon

But with what we have learned so far, I wouldn't really be able to execute different code based on the value of should_make_caffeinated_coffee.

For that we use a conditional statement. In Python that is done with the if keyword.

is_afternoon = current_time > 12
should_make_caffeinated_coffee = not is_afternoon

if should_make_caffeinated_coffee:
  make_caffeinated_coffe() # don't worry to much about this code, we'll cover how this works next week, but for now just know that this is running some code    

In this code example make_caffeinated_coffee() will only run if the value of should_make_caffeinated_coffee is True. Otherwise it will get skipped.

Anatomy of a conditional

Let's look at the anatomy of the code above before we go farther. A conditional statement (sometimes called an "if statement") always starts off with the keyword if. The very next thing is a logic check, this can be a variable that is expected to be either truthy or falsey, or an actual logic statement like we covered last week. For instance:

if current_time > 12 and current_time < 16:
  make_decaffeinated_coffee()

The line ends with a colon :, which indicates to Python that we're done doing our logic checks, now it's free to figure out what code it should execute. Most programming languages have a concept known as blocks. A block is simply code that is grouped together and typically is related to something. Conditions are the first example we have of a block. When a conditional statement evaluates True the code block below it will run, and only the code block below it. In Python blocks are determined with spaces. In the example above, make_decaffeinated_coffee() belongs to the if current_time > 12 and current_time < 16: because it is tabbed-in or indented using the Tab key on your keyboard.

Here's a slightly longer example with comments that will hopefully illustrate this:

player_health = 20
monster_health = 10
player_atk_type = get_player_atk_type() # again don't worry about this, just pretend that this variable's value is coming from the player

if player_health > 0: # since the player health above is 20, this will be True and the code below will run
  print("You're still alive! Keep it up!")
  dmg = get_dmg(player_atk_type)
  monster_health = monster_health - dmg
  print("You've attacked the monster for " + str(dmg) + "points of damage. His health is now " + str(monster_health))
  # notice that all four lines above are indented.
  # this tells Python that that code should only run when player_health > 0

print("It's the monster's turn now!") 
# see how this code is not indented? This print will run
# whether player_health > 0 is True or not. But if player_health > 0,
# then all the code in that block will run first

Important Note: Python cares alot that your spacing is consistent. In the example above, if dmg had extra spaces/indents before it than monster_health it would throw an error.

else

So what happens if we want a conditional statement to have code run specifically when player_health > 0 is False?

In Python we can create a default block of code connected to the first if that will fire when it is False.

if player_health > 0:
  get_monster_dmg()
else:
  print("You've died! You failed the kingdom. Better luck next time.")

In the example above, if the player has no health left, the code in the else block will fire.

This is useful in cases where perhaps we want to exit the program or, in this game example, send the player to the main menu if the player has died.

In this next example, just know that in Python this code: exit() will quit the program that is currently running.

if player_health > 0:
  get_monster_dmg()
else:
  print("You've died! You failed the kingdom. Better luck next time.")
  exit()

print("It's the monster's turn now, keep up the good work!")

In the example above, if the player's health was not above 0, the program would exit and the "print" below would never fire. We sometimes call this "short-circuiting" because we prevent other code from running based on the result of a conditional statement.

elif

Sometimes we will have some code that is not as simple as an if/else. Using our game example again, let's say we want to figure out how much damage the monster needs to take based on the weapon the player is using.

(Imagine for this example that we are getting a variable called player_weapon from somewhere)

dmg = 0

if player_weapon == "sword":
  dmg = 7
else:
  dmg = 10
  
print("The monster will take " + str(dmg) + " damage!")

The code above is really useful if we only have two weapons types, perhaps a "sword" and a "bow". But what if I have more than two weapon types?

In Python I can do that with elif. elif allows me to write a new conditional statement that will get checked if the if or any elif's above it evaluate to False.

dmg = 0

if player_weapon == "sword":
  dmg = 7
elif player_weapon == "spear":
  dmg = 4
elif player_weapon == "bow":
  dmg = 10
else:
  dmg = 3

print("The monster will take " + str(dmg) + " damage!")

Now you may be asking, why can't we just do multiple ifs in this scenario? We totally could:

dmg = 3 # notice that instead of using the else to set this to 3 I just start with it there

if player_weapon == "sword":
  dmg = 7

if player_weapon == "spear":
  dmg = 4

if player_weapon == "bow":
  dmg = 10

print("The monster will take " + str(dmg) + " damage!")

But maybe there are more things than player_weapon that can affect my damage. For instance, let's say that when the sun is out our monster takes 100 damage without the player even needing to attack:

dmg = 3

if sun_is_out: # since sun_is_out is always either True or False, I don't need to do an equality check
  dmg = 100

if player_weapon == "sword":
  dmg = 7

if player_weapon == "spear":
  dmg = 4

if player_weapon == "bow":
  dmg = 10

print("The monster will take " + str(dmg) + " damage!")

So while before, player_weapon could only be one value, now I have to different things I'm checking against. In the above scneario, if the sun_is_out was True but the player_weapon was also "sword", the dmg would be 7 not 100. Taking the same scenario with elif's:

dmg = 0

if sun_is_out:
  dmg = 100
elif player_weapon == "sword":
  dmg = 7
elif player_weapon == "spear":
  dmg = 4
elif player_weapon == "bow":
  dmg = 10
else:
  dmg = 3

print("The monster will take " + str(dmg) + " damage!")

In this case, if sun_is_out is True, we would jump all the way down to the print and dmg would not get reset.

Exercise

To put this in practice we did some "whiteboarding" (or in our case, "flip-chart paper"-ing), which is where we write code by hand with pen or marker. This is a common practice in the software world when we're trying to quickly solve problems or collaborate on some code.

In each of these exercises you are given a few variables that will be supplied from the outside. This is done using a convention that we will learn next week called functions.

Each exercise has five "tests" that given the inputs on the left should output the value on the right.

An important note, to output the new values in Python we use a new keyword called return. Again, we will explore this concept more next week.

Each exercise outlines the rules, shows the tests, and a link to a Repl that will run the tests to make sure the code you write works. The first exercise has been done for you to illustrate what we're going for.

The point of the exercise is to demonstrate and practice conditional statements using real code.

Exercise 1 - FizzBuzz

Repl

Rules
  • Given a number, return "fizz" if number is divisible by 3.
  • Given a number, return "buzz" if number is divisible by 5.
  • Given a number, return "fizzbuzz" if number is divisible by 3 and 5.
Tests
  • 7 -> 7
  • 5 -> "buzz"
  • 12 -> "fizz"
  • 30 -> "fizzbuzz"
  • 33 -> "fizz"

Exercise 2 - Coin Counter

Repl

Rules

Given a count of coins and a coin_type, return the value of the coins in pennies.

Tests
  • (2, "nickle") -> 10
  • (1, "penny") -> 1
  • (5, "dime") -> 50
  • (2, "quarter") -> 50
  • (1, "half-dollar") -> 50
Help
  • Penny = 1
  • Nickle = 5
  • Dime = 10
  • Quarter = 25
  • Half-Dollar = 50

Exercise 3 - Football Scorer

Repl

Rules

Given a score_type and the current_score of a football game, return the new score.

Tests
  • ("fieldgoal", 27) -> 30
  • ("safety", 3) -> 5
  • ("extra-point", 6) -> 7
  • ("2pt-conv", 6) -> 8
  • ("touchdown", 0) -> 6
Help
  • Fieldgoal = 3
  • Safety = 2
  • Extra-Point = 1
  • 2pt Conversion = 2
  • Touchdown = 6

Homework

None! But if you want to send me code you've played around with in the in-class exercise, feel free. I'll happily look it over.

Week 5

In Class

A function is a block of code which only runs when called, can have data passed in as parameters, and can return data.

Take Home

This week you will write a few functions to make sure you understand the concept. In the repl below there are 5 files each with it's own function. In the main.py file, each of those function has some tests running on it that are currently failing. Your job is to write code inside the function that will make the code pass.

Each function is kind of like a puzzle, you will know what the answer is supposed to be based on the equality checks, but you will need to figure out what conditions to write based on the parameters being passed into the function.

Repl

Instructions

Repl

In the Repl you'll see a list of files on the left.

Repl file picker

In main.py you should see 5 sets of 4 tests, each set having a comment above it indicating the file that is having its function tested. main.py

Each of these tests is calling a function with either strings or numbers passed in as parameters. The function then returns a value based on those parameters. Just like variables or values, we can check equality on the return value of a function by calling it and then using our equality operator ==. equality

Note: You should not modify any code in main.py.

Right now if I ran this code, each of the function in main.py would be called, and some code that I wrote will check if the return value on each one equals the value on the right side of the equality check ==. Getting started you should get an output that looks like this: tests failing

Note: You should not modify any code in main.py.

Let's do the first test together, and see how far you can get on your own. We start by reading the first test. We see that it's calling get_player_dmg. The first parameter is being passed the value "arrow" and the second parameter is being passed the value "goblin". We also see that given those two parameters, the expected return value is 2.

Now we'll head into get_player_dmg.py on your sidebar. You should see a fairly empty file that looks like this: get_player_dmg file, getting started

In this file we see that we've defined a function called get_player_dmg. We also see that it has two parameters called atk_type and monster_type respectively. Remember, parameters are just like variables, we can do equality checks on them and, if they're numbers, do math on them. The only difference is that they are mapping to the values we passed into the function at it's call site. In test 0 then, atk_type is "arrow" and monster_type is "goblin". Now from reading the test we see that the expectation is that the function returns 2 in this scenario. We could change the 0 to a 2, but then we would have other tests that don't pass. So we'll use our conditional statements that we learned last week.

def get_player_dmg(atk_type, monster_type):
  if atk_type == "arrow" and monster_type == "goblin":
    return 2
  return 0

What we've done here is say that if I call (or run) get_player_dmg like this get_player_dmg("arrow", "goblin") it will return 2, since atk_type == "arrow" and monster_type == "goblin". Since I am returning, I am also ending the function's run, it will stop as soon as it sees return and give out the new value, so return 0 will never be reached.

If you were to copy and paste the above code into get_player_dmg.py, you should see the Test 0 pass in your console.

Note: You should not modify any code in main.py.

Hopefully that's enough to get you started. If you need any help at all, don't hesitate to reach out. I'm really rooting for you on this one.

Repl

Week 7

This week we covered dictionaries in Python.

A dictionary is a data structure that uses a key as an identifier to access and set a value.

Remember, dictionaries are created using the open and close curly braces: {}.

We can start putting values in it when we first initialize a dictionary:

book = {
  "title": "Anne of Green Gables",
  "page_count": 250
}

If we need to assign values to it after the fact, or change one of the values we've already set, we access the value by its key:

book["title"] = "The Two Towers"
book["page_count"] = 352

Finally, if I want to access one of the values, say to print it to the console, I do that in a similar fashion, by accessing it by its key:

print(book["title"])

# > The Two Towers

Take Home

Repl

There are four tests in this Repl and three of them are failing. The goal of the tests is to solidify 3 concepts: getting values, providing safety, and setting values. Modify the functions referenced in main.py but do not modify main.py.

The instructions are listed above each test but are repeated here:

  • Test 0: This function is trying to get player health out of a dictionary. Right now, the function is just returning None. Use what we explored in class to get the player's health out of the game_state.
  • Test 1 & 2: This function is trying to get the name of the player's weapon name. In the first example, we are expecting None because game_state_one doesn't have a weapon. But we need to be ready for test 2 which uses the same function. Check each key as you try to access the name of the player's weapon. If the key doesn't exist, return None.
  • Test 3: In this example, we pass the game_state into a function, but we don't return anything. Like we talked about in class, unless you use a specific tool, you are always directly modifying the dictionary you passed in, unlike other variables. For this test, modify decrease_player_health to subtract the hit amount from the player health in the game_state but don't return anything.

Week 8

A list is a data structure whose values are ordered sequentially and can be accessed by their index.

Takehome

Repl

This week we'll work through 5 tests to practice what we learned about lists in Python. This time you will only be working inside of main.py. You will need to modify code in there, but do not modify anything inside any of the test.add_case functions. All of the instructions in the comments of the code are copied below. If you have questions, please email me.

  • Test 0 - Replace the comment with some code to add weapon name (as a string) to weapon_list. The test will make sure there is at least 1 item inside the list.
  • Test 1 - Python has a built-in function called len. We do not need to import it. If we pass in a list as the argument, it will return the number of items in the list. Below, we create an empty list. Fill that list with items (either manually or with append) until it has the number of items the test is expecting.
  • Test 2 - In order to access data in a list, we have to use it's index. Below, we need to assign the value of one of the items to the variable "item". The value needs to match the value in the test. Remember, indexes start at 0. NOTE: Right now we are assigning an empty string to item. You will need to change this.
  • Test 3 - Below is a list of foods commonly eaten at Thanksgiving. But nobody likes cranberries, so we're gonna remove it from the list. Python has a helpful function build directly into the list called "remove". This will search the list for the first matching item and remove it.
  • Test 4 - Another way we can delete items from a list is with the "del" command, provided we know the index of our item. Down below is my Christmas list. However somehow I have duplicates in the list. Using the del command, remove the duplicates. NOTE: del is not a function. To use it simply type: del list[index]

Week 9/10

A loop is a sequence of statements which is specified once but which may be carried out several times in succession.

Takehome

Repl (Yes it is intentionally blank)

Using a while loop like we learned in class, create a guessing game.

  1. At the top of the file, create a variable with a random word
  2. Create a while loop with an input that asks the player for a word
  3. If the player guess matches the word in the variable, break the loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment