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
      • 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 Sharing URL Create Help
Create Create new note Create a note from template
Menu
Options
Versions and GitHub Sync 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
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 6 2024, Python II 💸 [<<< Back to main site](https://cs.brown.edu/courses/csci0020/) <img src="https://hackmd.io/_uploads/ByIXKvJ2C.png" width=200> > **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. :::warning **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](https://hackmd.io/@QQz43ugtRROGICapy_ZGyA/HJsbSQAiC/edit). ::: ## 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. <hr /> **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: ```python= for item in collection: print(item) # prints the selected item. ``` :::warning 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: ```python= collection = [1, 2, 3, 4] ``` Then running ```python= 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: ```python= 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: ```python= 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: ```python= 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. :::warning **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: ```python= 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. ```python= 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: ```python= 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!** ```python= def divide(numerator, denominator): print(numerator / denominator) ``` Think of the outputs: ```python= 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: ```python= 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. ```python= 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! ```python= 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. ```python= 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! ``` :::warning **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 :). <hr /> ## 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. <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 II`. All your files for the lab should live in this folder. ::: :::info **Task 2** Download the [`stencil file`](https://drive.google.com/file/d/1rZqFkcI2wYLmreZcp0BunBJ_6LoEpXeG/view?usp=sharing) for this lab, and put it in your `Python Lab II` folder you just created! ::: :::info **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](https://hackmd.io/@QQz43ugtRROGICapy_ZGyA/HJsbSQAiC/edit)! :::info **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 :::spoiler **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. ::: :::info **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. :::spoiler **Hint** Remember how we can iterate over a collection using a **for loop**! ::: :::info **Task 6** Use comments to explain how your `print_games` function works. :::spoiler **Hint** Notice how the stencil comments are written in the file! ::: :::info **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`.** :::spoiler **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 💸 :::success **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!! ::: :::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