Emily Perelman
    • Create new note
    • Create a note from template
      • Sharing URL Link copied
      • /edit
      • View mode
        • Edit mode
        • View mode
        • Book mode
        • Slide mode
        Edit mode View mode Book mode Slide mode
      • Customize slides
      • Note Permission
      • Read
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Write
        • Only me
        • Signed-in users
        • Everyone
        Only me Signed-in users Everyone
      • Engagement control Commenting, Suggest edit, Emoji Reply
    • Invite by email
      Invitee
    • Publish Note

      Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

      Your note will be visible on your profile and discoverable by anyone.
      Your note is now live.
      This note is visible on your profile and discoverable online.
      Everyone on the web can find and read all notes of this public team.
      See published notes
      Unpublish note
      Please check the box to agree to the Community Guidelines.
      View profile
    • Commenting
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
      • Everyone
    • Suggest edit
      Permission
      Disabled Forbidden Owners Signed-in users Everyone
    • Enable
    • Permission
      • Forbidden
      • Owners
      • Signed-in users
    • Emoji Reply
    • Enable
    • Versions and GitHub Sync
    • Note settings
    • Engagement control
    • Transfer ownership
    • Delete this note
    • Save as template
    • Insert from template
    • Import from
      • Dropbox
      • Google Drive
      • Gist
      • Clipboard
    • Export to
      • Dropbox
      • Google Drive
      • Gist
    • Download
      • Markdown
      • HTML
      • Raw HTML
Menu Note settings Versions and GitHub Sync Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Engagement control Transfer ownership Delete this note
Import from
Dropbox Google Drive Gist Clipboard
Export to
Dropbox Google Drive Gist
Download
Markdown HTML Raw HTML
Back
Sharing URL Link copied
/edit
View mode
  • Edit mode
  • View mode
  • Book mode
  • Slide mode
Edit mode View mode Book mode Slide mode
Customize slides
Note Permission
Read
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Write
Only me
  • Only me
  • Signed-in users
  • Everyone
Only me Signed-in users Everyone
Engagement control Commenting, Suggest edit, Emoji Reply
  • Invite by email
    Invitee
  • Publish Note

    Share your work with the world Congratulations! 🎉 Your note is out in the world Publish Note

    Your note will be visible on your profile and discoverable by anyone.
    Your note is now live.
    This note is visible on your profile and discoverable online.
    Everyone on the web can find and read all notes of this public team.
    See published notes
    Unpublish note
    Please check the box to agree to the Community Guidelines.
    View profile
    Engagement control
    Commenting
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    • Everyone
    Suggest edit
    Permission
    Disabled Forbidden Owners Signed-in users Everyone
    Enable
    Permission
    • Forbidden
    • Owners
    • Signed-in users
    Emoji Reply
    Enable
    Import from Dropbox Google Drive Gist Clipboard
       owned this note    owned this note      
    Published Linked with GitHub
    Subscribed
    • Any changes
      Be notified of any changes
    • Mention me
      Be notified of mention me
    • Unsubscribe
    Subscribe
    # 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 />

    Import from clipboard

    Paste your markdown or webpage here...

    Advanced permission required

    Your current role can only read. Ask the system administrator to acquire write and comment permission.

    This team is disabled

    Sorry, this team is disabled. You can't edit this note.

    This note is locked

    Sorry, only owner can edit this note.

    Reach the limit

    Sorry, you've reached the max length this note can be.
    Please reduce the content or divide it to more notes, thank you!

    Import from Gist

    Import from Snippet

    or

    Export to Snippet

    Are you sure?

    Do you really want to delete this note?
    All users will lose their connection.

    Create a note from template

    Create a note from template

    Oops...
    This template has been removed or transferred.
    Upgrade
    All
    • All
    • Team
    No template.

    Create a template

    Upgrade

    Delete template

    Do you really want to delete this template?
    Turn this template into a regular note and keep its content, versions, and comments.

    This page need refresh

    You have an incompatible client version.
    Refresh to update.
    New version available!
    See releases notes here
    Refresh to enjoy new features.
    Your user state has changed.
    Refresh to load new user state.

    Sign in

    Forgot password

    or

    By clicking below, you agree to our terms of service.

    Sign in via Facebook Sign in via Twitter Sign in via GitHub Sign in via Dropbox Sign in with Wallet
    Wallet ( )
    Connect another wallet

    New to HackMD? Sign up

    Help

    • English
    • 中文
    • Français
    • Deutsch
    • 日本語
    • Español
    • Català
    • Ελληνικά
    • Português
    • italiano
    • Türkçe
    • Русский
    • Nederlands
    • hrvatski jezik
    • język polski
    • Українська
    • हिन्दी
    • svenska
    • Esperanto
    • dansk

    Documents

    Help & Tutorial

    How to use Book mode

    Slide Example

    API Docs

    Edit in VSCode

    Install browser extension

    Contacts

    Feedback

    Discord

    Send us email

    Resources

    Releases

    Pricing

    Blog

    Policy

    Terms

    Privacy

    Cheatsheet

    Syntax Example Reference
    # Header Header 基本排版
    - Unordered List
    • Unordered List
    1. Ordered List
    1. Ordered List
    - [ ] Todo List
    • Todo List
    > Blockquote
    Blockquote
    **Bold font** Bold font
    *Italics font* Italics font
    ~~Strikethrough~~ Strikethrough
    19^th^ 19th
    H~2~O H2O
    ++Inserted text++ Inserted text
    ==Marked text== Marked text
    [link text](https:// "title") Link
    ![image alt](https:// "title") Image
    `Code` Code 在筆記中貼入程式碼
    ```javascript
    var i = 0;
    ```
    var i = 0;
    :smile: :smile: Emoji list
    {%youtube youtube_id %} Externals
    $L^aT_eX$ LaTeX
    :::info
    This is a alert area.
    :::

    This is a alert area.

    Versions and GitHub Sync
    Get Full History Access

    • Edit version name
    • Delete

    revision author avatar     named on  

    More Less

    Note content is identical to the latest version.
    Compare
      Choose a version
      No search result
      Version not found
    Sign in to link this note to GitHub
    Learn more
    This note is not linked with GitHub
     

    Feedback

    Submission failed, please try again

    Thanks for your support.

    On a scale of 0-10, how likely is it that you would recommend HackMD to your friends, family or business associates?

    Please give us some advice and help us improve HackMD.

     

    Thanks for your feedback

    Remove version name

    Do you want to remove this version name and description?

    Transfer ownership

    Transfer to
      Warning: is a public team. If you transfer note to this team, everyone on the web can find and read this note.

        Link with GitHub

        Please authorize HackMD on GitHub
        • Please sign in to GitHub and install the HackMD app on your GitHub repo.
        • HackMD links with GitHub through a GitHub App. You can choose which repo to install our App.
        Learn more  Sign in to GitHub

        Push the note to GitHub Push to GitHub Pull a file from GitHub

          Authorize again
         

        Choose which file to push to

        Select repo
        Refresh Authorize more repos
        Select branch
        Select file
        Select branch
        Choose version(s) to push
        • Save a new version and push
        • Choose from existing versions
        Include title and tags
        Available push count

        Pull from GitHub

         
        File from GitHub
        File from HackMD

        GitHub Link Settings

        File linked

        Linked by
        File path
        Last synced branch
        Available push count

        Danger Zone

        Unlink
        You will no longer receive notification when GitHub file changes after unlink.

        Syncing

        Push failed

        Push successfully