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)
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)
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:
print(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):
print(num)
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):
print("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...):
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)
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)
divide(2, 1)
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.
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
def my_func():
print(x)
my_func()
print(x)
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
print(x)
my_func()
print(x)
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:
- Understand and write comments in Python
- Understand and write loops in Python
- Understand and write functions in Python
- Understand and implement different variable scopes
- Understand how to import and use libraries in Python
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:
- Blackjack
- Roulette
- Poker
- Craps
- Baccarat
- Slots
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:
game_list
, the list of games
special_number
, the number indicating Don's special number for max characters in
a game's name.
You will need to use the Python function len()
.
len()
gives you the length of a string. Example,
len("hello")
returns 5
.
Hints
- Iterate through each
game
in game_list
- 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:
- All of the games printed.
- All of the free games printed.
Congrats! You just finished your last CS2 lab!!
CS2 Lab 6 2024, Python II 💸
<<< Back to main site
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 💸
In Lab 6: Python Part II, you will be learning about some of the most powerful components of programming -
functions
,loops
, andvariable 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
oriterate
over data. We can "loop over" or go through each item in a collection usingfor
loops.Here's how we break down a for loop:
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:
Then running
Will print:
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:
"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:Will print:
You can also use number ranges to execute code a certain number of times. For example:
Will print the word "Hi!" ten times.
Important Note: Recall that in programming, we always start with the number 0!
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 aninput
, but they often do. The body of a function is as follows: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.
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.
We can "call" this function and have it execute through the following:
Notice we invoke the name of the function, followed by parentheses, and put the parameters inside the parentheses as
arguments
. Anargument
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!
Think of the outputs:
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: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.
Will assign the variable
divisor
to thereturn
value of the functiondivide
. We can then use thatdivisor
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!local variables
: variables assigned / declared within a specific function or loop, and can only then be used within that function or loop.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 forPython
. Then, create a new folder inside calledPython 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 calledgame_list
. Inside this function, print each game in the inputtedgame_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 ofgames
.The function should have two parameters:
game_list
, the list of gamesspecial_number
, the number indicating Don's special number for max characters in a game's name.You will need to use the Python function
len()
.len()
gives you the length of a string. Example,len("hello")
returns5
.Hints
game
ingame_list
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:
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