CS2 Lab 6 2024, Python II 💸

<<< Back to main site

Due Date: 11/21/2023
Complete this lab after Python I lab.

Need help? Remember to check out Edstem and our Website for TA help assistance.

Be sure that you have completed Lab 5, Python I before beginning this lab!!

It will be helpful to refer back to this lab, linked here.

Background 💸

Be sure to read all background notes, as they are vital to do the assignment.

In Lab 6: Python Part II, you will be learning about some of the most powerful components of programming - functions, loops, and variable scope.

Nearly every electronic device on the planet uses these ideas, and even the most complicated bits of code rely on these building blocks to work.


Let's learn some more python!

For Loops

In programming, we often want to loop or iterate over data. We can "loop over" or go through each item in a collection using for loops.

Here's how we break down a for loop:

for item in collection: print(item) # prints the selected item.

Remember that alignment is VERY important in Python! Make sure that you follow the alignment (proper indentation) seen throughout the lab.

Say our collection was:

collection = [1, 2, 3, 4]

Then running

for item in collection: print(item) # prints the selected item.

Will print:

1
2
3
4

So think of a loop as "going through" each item in a collection, and then doing something with that item. In this example, we just print-ed that item out to our console.

After the loop iterates over every element in a collection, it terminates and code beyond the loop body will be executed.

So, if we had:

for item in collection: # for ever item in collection print(item) # prints the selected item. print("hey!")

"hey!" would only print after every item in the collection was visited.

The collection to be iterated over can also be a number! If we wanted to produce an output a certain number of times, we can use a range of numbers:

for num in range(10): # every number between 0 and 10 (exclusive) print(num) # prints the current number.

Will print:

0
1
2
3
4
5
6
7
8
9

You can also use number ranges to execute code a certain number of times. For example:

for num in range(10): # every number between 0 and 10 (exclusive) print("Hi!") # prints the string "Hi!"

Will print the word "Hi!" ten times.

Important Note: Recall that in programming, we always start with the number 0!

Think of why we would want to use a number loop in some cases, vs a loop that goes over a collection in other places!

Functions

The purpose of functions is to contain code that has to be done repeatedly. If, on the other hand, a task is only to be done once, then it should be written directly in the main program.

Functions don’t have to take in a parameter, or an input, but they often do. The body of a function is as follows:

def function_name(parameter1, parameter 2...): #Code inside the function # Code outside of function

The body of a function, or the code that the function will execute, is everything that is indented below the function declaration. Anything on the same alignment level as the function declaration is not in the function.

Below is an example of a function that adds three parameters together and prints the total.

def add_three_numbers(number1, number2, number3): print(number1 + number2 + number3)

You can think of the parameters as inputs that generate some output. Parameters let us call functions with different inputs, and run the same code on them.

Think, parameters let us call the add_three_numbers function on different sets of numbers.

We can "call" this function and have it execute through the following:

add_three_numbers(1, 2, 3) # Will print the total of 1 + 2 + 3.

Notice we invoke the name of the function, followed by parentheses, and put the parameters inside the parentheses as arguments. An argument is the actual input you give a function. (Think of parameters as placeholders, and arguments as the real deal.)

We can re-use this function as many times as we want, just by calling it and trying different numbers as arguments!

The order of your parameters matters!

def divide(numerator, denominator): print(numerator / denominator)

Think of the outputs:

divide(1, 2) # prints 0.5, 1 = numerator, 2 = denominator divide(2, 1) # prints 2 2 = numerator, 1 = denominator

Many times it is useful to have a function return some data instead of simply printing it. You can think of return as outputting some variable. For example, perhaps you want to access the sum of three numbers outside the function in order to use that value later, perhaps by storing the returned value into a variable.

Let's change our divide function from before:

def divide(numerator, denominator): return (numerator / denominator)

Now instead of printing the division result, it will return the value for us to use.

We can assign a variable to this returned value.

divisor = divide(2 / 1)

Will assign the variable divisor to the return value of the function divide. We can then use that divisor variable for some other things…

Variable Scope

The last new information for this lab is variable scope, which refers to where assigned variables can be accessed.

There are two types of variables:

global variables : variables assigned / declared just within a file, and can be used anywhere inside the file, including functions and loops!

x = 300 # globally assigned def my_func(): print(x) # can be accessed in a function my_func() print(x) # can be accessed outside a function too!

local variables : variables assigned / declared within a specific function or loop, and can only then be used within that function or loop.

def my_func(): x = 300 # locally assigned print(x) # can be accessed in the same function my_func() print(x) # can NOT be accessed outside its home function, will throw an error!

Important Note: Make sure to always check your scope via indents! A variable assigned at a certain indent level can only be accessed by functions and places more and more indented!

You're ready for the next part of the lab! Great job :).


Lab Description 💸

The goals of this lab include:

The practice sections of this lab below will go over new concepts and provide already written code to practice with. The task sections of this lab at the bottom of this page will let you apply your new knowledge and write your own code.


Tasks 💸

Task 1 Double click your CS2 folder on your desktop, and enter your folder for Python. Then, create a new folder inside called Python Lab II. All your files for the lab should live in this folder.

Task 2 Download the stencil file for this lab, and put it in your Python Lab II folder you just created!

Task 3 Open up your Python Lab II folder by dragging the folder into Visual Studio Code, or by opening up Visual Studio Code, clicking "Open" under the "Start" header, and finding the folder in your file system.

Now let's pick off from what we learned in part I!

Task 4 At the top of the file, create a list of casino games, named games, composed of the following games:

Hint

Give your list a name, and then set it equal to some value. A list was assigned earlier in the handout if you need a reference! Recall these should be strings, so surround the name in straight quotation marks.

Task 5 At the next comment where it says to create the function that prints a game list, create a function called print_games with a parameter called game_list. Inside this function, print each game in the inputted game_list.

Then, call the function right below, and use the games list we created before as the inputted argument. If you click the arrow at the top right of your Visual Studio Code window at this point, you should see each game printed out in the terminal.

Hint

Remember how we can iterate over a collection using a for loop!

Task 6 Use comments to explain how your print_games function works.

Hint

Notice how the stencil comments are written in the file!

Task 7 Don only wants to play CS2 Casino games that are double or nothing.

Today's special number is 6, which means the double or nothing games include games with names less than or equal to 6 characters.

Write a function called print_double that will print out all the double or nothing games for today, from the list of games.

The function should have two parameters:

You will need to use the Python function len(). len() gives you the length of a string. Example, len("hello") returns 5.

Hints
  1. Iterate through each game in game_list
  2. If the length of the game is less than or equal to the special_number, print it out!

Hand-In 💸

To Hand-In Lab 6:
Come to hours and show your TA your terminal for checkoff. It should have:

  1. All of the games printed.
  2. All of the free games printed.

Congrats! You just finished your last CS2 lab!!

If you have any issues with completing this assignment, please reach out to the course HTAs: cs0020headtas@lists.brown.edu

If you need to request an extension, contact Professor Stanford directly: don.stanford@gmail.com