owned this note
owned this note
Published
Linked with GitHub
# CS2 Lab 5 2024, Python I 🎰
[<<< Back to main site](https://cs.brown.edu/courses/csci0020/)
<img src="https://hackmd.io/_uploads/ByIXKvJ2C.png" width=200>
> **Due Date: Thursday, November 14, 2024**
> Complete this lab before Lab 6 (Python II) and Project 5.
> **Need help?** Remember to check out Edstem and our Website for TA help assistance.
## Background 🎰
> Be sure to read all background notes, as they are vital to do the assignment.
- Python is a high-level, object-oriented computing language. It more closely resembles “human language” than “computer language.” Python is increasing in popularity among employers: knowledge of it will prove useful!
- We will be using Python 3 for this course. Here are some resources we found helpful when learning Python:
- [Python Tutorial at W3Schools](https://www.w3schools.com/python/) - basic coding practice, click the tabs on the left side of the screen to see overviews of each topic
- [Python Documentation at W3Schools](https://www.w3schools.com/python/python_reference.asp) - defines methods that can be used for each type of variable
- [Python Standard Library](https://docs.python.org/3/library/) - details a collection of built-in functions, types, and constants available to all Python programs.
- 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.
<hr />
## Project/Lab Description 🎰
**Lab Goals:**
- Gain familiarity with Python in VSCode
- Understand how to print, input, and store data
- Learn how to model mathematical functions with code
## Downloading Python
The final part of the course will be using Python. If you do not have Python 3 installed, you can follow the instructions on [this website](https://www.python.org/downloads/) to download the correct version for your device. If you believe you have already downloaded Python, you can check which version of Python you have installed by running `python3 --version` in your terminal / command prompt.
## Download the VSCode Python Extension
In addition to downloading the software, please download the Python extension on VSCode as well. Follow the steps below to download the extension:
1. Go to the “Extensions” tab on VSCode (located on the lefthand side of the IDE).
2. Search “Python” in the 'Search Extensions in MarketPlace'. You’ll see three options popping up at the top.
3. Select the one that includes the word “Pylance” in the description, and install it (the first option in the following screenshot).
![](https://i.imgur.com/MY2Wjc9.png)
Once you have that extension installed, you should be set to code in VSCode! When writing in Python, remember to have your file end in .py (`example.py`).
<hr />
## Tasks 🎰
:::info
**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 I`. All your files for the lab should live in this folder.
:::
:::info
**Task 2** Download the [**stencil file**](https://drive.google.com/file/d/1yU5HcHTU8nh36m1FAyPfOLzppyD4L5mo/view?usp=sharing) for this lab, and put it in your `Python Lab I` folder you just created!
:::
:::info
**Task 3** Open up your `Python Lab I` 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.
:::
Once the folder has opened, you should see our stencil file, `CS2_2023_Lab5_Stencil.py` on the lefthand side of the screen. Double click the file, and you should see that it already contains some lines of code. Now we'll learn how to run that code!
:::info
**Task 4** In the file provided, we've written a line of code containing a **print statement**. Run the code by clicking the play button on the top right corner of the screen to see what happens.
:::
This program uses the print method to print the string "hello, world!" in the terminal. The terminal should appear at the bottom of your VSCode window once you click run. Methods (also called functions) are blocks of organized, reusable code that perform a single action. You’ll write your own function later!
### Math Operations Practices
In Python, text between quotation marks is known as a string. For example, 6 is an integer, but "6" is a string.
Here is a list of some basic math operations in Python. More information about math operations in Python can be found [here](https://www.w3schools.com/python/python_operators.asp).
- `+` addition
- `-` subtraction
- `*` multiplication
- `/` division
- `%` modulo/remainder after division
- `()` parentheses/indicate order of operations
:::info
**Task 5a** Try running the following code by copy-pasting this line into line 5 of your stencil file.
```
print(20+4)
```
:::
:::info
**Task 5b** The code block on line 6 contains a python comment. Prepending a line with # produces a comment. Try removing the comment and printing out your own math equation, as above.
:::
### Concatenation Practice
The + operator can be used for addition, as above, but can also be used with strings. This operation is called concatenation.
:::info
**Task 6** Try running the following line of code:
```
print("hello, " + "world" + "!")
```
Because the + operator has different roles when used with numbers versus strings, it's important to always make sure you're only using it with just numbers or just strings, not both!
**IMPORTANT NOTE:** Please make sure that your quotation marks look straight (like in the code block above). If they appear angled or curly, delete them and retype them within VSCode.
:::
### Variables Practice
In Python, you can store data in variables. More information about variables in Python can be found [here](https://www.w3schools.com/python/python_variables.asp).
:::info
**Task 7a** Try running the code below. In this variables practice section, it is important to run all of the code blocks in order, as some depend on the ones above.
```
width = 16
print(width)
```
:::
:::info
**Task 7b** Variables can also be used with other variables. To see this, use your stencil file to
1. Create your own variable called **height** and assign it the value **7**
2. Print this new variable
3. Create a new variable **area** and assign it the value of **width** multiplied by **height** using the two variables above
4. Print this variable area
:::
### List Practice
In Python you can make lists to group things together. More information about lists in Python can be found [here](https://www.w3schools.com/python/python_lists.asp).
```
casino_games = ["blackjack", "roulette", "poker"]
print(casino_games)
```
The items inside of the square brackets can be any combination of strings, numbers, or other lists. Each item in your list must be separated by a comma.
Each item in a list has an associated list number, or index. **List indexing starts at zero.** In `casino_games`, `"blackjack"` is at index zero, `"roulette"` is at index 1, and `"poker"` is at index 2. This is called zero indexing.
To access items in your list, you use bracket syntax, like so:
```
my_list[index_number]
```
where `my_list` is the name of your list and `index_number` is an integer and the index of the item you’re trying to access.
:::info
**Task 8** In your stencil file, write code to print the second index/third item in `casino_games`.
:::
:::info
**Task 9** We can alter items in the list in a similar manner. Try running the code below.
```
casino_games[0] = "slots"
print(casino_games)
```
To add an item to the end of your list you can use the append function as so:
```
casino_games.append("baccarat")
print(casino_games)
```
Try adding your own casino game to the end of the list in your stencil file!
:::
### Conditionals Practice
Conditional expressions use logic to determine which path of action to take based upon conditions set by the programmer. You used them in JavaScript and they are pretty similar in Python, with slightly different syntax. More information about conditionals in Python can be found [here](https://www.w3schools.com/python/python_conditions.asp).
Conditional statements are often set up in the following way:
```
if condition1:
do something
elif condition2:
do something else
else:
do something else
```
Note that "elif" is short for "else if." Only the first if block is necessary in conditional statements; there can be none, one, or multiple elif blocks after an if block, and there can at most be one else block following an if block. This depends on what you’re trying to achieve in your code.
:::info
**Task 10** Try running the following code with different input to see what happens.
```
number = input("Type in 1 or 2")
if number == "1":
print("nice choice!")
elif number == "2":
print("cool!")
else:
print("that's not 1 or 2!")
```
:::
Some important things to remember for conditional statements:
- Each condition must evaluate to **True** or **False**
- Each condition must be followed with a colon
- ==Each condition must be aligned with all other conditions, and each conditional statement must be indented one tab over (equal to four spaces)==
:::warning
Alignment is VERY important in Python! Make sure that you follow the alignment (proper indentation) seen throughout the lab.
:::
The following is a list of conditional operators:
- `<` less than
- `<=` less than or equal to
- `>` greater than
- `>=` greater than or equal to
- `==` equal to
- `!=` not equal to (this is different from =, which is an assignment operator)
- and
- or
- not
A brief note about and, or, not:
- An **and** statement is True if both of the conditional statements are True, e.g. (5>2) and (5>3)
- An **or** statement is True if at least one of the conditional statements is True, e.g. (5>2) or (5==1)
- A **not** statement is True if the conditional statement is False, e.g. not(5==1)
:::info
**Task 11** Try running the following examples:
```
if 8 > 5:
print("8 is greater than 5")
else:
print("8 is not greater than 5")
if 10 <= 6:
print("10 is less than or equal to 6")
else:
print("10 is greater than 6")
```
:::
:::info
**Task 12** Try editing the variable values below so that the code prints "I love blackjack!":
```
# edit this code!
skill_based = True
player_to_player = True
# do not edit this code!
if (skill_based == True) and (player_to_player == True):
print("I like poker!")
elif not(skill_based == True) and not(player_to_player == True):
print("I like slots!")
else:
print("I love blackjack!")
```
:::
### Putting It All Together :)
:::info
**Task 13**
Zach has recruited 12 friends to shuffle decks of cards. Each friend can shuffle 4 decks per hour.
In the stencil file, write code to solve this problem:
a variable **num_friends** with value 12
a variable **decks_per_hour** with value 4
a variable **total_time** that stores how long it will take (in hours) for Zach's friends to shuffle 240 decks.
If you're having trouble, look back at *Math Operations* and *Variables Practice*!
:::
:::info
**Task 14**
In the stencil file, add onto the code below in the following manner:
1. Append another name to the end of the list.
2. Use list indexing to print out `"clubs"`.
3. Then replace `"clubs"` with a different suit.
4. Print the element at that same index to show the change.
Optional: figure out how to remove items if you disagree with our list and print the ammended list.
If you're having trouble, look back to *Lists Practice*!
```
suits = ["clubs", "hearts", "diamonds"] # do not edit this line!
# Your code here
```
:::
:::info
**Task 15**
In the stencil file, create a program that checks for how many cards a player has, from 1 to 52.
To do this, we must first assign the initial number of cards in the store. Write a value called **total_cards** and assign it a value from 1 to 52.
Now, we will write some **conditional** statements to print out a message based on the value of **total_cards**. Based on the availabe number of cards, several things can happen:
- If there are less than 52 cards, print "Sorry, we don't have all the cards!" (i.e. if **total_cards** is less than 52)
- If the user enters the number 52, print "That's the right number of cards!"
- If the user enters a number greater than 52, print "That seems like too many cards"
If you're having trouble, look back to *Conditionals Practice*!
:::
<hr />
## Hand-In 🎰
:::success
**To Hand-In Lab 5**:
Come to hours and show your TA two things for checkoff:
1. The downloaded Python and extension on VSCode.
2. Output for Tasks 13-15.
Congrats! You just finished your second-to-last CS2 lab! 🎰
:::
:::warning
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
:::
<hr />