# Introduction

Welcome to Python Classroom! This website is for students who are interested in learning Python.  Since your coding will take place in the cloud, all you need is an Internet connection and a browser (Chrome, Firefox, Safari, Opera etc).  This course is Chromebook friendly and encourages you to use Python cloud options.


# About Python Classroom

Python Classroom is written by Matthew Cheng, a High School Computer Science Instructor and Adjunct Professor.  He earned a M.A. Teaching Secondary Education Mathematics from William Paterson University where he was awarded the Woodrow Wilson Teaching Fellowship and Robert Noyce Teacher Scholarship.  He also earned a M.S. in Digital Forensics and Cybersecurity, an Advanced Certificate in Digital Forensics for Computer Science and a B.S. in Computer Information Systems from John Jay College of Criminal Justice.  Matthew is a MIT Master Trainer in Educational Computing using the MIT App Inventor platform.  He was twice elected as a Trustee for the West New York Board of Education and served on the Board of Directors of the New Jersey School Boards Association.  He can be reached at chengm1 @ wpunj.edu

"Python" is a registered trademark of the Python Software Foundation.&#x20;

All product names, logos, and brands are property of their respective owners. All company, product and service names used in this website are for identification purposes only. Use of these names, logos, and brands does not imply endorsement.


# Python Cloud Options

To the cloud!  The following sections introduce you to cloud based Python programming environments.


# CS50 IDE

{% embed url="<https://docs.google.com/presentation/d/1vpipnVjcbrnG88Qw3S82Z0aLefu_ebgl78dvVrRxHIA/edit?usp=sharing>" %}

![AWS Cloud9](/files/-LVYpWyU1PSaRZZxRbP4)

CS50 IDE <https://ide.cs50.io/> is a customized version of AWS Cloud9, an open source cloud-based integrated development environment, designed with students with little or no prior computer science or programming experience in mind.

**Features include**

* Ubuntu 18.04
* Simplified user interface
* Text editor with syntax highlighting
* File browser
* Terminal emulator
* Graphical debugger for C and Python
* Revision history
* Keyboard shortcuts
* Collaboration

![CS50 IDE Screenshot](/files/-Lcvg2jRDILf3nmStUBI)

To login, you need a [GitHub](https://www.github.com) account.

![](/files/-Ld0xMhWOt4bBriCPo0H)


# CS50 IDE Overview

## Split View

Your preference may vary but I prefer working with the Split Pane in Two Rows.   I like having files open on  on the left and terminal windows on the right.  You can browse your files on the left hand side using the File Browser. &#x20;

![CS50 IDE Workspace](/files/-LVW0Uf7w4YuTJomZhEa)

\
To change your view to this option, click on Split Pane in Two Rows.

![](/files/-LVW0JTShPwIiuAu2Zjj)

## Working with Files

### Create a new File

* Click on the![plus](https://cs50.readthedocs.io/_images/plus.png)button atop any of the open panes and choose **New File** to open a blank file in that particular pane.
* From the file browser on the left, right-click or control-click on a directory and choose **New File** from the menu to create a blank file inside that directory, then double-click that file to open it.
* Press Alt + N (on a PC) or ⌘ + N (on a Mac).

### Save File

When a file is open in a tab and you have some unsaved changes, Cloud9 will show a red dot a top that tab, until you save your changes. To save a file, press Ctrl + S (on a PC) or ⌘ + S (on a Mac).  You can also click on **File > Save** (or **File > Save As…** if you want to save that as a new file).

![Red dot indicates the file has been edited.](/files/-LVWDDxsnb4bJZ-DwcFx)

### Download File

To download a file from your workspace to your local computer, navigate to the file in the File Browser on the left, right-click on the file’s name, and choose **Download**.

![In File Browser, select the file and then select the Download.](/files/-LVWDa3lLIBYx8IEdkwB)

To download all files in your workspace, click **File > Download Project**.

### Upload File

To upload a file from your local computer to your workspace:

1. Select a directory where you want your files to get uploaded into, by clicking on that directory in the file browser on the left. By default, this is your `~/workspace`directory.
2. Click **File > Upload Local Files…**, then choose either **Select files** or **Select folder**, depending on what you want to upload.

### File Revision History

While working on a file, you can undo changes by clicking **Edit > Undo** or by hitting Ctrl + Z (on a PC) or ⌘ + Z on your keyboard. Similarly, you can redo changes by clicking **Edit > Redo** or by hitting Ctrl + Shift + Z.

Cloud9 also keeps track of file revisions.  You can show the whole file revision history by clicking **File > Show File Revision History**, which will show a timeline on which you can click to jump to a particular version.  If you click on the Play button, you can watch yourself code!

![Revision History of a file.](/files/-LVWB6egKhL8u4UMNUuM)

## Working with the Terminal

The Terminal allow you to interact with the underlying Ubuntu environment using text commands such as creating, copying, or moving files, compiling and running your programs, and more.

### Opening New Terminals

When Cloud9 starts, there should be a terminal tab open at the bottom, by default. You can also open a new terminal tab in that or any other pane of your choice by clicking the ![plus](https://cs50.readthedocs.io/_images/plus.png) button atop that pane, and choosing **New Terminal**. Alternatively, you may just hit Alt + T (on a PC) or Option + T (on a Mac).

By default, the current working directory (cwd) in a new terminal is your `~/workspace` directory. You can  navigate to your desired directory using `cd path/to/directory`.

**TIP**: To open a terminal in a different directory, navigate to that directory in your file browser, right-click (on a PC) or Ctrl-click (on a Mac) on the directory’s name, and choose **Open Terminal Here**.

### Copying and Pasting

You will probably need to copy and paste commands into terminal tabs to run them. By default, copying and pasting via menus will work inside Cloud9 only (you might even get warned), so it’s recommended to use your keyboard to copy and paste by hitting Ctrl + C and Ctrl + C> (on a PC) or ⌘ + C and ⌘ + V (on a Mac).

### Command History

You will be often using the same commands over and over. You can scroll up and down through the list of commands by hitting your keyboard’s up or down arrow.

{% hint style="info" %}
When testing your program, the up arrow is your friend.
{% endhint %}

Additionally, you can search for a particular command by hitting Ctrl + R (on a PC) or ⌘ + R (on a Mac), then hitting the same again to scroll through the matches, then hitting Tab to select a particular match to modify it before running or Enter if you want to run it directly.

### Clearing Terminals

From time to time you will need to clear your terminal so that it’s easier to see what you’re doing. There are two main ways to do that

1. Press Ctrl + L (on a PC) or ⌘ + L (on a Mac). This way doesn’t actually clear the terminal, but rather just scrolls down, so you can always scroll back up and see what got cleared, if you wanted to.
2. Press Ctrl + K (on a PC) or ⌘ + K (on a Mac). This way actually clears the terminal; you won’t be able to scroll back up and see what got cleared.

### Restarting Terminals

Sometimes you need to restart your terminals, for example after an update, to have the new changes reflected on your terminal tabs. While you could go ahead and close any open terminal tabs, then reopen them, there’s an easier way by right-clicking (on a PC) or Control-clicking (on a Mac) inside of any terminal tab and choosing *Restart All Terminal Sessions*.

### Troubleshooting

If you want to force a program to quit, for example because it’s stuck in an infinite loop, press Ctrl + C (on a PC) or ⌘ + C (on a Mac). It may take several seconds for the program to respond, so do be patient!

As a last resort, in case the program won’t stop, you might need to forcibly kill it. Perhaps the easiest way to do that is to just close the terminal tab, clicking *Close* when prompted, and opening a new one.

Alternatively, you can click the stats button (showing memory, CPU, and disk stats) on the upper-right corner, and click *Show Process List*, find your program in the list, select it, and click **Kill**. If it doesn’t respond within a few seconds, click *Force Kill* instead.

If all else fails, click on CS50 IDE and Restart Workspace.  This will clear all running programs.

![](/files/-LVYdnnmxCzul2nO61w9)

### Layouts and Themes

Cloud9 is very customizable when it comes to laying out panes and tabs. You could very easily split a pane horizontally or vertically, by right-clicking (on a PC) or Ctrl-clicking (on a Mac) somewhere next to the ![plus](https://cs50.readthedocs.io/_images/plus.png) button atop the pane you want to split and choosing **Split Pane in Two Rows** or **Split Pane in Two Columns**.

You could also move tabs between different panes by dragging and dropping a tab to the targeted pane or even to somewhere you want a new pane with that tab to be created.

There’s a number of themes available in CS50 IDE that you can find under **View > Themes**. By default a theme called **Cloud9 Day** is selected, but if you prefer a dark theme, you can select it via **View > Night Mode**. Otherwise, you’re free to select from any of the available themes.

CS50 IDE also provides **Presentation Mode** in which the user interface is even more simplified and font sizes are larger. You can toggle that mode via **View > Presentation Mode**.

### Sharing Your Workspace

Sometimes it’s useful to share your workspace with someone (e.g. your teacher or professor) to assist you with something. &#x20;

![Cloud9 Share Button](/files/-LVZbJmHT8mlORNDHRHr)

Click on the **Share** button in the upper-right corner and type their email in the text field under **Invite People** and click **Invite.**

![Cloud9 Invite People](/files/-LVZbUsVzg0iXKtWbQcj)

You can choose to give the person R for Read Access or RW for Read and Write Access.

## Switching between Files and Terminal

To switch between Files and Terminal:

* On a Mac, click Option-S
* On a PC / Chromebook, click Alt-S

**Reference**: CS50 IDE Documentation <https://cs50.readthedocs.io/ide/online/>


# CS50 IDE and Python

## Python 3

Currently, CS50 IDE is running Python 3.7.3 (as of July 10, 2019)

![](/files/-LcvgUyMnqS0NM43T93n)

To run a Python file in CS50 IDE, save the file.  For example, hello.py

Then type: python hello.py

{% code title="hello.py" %}

```bash
~/workspace/ $ python hello.py
```

{% endcode %}

```
Hello World!
```


# CS50 IDE Debugging

## Text Editor Debugging

Once you've saved a file with a file extension (i.e. something.py), CS50 IDE's text editor will detect syntax errors in your code.  Sometimes the error will be on the same line as<img src="/files/-LVZ_6TBsi4HvBEWIwuk" alt="" data-size="line">and other times it will be the line after.  Keep this in mind when you're debugging your code.

{% hint style="info" %}
Fix syntax errors as they appear.   Don't write lines and lines of code without testing to see if your program works.  It will cost you more time in the long run.
{% endhint %}

### Example 1

Cloud9 detects a syntax error on the same line as the syntax error.

![Error in line 12](/files/-LVYTJne2YHymVeadHCo)

### Example 2

Cloud9 detects a syntax error as the line after the syntax error.

![Error in line 21](/files/-LVYSSNso_Gfa6gXROcw)

## Terminal Debugging

Similarly, if run the file in the Terminal, Python will give you a similar error message.  Remember, the error is on that line or the previous line.

![](/files/-LVYYzv8VF0r60jNujuX)


# CS50 IDE Shortcuts

## Text Editing

| Key                 | Description            |
| ------------------- | ---------------------- |
| Tab                 | Indent or Block Indent |
| Shift + Tab         | Block un-Indent        |
| Control + C         | Copy                   |
| Control + V         | Paste                  |
| Control + A         | Select all             |
| Control + Z         | Undo                   |
| Control + X         | Cut                    |
| Control + /         | Comment                |
| Control + F         | Find                   |
| Control + K         | Find Next              |
| Shift + Control + K | Find Previous          |
| Control + Backspace | Remove Word Left       |
| Control + =         | Larger Font            |
| Shift + Control + = | Smaller Font           |

## Selection

| Keys                | Description    |
| ------------------- | -------------- |
| Shift + Down Arrow  | Highlight down |
| Shift + Up Arrow    | Highlight up   |
| Shift + Left Arrow  | Select Left    |
| Shift + Right Arrow | Select Right   |

## Terminal

| Keys        | Description                |
| ----------- | -------------------------- |
| Alt + S     | Switch to Terminal or File |
| Control + C | Abort Command or Program   |

## Navigation

| Keys            | Description    |
| --------------- | -------------- |
| Control + W     | Close Pane     |
| Shift + Control | Previous Pane  |
| Control + ]     | Goto Right Tab |
| Control + \[    | Goto Left Tab  |

## File

| Keys                | Description |
| ------------------- | ----------- |
| Control + S         | Save        |
| Control + N         | New File    |
| Shift + Control + S | Save As     |


# Linux Bash Shell

CS50 IDE is currently using Ubuntu 18 LTS

```bash
$ cat /etc/*release
DISTRIB_ID=Ubuntu
DISTRIB_RELEASE=18.04
DISTRIB_CODENAME=bionic
DISTRIB_DESCRIPTION="Ubuntu 18.04.3 LTS"
```

## Terminal Shortcuts

| Key/Command | Description                                                                       |
| ----------- | --------------------------------------------------------------------------------- |
| ctrl-a      | Go to the beginning of the line you are currently typing on.                      |
| ctrl-c      | Kill whatever you are running. Also clears everything on current line             |
| ctrl-e      | Go to the end of the line you are currently typing on.                            |
| ctrl-l      | Clear the terminal                                                                |
| ctrl-r      | Reverse search history                                                            |
| ctrl-w      | Delete word on the left                                                           |
| ctrl-y      | Paste                                                                             |
| ctrl-z      | Puts whatever you are running into a suspended background process. fg restores it |
| tab         | auto completion of file or command                                                |
| !!          | repeat last command                                                               |

## Terminal Navigation

| Key/Command        | Description                   |
| ------------------ | ----------------------------- |
| ls -a              | list all files and folders    |
| ls \<foldername>   | list files in folder          |
| ls -lh             | Detailed list, human readable |
| ls -l \*.jpg       | list jpeg files only          |
| ls -lh \<filename> | Result for file only          |
| cd \<foldername>   | change direcxtory             |
| cd /               | goto root directory           |
| cd ..              | go up one folder              |
| pwd                | print working directory       |
| man \<command>     | shows manual                  |

## Pipe

| Key/Command                  | Description                                                                      |
| ---------------------------- | -------------------------------------------------------------------------------- |
| \[command-a] \| \[command-b] | Run command A and then pass the result to command B e.g ps auxwww \| grep google |

## File Manipulation

### tail

| Key/Command         | Description                            |
| ------------------- | -------------------------------------- |
| tail \<filename>    | output the last part of files          |
| tail -f \<filename> | output appended data as the file grows |

### head

| Key/Command         | Description                                       |
| ------------------- | ------------------------------------------------- |
| head \<filename>    | output the first part of files                    |
| head -n \<filename> | print the first NUM lines instead of the first 10 |

### cp

| Key/Command                | Description                     |
| -------------------------- | ------------------------------- |
| cp image.jpg newimage.jpg  | copy and rename a file          |
| cp image.jpg \<foldername> | copy to a folder                |
| cp -R stuff otherstuff     | copy and rename a folder        |
| cp \*.txt stuff            | copy all \*.txt to stuff folder |

### cat

| Key/Command     | Description                                        |
| --------------- | -------------------------------------------------- |
| cat \<filename> | concatenate files and print on the standard output |

### mkdir

| Key/Command         | Description        |
| ------------------- | ------------------ |
| mkdir \<foldername> | create a directory |

### redirect

| Key/Command           | Description                                               |
| --------------------- | --------------------------------------------------------- |
| \[command] > \[file]  | Push output to file, keep in mind it will get overwritten |
| \[command] >> \[file] | Append output to existing file                            |
| \[command] < \[file]  | Tell command to read content from a file                  |

### touch

| Key/Command       | Description            |
| ----------------- | ---------------------- |
| touch \<filename> | change file timestamps |

##


# Vim Mode

Vim is an editor to create or edit a text file.&#x20;

{% embed url="<https://docs.google.com/presentation/d/15GyPedfwTgNicd2esmipPzCoLwYmFVIRAElPXRLnvss/edit?usp=sharing>" %}

![Source: http://www.viemu.com/a\_vi\_vim\_graphical\_cheat\_sheet\_tutorial.html](/files/-LqnK441fKXw2ZWfSfLo)

## Command Mode

In the command mode, user can move around the file, delete text, etc.

| Key      | Explanation                                  |
| -------- | -------------------------------------------- |
| h        | Moves the cursor one character to the left   |
| l        | Moves the cursor one character to the right  |
| k        | Moves the cursor up one line                 |
| j        | Moves the cursor down one line               |
| nG or :n | Cursor goes to the specified (n) line        |
| ^F       | (CTRl F) Forward screenful                   |
| ^B       | Backward screenful                           |
| ^f       | One page forward                             |
| ^b       | One page backward                            |
| ^U       | Up half screenful                            |
| ^D       | Down half screenful                          |
| $        | Move cursor to the end of current line       |
| 0        | Move cursor to the beginning of current line |
| w        | Forward one word                             |
| b        | Backward one word                            |
|          |                                              |

### Exit Commands

|     |                                                                   |
| --- | ----------------------------------------------------------------- |
| :wq | Write file to disk and quit the editor                            |
| :q! | Quit (no warning)                                                 |
| :q  | Quit (a warning is printed if a modified file has not been saved) |
| ZZ  | Save workspace and quit the editor (same as :wq)                  |

### File Manipulation Commands

|         |                                          |
| ------- | ---------------------------------------- |
| :w      | Write workspace to original file         |
| :w file | Write workspace to named file            |
| :e file | Start editing a new file                 |
| :r file | Read contents of a file to the workspace |

### Text Deletion Commands

|    |                             |
| -- | --------------------------- |
| x  | Delete character            |
| dw | Delete word from cursor on  |
| db | Delete word backward        |
| dd | Delete line                 |
| d$ | Delete to end of line       |
| d^ | Delete to beginning of line |

### Yank Commands

|    |                                         |
| -- | --------------------------------------- |
| yy | yank current line                       |
| y$ | yank to end of current line from cursor |
| yw | yank from cursor to end of current word |

### Paste

|   |                    |
| - | ------------------ |
| p | paste below cursor |
| P | paste above cursor |
|   |                    |

### Undo

|   |                  |
| - | ---------------- |
| u | Undo last change |
| U | Restore line     |

### Change from command mode to insert mode

**From** command mode **to** insert mode type **a**/**A**/**i**/**I**/**o**/**O** ( see details below)

## Insert Mode

In the insert mode, user can insert text.

**Changing mode from one to another**

### Change from insert mode to command mode

**From** insert mode **to** command mode type **Esc** (escape key)

Some useful commands for VIM

| Key | Explanation                                                        |
| --- | ------------------------------------------------------------------ |
| a   | Append text following current cursor position                      |
| A   | Append text to the end of current line                             |
| i   | Insert text before the current cursor position                     |
| I   | Insert text at the beginning of the cursor line                    |
| o   | Open up a new line following the current line and add text there   |
| O   | Open up a new line in front of the current line and add text there |

&#x20;

**To create a page break,** while in the insert mode, press the CTRL key

And l. ^L will appear in your text and will cause the printer to start

A new page.

**Other Useful Commands**

Most commands can be repeated n times by typing a number, n, before

the command. For example 10dd means delete 10 lines.

. Repeat last command

cw Change current word to a new word

r Replace one character at the cursor position

R Begin overstrike or replace mode � use ESC key to exit

:/ pattern Search forward for the pattern

:? pattern Search backward for the pattern

n (used after either of the 2 search commands above to

continue to find next occurrence of the pattern.

:g/pat1/s//pat2/g replace every occurrence of pattern1 (pat1) with


# Vim Tutorial

![Source: http://www.viemu.com/a\_vi\_vim\_graphical\_cheat\_sheet\_tutorial.html](/files/-LqnKgwWZ1DpbSL5x_Ye)

![Source: http://www.viemu.com/a\_vi\_vim\_graphical\_cheat\_sheet\_tutorial.html](/files/-LqnKk8Vgtsmjwcn1mGh)

![Source: http://www.viemu.com/a\_vi\_vim\_graphical\_cheat\_sheet\_tutorial.html](/files/-LqnKnFayfHF2bj8p-vS)

![Source: http://www.viemu.com/a\_vi\_vim\_graphical\_cheat\_sheet\_tutorial.html](/files/-LqnKprolATS4I_iAsHe)

![Source: http://www.viemu.com/a\_vi\_vim\_graphical\_cheat\_sheet\_tutorial.html](/files/-LqnKsOBSmHa7AYEfgRT)

![Source: http://www.viemu.com/a\_vi\_vim\_graphical\_cheat\_sheet\_tutorial.html](/files/-LqnKuyUrdTCginAJvLu)

![Source: http://www.viemu.com/a\_vi\_vim\_graphical\_cheat\_sheet\_tutorial.html](/files/-LqnKxNGb6EwXeJTaxTh)


# CS50 Sandbox

The CS50 Sandbox <https://sandbox.cs50.io> is a temporary programming environment for students and teachers.

## CS50 Sandbox

![](/files/-LajyPBq3ZfgV80lQftj)

### Github Login

You will need to Sign in to Github in order to access the CS50 Sandbox. &#x20;

![](/files/-L_WzHqR8jYzzCpMZOjn)

### Sandbox

Once you've signed in, you'll have access to a Code Editor and a Terminal.

![](/files/-L_WzmB_HO3iOqC8Nz8M)

### Create a New File

You can create a new File and then execute it via the Terminal.&#x20;

![](/files/-LajymwMFyODAC48udpU)

### Share

You can also share a copy of your sandbox by clicking on the Share link on the top right hand corner.

![](/files/-LajzFHsVcQK3N6ETw14)

## X Window

If you're using Turtle Graphics or PyGame, select the X Window option.

![](/files/-L__56dsgCwo2wOzUJ17)

![](/files/-L__5K0IgD89CMbiBQdG)


# PythonAnywhere

![PythonAnywhere](/files/-LV_KLxwBKClQzmQMk04)

Another cloud based Python programming option is PythonAnywhere <https://www.pythonanywhere.com>

It offers a text editor with Vim compatibility and a bash terminal.

![](/files/-LV_Ky1TGhsn3N-Ao91N)


# Repl.it

![Repl.it](/files/-LV_JhT7PhPj27RO3zFA)

Another cloud based Python programming option is Repl.it <https://www.repl.it>

It offers a text editor and run button that executes Python files.

![](/files/-LV_HzbBZOl7X06FzLnk)


# Python Curriculum Map

* Turtle Graphics
  * Commands
  * Shapes
  * Colors
* Output
  * Print Statement
  * String Concatenation
* Variables
  * Variable Data Types
  * Variable Roles
* Math
  * Math Operators
  * Order of Operations
* Input
* Decisions
  * if
  * if else
  * if elif else
  * nested if
  * logical operators
* Loops
  * while loop
    * count up
    * count down
    * sentinel menu
    * sentinel value
  * for loop
    * range (one argument)
    * range (two arguments)
    * range (three arguments)
* Lists
  * Lists - Numbers
  * Lists - Strings
* Dictionaries
* Functions
  * Variable Scope
  * Functions - no parameters
  * Functions - one parameter
  * Functions - multiple parameters
  * Functions - return value
* Classes
  * Methods
  * Parameters
  * Inheritance

##


# Pedagogy


# Python Professional Development

{% embed url="<https://docs.google.com/presentation/d/14xgcMFi0nmMNN8ft0gW9DYZHtPbKHeQppmpWadm-5vk/edit?usp=sharing>" %}

## Capstone Project

{% embed url="<https://docs.google.com/document/d/1QdclAIRVjsUYEIxSQJcmhM9oQ-vCw46_brYG_bY6uJM/edit?usp=sharing>" %}

## Toms River - You Can Code!

{% embed url="<https://docs.google.com/presentation/d/1ib96alLadAXPM0TuCvBfPtb4pXRsfbb_opMHi30xugI/edit?usp=sharing>" %}


# Teaching Tips

## Introduce the growth mindset

Students pursue more effective learning strategies when they see intellectual abilities as malleable i.e. have a growth mindset rather than innate i.e. having a fixed mindset.  Students with a growth mindset are more willing to learn from mistakes and challenge themselves.

## Integrate active learning

During the lecture, engage your students in problem solving, discussing or debating content, practicing skills, or presenting or summarizing information.

## Encourage questions

By encouraging students to ask questions, you gain insights into parts of your explanation that were unclear and better understand what students find difficult about the topic.

## Require students to self-assess

You can ask students to re-explain a topic to a neighbor or solve a problem that requires them to apply a new idea or skill.  Students might otherwise assume that they understand the content better than they do. &#x20;

## Ask students for feedback

Ask for students' feedback and in written form.

## Structure collaboration

To ensure that all students have access to an information support network, provide structured collaboration opportunities where students can get to know each other.

Reference: <http://csteachingtips.org/>


# Assessment Tips

## Predict the output of code

Ask students what code will output when provided specific inputs.  You can also ask students to provide inputs that will produce specific outputs. &#x20;

## Find and fix a bug in code

Ask students to identify a bug in code. &#x20;

## Explain, compare or critique code

Ask students to write sentences to describe code in a way that isn't in the class would understand.

## Solve the problem by hand

Before students try to write code, make sure they can solve the problem by hand.


# Rubrics

### Active Learning

| 4 Exemplary                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                      | 3 Successful                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                             | 2 Insufficient                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                    | 1 Unsatisfactory                                                                                                                                                                                                                                                                                                                                                                                                                                            |
| -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The student actively engages with the learning process by demonstrating most if not of all of these habits, almost all the time: setting goals, persisting through challenges, seeking feedback, reflecting on the process, and implementing feedback and reflections in future performances. The student also practices proactive problem-solving strategies by seeking out answers and information before asking for help, from investigation of course concepts to navigation and troubleshooting within an online environment. While there is room for growth, the student is overall a highly-motivated, autonomous, and self-sufficient learner who can experience success due to these habits. The student may be considered a role model when it comes to this behavior. | The student engages with the learning process by often demonstrating a number of these habits: setting goals, persisting through challenges, seeking feedback, reflecting on the process, and implementing feedback and reflections in future performances. The student often seeks out answers and information before asking for help, from investigation of course concepts to navigation and troubleshooting within an online environment. The student shows growth in one or more of the following areas: motivation, autonomy, or self-sufficiency. There is may also be some room for substantial growth in one of these areas, but any gaps are not major impediments to success. | The student sometimes engages with the learning process by doing one or part of the following tasks: setting goals, persisting through challenges, seeking feedback, reflecting on the process, or implementing feedback and reflections in future performances. The student does not regularly seek out answers and information before asking for help, and may need to be pursued by the instructor and peers. The student may occasionally query to better investigate course concepts or to navigate and troubleshoot issues within the online environment. Motivation, autonomy, or self-sufficiency is occasionally apparent in some work, but the behavior is not consistent nor a habit. Extrinsic motivation (the teacher, deadlines, reminders, etc.) are the motivators rather than internal guidelines and habits. There is room for the student to grow significantly in a number of these areas so that the student can experience increased success with learning. | The student struggles to actively engage with the learning process. There is little evidence that the student is doing any or much for the following: setting goals, persisting through challenges, seeking feedback, reflecting on the process, and implementing feedback and reflections in future performances. The student is not proactive in seeking out answers or asking for help, in troubleshooting issues, or in querying about course concepts. |

### Exit Slip

| 2                   | 1                        |
| ------------------- | ------------------------ |
| Submitted Exit Slip | Did not submit Exit Slip |

### Submission Template

| 4 Exemplary                                                                    | 3 Successful                                                         | 2 Insufficient                                                             | 1 Unsatisfactory                                                       |
| ------------------------------------------------------------------------------ | -------------------------------------------------------------------- | -------------------------------------------------------------------------- | ---------------------------------------------------------------------- |
| Students throughly answered all questions in the submission template document. | Students answered all questions in the submission template document. | Students partially answered questions in the submission template document. | Students did not answer questions in the submission template document. |

### Python File

| 5 Completed               | 3 Partial                           | 1 Incomplete                     |
| ------------------------- | ----------------------------------- | -------------------------------- |
| Completed Python Activity | Partially completed Python activity | Did not complete Python Activity |


# Activities


# Picture Activity

## Introduction

This activity has been designed to improve communication skills and help students understand how difficult it is to formulate clear directions.

The image you are going to have students communicate should be very simple. For example, pick a couple of letters or shapes as the images that students should be communicating. If you do this activity several days in a row, then you may place more images on the picture or make something slightly more complicated.

## Directions

1. Please split the class into partners (2 students)
2. Partner 1 is sitting in a chair facing the front of the room, and partner 2 iis sitting in a chair facing the back of the room. All pairs should be sitting back to back; half the class facing the front and the other half the back.
3. Explain to the class that you will be showing the half facing the front a picture while the other half will not be able to see it.
4. The goal is for Partner 1 (the students looking at the picture) to communicate what the image is to their partner.
5. Partner 2 cannot speak or communicate in any way; they are drawing what Partner 1 is telling them to do.
6. Allow pairs two minutes to come up with how they will communicate clearly.
7. It should take approximately 3-5 minutes to communicate the picture.&#x20;
8. When students are done, they will hold up their drawings to see how they did.
9. Have a discussion about what some partners said to others and how groups were successful.
10. Allow students another 2-3 minutes to switch what partner is communicating and come up with a new strategy.
11. Give the students another image and repeat steps 7-9.

{% file src="/files/-LkLtWMQFJk06bRUXfby" %}

{% file src="/files/-LkLudy1AmpJem3cq1k6" %}


# Map Activity

Study the map below carefully.  Later you will be asked several questions about these locations.

## Map Study Sheet

![](/files/-LkcOg6ao7b6jJNr5o1K)

{% file src="/files/-Lkd4y010AlLMwWD2lcw" %}

{% embed url="<https://docs.google.com/drawings/d/1x-g9XaxlbzFAsL2PX0CPVLsqiBs0HQ4U_1qnpAMFwm8/edit?usp=sharing>" %}

## Word Study Sheet

Study the sentences below carefully.  They will tell you where six children live and where their school is.  Later you will be asked several questions about these locations.

> Sandy lives three blocks north of the school and one block west of Peter.  Peter lives one block north and two blocks west of Sophia.  Sophia lives two blocks north of Alex and one block west of Dom.  Alex lives three blocks west of the school and two blocks north of Sam.

{% file src="/files/-LkcOPq17x-OkJpsNRBh" %}

{% embed url="<https://docs.google.com/document/d/1zkihSsm1F4WXa2UC8UeiP5LxuvlC46_GVC0GL72yaW4/edit?usp=sharing>" %}

## Maps Quiz Sheet

{% file src="/files/-Lkd6vzSmcPAO-7q3K1w" %}

{% embed url="<https://docs.google.com/document/d/1-C9mrU4zgZQMq1uG7ytNMdCMi-3HZvkTgagsbMHH1u8/edit?usp=sharing>" %}


# Crossing the Bridge

Alice, Bob, Carrie, and Dan have to cross a rickety bridge. The bridge can only hold two people at a time. They also have a flashlight, and one person on the bridge must be always holding the flashlight. Alice can cross the bridge in 1 minute, Bob can cross the bridge in 2 minutes, Carrie can cross the bridge in 5 minutes, and Dan can cross the bridge in 10 minutes. What is the fastest amount of time that all four of them can cross the bridge?

* This problem has no tricks, no one is carrying another person, dragging them, running, etc.&#x20;
* There is a good answer and a best answer
* You are as fast as the slowest person on the bridge


# NIM

## Introduction

NIM is a solvable game! The goal is for students to play and develop a strategy that will allow them to win the game every time.

Suggested Method of teaching 1. Place students into groups of 3. 2. Allow each group to practice with their partners for 10 minutes to see if they can create a strategy to play 3. Then have groups play each other for 10 minutes. (rotate the groups so everyone can play each other) 4. When finished, discuss strategies that the groups came up with. There should be one that guarantees a win every time

Here is the board set up. You can use chips or cards for each circle

### Version 1

O O O O O&#x20;

O O O O&#x20;

O O O

### Version 2

O O O O O O O O O O O O O O O O O&#x20;

Game Rules 1. Players will alternate turns. (Best to flip a coin to see who goes first) 2. On each turn you must take at least one piece from the board. You may take more than one. 3. You can only remove pieces from one row on your turn. For example, I may choose to take all five from the top row. (With this move I have fulfilled rule 2 and 3) 4. The winner is the player who takes the last piece off of the board


# Mastermind

{% embed url="<https://docs.google.com/presentation/d/1m8AydSpdkzbrNmUOQTuKTy_1wI2-zK1XqZ1G3xOw2fo/edit?usp=sharing>" %}

## Introduction

This game of mastermind uses eight colors. The teacher selects three colors for their combination. The teacher is not picking any repeat colors. With this version of the game, the students should be able to have the answer in 6 guesses or less. If students have never played before, it is good to do an example on the board to show expectations. The very first time you play it will probably take 30 minutes to explain, demonstrate, and move through two rounds.

### Eight Colors

1. Red
2. Blue
3. Yellow
4. Green
5. Magenta
6. Orange
7. Purple
8. White

### Secret Code

| Position 1 | Position 2 | Position 3 |
| ---------- | ---------- | ---------- |
| Red        | Blue       | Magenta    |

### Game Rules

1. The teacher puts the students into groups of 3.
2. The teacher picks the secret code. (Three colors/no repeats.)&#x20;
3. Explain to students they will be making their guess one set at a time (three colors)
4. Before allowing the students to start working in their groups, tell them that each guess they make is a clue to the secret code. Encourage the students to use the first letter of each color as they guess. This will get them into the routine of using symbols.
5. Teacher will call the students over for each round of guesses. By calling them by Round 1, Round 2, etc., you are ensuring the the teams are not rushing.
6. When students bring up their guess, tell them how many colors they have correct, then how many colors they have in the correct space. (For example, 1 correct, none in the right space)
7. Students will return to their groups to formulate their next guess. Give groups about 45 seconds between guesses.
8. Call students up for round two and repeat steps 6-7.
9. If students guess in 6 or less, then they win! If they do not complete their guesses in 6 or less then their game is over.
10. Have a winning and losing team place their guess process on the board. Have them explain their process and discuss logically why their guesses made or did not make sense. Explaining the process at the end will help make all groups more successful.


# Cards


# Card Deck Algorithms

## Scenario 1&#x20;

Pull the cards, A-10 out of a card deck. (It is preferable that they are the same suit). The goal is to devise an algorithm that when you deal the cards A, 2, 3...10 they are in order. Here is the catch: you are dealing the cards out one face up, then one to the bottom of the deck, one face up, one to the bottom of the deck…..and this will continue until all the cards are face up in order. The students need to work in groups to find/solve the pattern.

## Scenario 2&#x20;

Pull the cards, A-10 out of a card deck. (It is preferable that they are the same suit). The goal is to devise an algorithm that when you deal the cards A, 2, 3...10 they are in order. Here is the catch: you are dealing the cards out one face up, then two to the bottom of the deck, one face up, two to the bottom of the deck…..and this will continue until all the cards are face up in order. The students need to work in groups to find/solve the pattern.

## Scenario 3&#x20;

Pull the cards, A-10 out of a card deck. (It is preferable that they are the same suit). The goal is to devise an algorithm that when you deal the cards A, 2, 3...10 they are in order. Here is the catch: you are dealing the cards out one face up, then three to the bottom of the deck, one face up, three to the bottom of the deck…..and this will continue until all the cards are face up in order. The students need to work in groups to find/solve the pattern.

## Scenario 4&#x20;

Pull the cards, A-10 out of a card deck. (It is preferable that they are the same suit). The goal is to devise an algorithm that when you deal the cards A, 2, 3...10 they are in order. Here is the catch: you are dealing the cards out one face up, then one to the bottom of the deck, one face up, two to the bottom of the deck, one up, three to the bottom of the deck ( then 4 then 5...etc) and this will continue until all the cards are face up in order. The students need to work in groups to find/solve the pattern.


# Sorting Cards

Students should be placed in groups of three and given a deck of cards. Explain to students that they will be developing a strategy to place the cards in order A-K by suit. All the hearts should be in order, all the diamonds, all the spades and all the clubs. It does not matter which suit they place first in the deck, but all the cards in that suit must be in order. The goal is to complete this as quickly as possible with their group members.

1. All students should be given a shuffled deck and be told the goal.&#x20;
2. Clarify any questions about suit, make sure the students see an example of what the cards look like in order.&#x20;
3. Give students five minutes to practice and develop their strategy in their groups.
4. After five minutes, make sure each group shuffles a card deck for another group to ensure that the decks are shuffled
5. To be finished, the students must order their deck, place the deck in a neat pile face down on the table, and all members must place their hands above their heads to indicate they are finished and not touching their cards
6. Go around to each group in the order they finished to see if their cards are in order, if there is a mistake they are disqualified.
7. Allow students another three minutes to see if they can improve their algorithm and repeat steps 5-6


# River Crossing

##


# Jealous Boyfriends

Three heterosexual couples must cross a river using a boat which can carry at most two people.  No girl can be in the presence of a boy unless her boyfriend is present.&#x20;

How can all the boys and girls cross the river?&#x20;

Develop a plan and write down your **algorithm**.


# Cannibals and Priests

Three cannibals and three priests must cross a river using a boat which can carry at most two people.  On either side of the bank, the priests can never be outnumbered by the cannibals or else the cannibals will eat the priests.  The boat cannot cross the river with no people on board.

How can all the cannibals and priests cross the river?

Develop a plan and write down your **algorithm**.


# Family

Parents with two children - a son and a daughter - came to a wide river. There was no bridge there. The only way to get to the other side was to ask a fisherman if he could lend them his boat. However, the boat could carry only one adult or two children. How does the family get to the other side and return the boat to the fisherman?


# Police and the Thief

The ferry can carry no more than 2 people.&#x20;

Only the Adults (mom, dad and policeman) can operate the ferry.  &#x20;

There are two boys and two girls.

Dad can not be in the presence of the girls without Mom.&#x20;

Mom can not be in the presence of the boys without Dad.

The thief can not be alone with any of the family without the policeman.


# Humans and Monkeys

Three humans, one big monkey and two small monkeys are to cross a river:

Only humans and the big monkey can row the boat. At all times, the number of humans on either side of the river must be greater or equal to the number of monkeys on that side. (Or else the humans will be eaten by the monkeys!) The boat only has room for 2 (monkeys or humans). Monkeys can jump out of the boat when it's banked.


# Moving Money

Joe has $5000 worth of gold in a bag.  Sue has $8000 worth of gold in a bag.  Pedro has $13,000 worth of gold in a bag.  Joe, Pedro and Sue want to cross a river with their bags of gold.  The only way to cross the river is to use a row boat that only has 2 seats.  The row boat can handle either 2 people or one person and one bag of gold.  Joe, Sue and Pedro do not trust each other.  At no point can anybody be left in the presence of more gold than they own.

How can Joe, Pedro and Sue cross the river?

Develop a plan to move all three people across the river with their bags of gold and write your **algorithm**.


# Crossing the River

Four people wish to cross a river. They have a boat, but the boat holds at most two people. Each person takes a different amount of time to cross the river; person A takes 20 minutes, person B takes 15 minutes, person C takes 10 minutes, and person D takes 5 minutes. When two people are in the boat, it takes the maximum of their time to cross the river; that is, A and C together would take 20 minutes. What is the smallest crossing time required to get all four people across the river?


# Traveling Salesperson

If a traveling salesperson has to four six cities, how many possible travel routes are there, and which requires driving the shortest distance?

![](/files/-Lso5XyAqp1tsrEwLEnC)


# Logic Problems

{% embed url="<https://docs.google.com/document/d/1vrFnNYWmwqoKp8DpGhIFxi-qglRTt0fcpUfmBrnFva8/edit?usp=sharing>" %}


# CIA Crack the Code

{% embed url="<https://docs.google.com/document/d/1fABETplawplF-y3F-c4p6FtyHDlAwsLElnfibCsv2bc/edit?usp=sharing>" %}

{% embed url="<https://www.cia.gov/kids-page/games/games_code.html>" %}

{% file src="/files/-Ll6P5JwSAj2BZE4MwVq" %}


# IQ Test

{% embed url="<https://docs.google.com/document/d/1f1iMUfsmBkQs8uCCiOMu_flColmaOuYoq3j6ReTinw4/edit?usp=sharing>" %}

{% file src="/files/-LlC6HbTl7JBa-9jeHNl" %}


# Puzzles

## Keep It Even

Take 16 items and put them in rows of 4 each.  Remove 6 leaving an even number of objects in each row and each column.

![](/files/-LoPV3UxQq9uxHyTo3ye)

Source: <https://www.icollector.com/16-ANIMAL-PROOF-COINS-FROM-AROUND-THE-WORLD-APPROXIMATELY-2-oz-OF-SILVER_i9595385>

## Eight Squares

Arrange 15 large paperclips (all paperclips need to be the same size) so that they form eight complete squares all the same size.  No match may be overlapped or broken and no square my be formed inside another.

## Zombie

You want to survive the zombie apocalypse.  Each group has *x* people.  The zombie stands in the middle of the group and will pick the *x*th person to eat.  Where should you stand to be the last person standing?


# AP Computer Science Principles Framework

## AP Computer Science Principles Framework 2017

{% embed url="<https://secure-media.collegeboard.org/digitalServices/pdf/ap/ap-computer-science-principles-course-and-exam-description.pdf>" %}

## AP Computer Science Principles Framework 2020

{% embed url="<https://apcentral.collegeboard.org/pdf/ap-computer-science-principles-conceptual-framework-2020-21.pdf?course=ap-computer-science-principles>" %}


# Python Philosphy

Long time Pythoneer Tim Peters succinctly channels the BDFL's guiding principles for Python's design into 20 aphorisms, only 19 of which have been written down.  This Easter Egg is also known as PEP 20 -- The Zen of Python.

## The Zen of Python

![](/files/-LjxYEpH_aIYA4qAMrnt)

Reference: <https://www.python.org/dev/peps/pep-0020/>


# How to Practice Python

When practicing and learning a new skill, making slight changes during repeat practice sessions may help people master the skill faster than practicing the task in precisely the same way, Johns Hopkins researchers report.

In a study of 86 healthy volunteers asked to learn a computer-based motor skill, those who quickly adjusted to a modified practice session the second time around performed better than when repeating their original task, the researchers found. The results support the idea that a process called reconsolidation, in which existing memories are recalled and modified with new knowledge, plays a key role in the strengthening of motor skills, says senior study author Pablo A. Celnik, M.D., professor of physical medicine and rehabilitation at the Johns Hopkins University School of Medicine.

"What we found is if you practice a slightly modified version of a task you want to master, you actually learn more and faster than if you just keep practicing the exact same thing multiple times in a row," says Celnik. The work, described in the Jan. 28 edition of the journal Current Biology, has implications not only for leisure skills, like learning to play a musical instrument or a sport, but also for helping patients with stroke and other neurological conditions regain lost motor function, he says.

Sources:

Johns Hopkins Medicine. "Want to learn a new skill? Faster? Change up your practice sessions." ScienceDaily. ScienceDaily, 28 January 2016. <[www.sciencedaily.com/releases/2016/01/160128130955.htm](http://www.sciencedaily.com/releases/2016/01/160128130955.htm)>.

Wymbs, N., Bastian, A., & Celnik, P. (2016). Motor skills are strengthened through reconsolidation. Current Biology, 26(3), 338-343. doi:10.1016/j.cub.2015.11.066


# microbit

{% embed url="<https://docs.google.com/presentation/d/1e1qwanzjt4JFRp2STMQQWAtkbIUml2bdQWcU_yA1wS8/edit?usp=sharing>" %}

## Python Editor for micro:bit

{% embed url="<https://python.microbit.org/v/2.0>" %}

## Button Press

```python
from microbit import *

while True:
    if button_a.is_pressed() and button_b.is_pressed():
        display.scroll("AB")
    elif button_a.is_pressed():
        display.scroll("A")
    elif button_b.is_pressed():
        display.scroll("B")
    sleep(100)
```

## Detect Movement

```python
from microbit import *

while True:
    reading = accelerometer.get_x()
    if reading > 20:
        display.show("R")
    elif reading < -20:
        display.show("L")
    else:
        display.show("-")
```

## Random Numbers

```python
from microbit import *
import random

display.show(str(random.randint(1, 6)))
```

## Gestures

MicroPython is able to recognize the following gestures: up, down, left, right, face up, face down, freefall, 3g, 6g, 8g, shake. Gestures are always represented as strings. While most of the names should be obvious, the 3g, 6g and 8g gestures apply when the device encounters these levels of g-force (like when an astronaut is launched into space).

```python
from microbit import *

while True:
    gesture = accelerometer.current_gesture()
    if gesture == "face up":
        display.show(Image.HAPPY)
    else:
        display.show(Image.ANGRY)
```

## Magic-8

A Magic-8 ball is a toy first invented in the 1950s. The idea is to ask it a yes/no question, shake it and wait for it to reveal the truth.

```python
from microbit import *
import random

answers = [
    "It is certain",
    "It is decidedly so",
    "Without a doubt",
    "Yes, definitely",
    "You may rely on it",
    "As I see it, yes",
    "Most likely",
    "Outlook good",
    "Yes",
    "Signs point to yes",
    "Reply hazy try again",
    "Ask again later",
    "Better not tell you now",
    "Cannot predict now",
    "Concentrate and ask again",
    "Don't count on it"
    "My reply is no",
    "My sources say no",
    "Outlook not so good",
    "Very doubtful",
]

while True:
    display.show("8")
    if accelerometer.was_gesture("shake"):
        display.clear()
        sleep(1000)
        display.scroll(random.choice(answers))
```

## Built-in Images

* Image.HAPPY&#x20;
* Image.HEART\_SMALL&#x20;
* Image.HAPPY&#x20;
* Image.SMILE&#x20;
* Image.SAD&#x20;
* Image.CONFUSED&#x20;
* Image.ANGRY&#x20;
* Image.ASLEEP&#x20;
* Image.SURPRISED&#x20;
* Image.SILLY&#x20;
* Image.FABULOUS&#x20;
* Image.MEH&#x20;
* Image.YES&#x20;
* Image.NO&#x20;
* Image.CLOCK12&#x20;
* Image.CLOCK11&#x20;
* Image.CLOCK10&#x20;
* Image.CLOCK9&#x20;
* Image.CLOCK8&#x20;
* Image.CLOCK7&#x20;
* Image.CLOCK6&#x20;
* Image.CLOCK5&#x20;
* Image.CLOCK4&#x20;
* Image.CLOCK3&#x20;
* Image.CLOCK2&#x20;
* Image.CLOCK1&#x20;
* Image.ARROW\_N&#x20;
* Image.ARROW\_NE&#x20;
* Image.ARROW\_E&#x20;
* Image.ARROW\_SE&#x20;
* Image.ARROW\_S&#x20;
* Image.ARROW\_SW&#x20;
* Image.ARROW\_W&#x20;
* Image.ARROW\_NW&#x20;
* Image.TRIANGLE&#x20;
* Image.TRIANGLE\_LEFT&#x20;
* Image.CHESSBOARD&#x20;
* Image.DIAMOND&#x20;
* Image.DIAMOND\_SMALL&#x20;
* Image.SQUARE&#x20;
* Image.SQUARE\_SMALL&#x20;
* Image.RABBIT&#x20;
* Image.COW&#x20;
* Image.MUSIC\_CROTCHET&#x20;
* Image.MUSIC\_QUAVER&#x20;
* Image.MUSIC\_QUAVERS&#x20;
* Image.PITCHFORK&#x20;
* Image.XMAS&#x20;
* Image.PACMAN&#x20;
* Image.TARGET&#x20;
* Image.TSHIRT&#x20;
* Image.ROLLERSKATE&#x20;
* Image.DUCK&#x20;
* Image.HOUSE&#x20;
* Image.TORTOISE&#x20;
* Image.BUTTERFLY&#x20;
* Image.STICKFIGURE&#x20;
* Image.GHOST&#x20;
* Image.SWORD&#x20;
* Image.GIRAFFE&#x20;
* Image.SKULL&#x20;
* Image.UMBRELLA&#x20;
* Image.SNAKE


# Turtle Graphics

## Introduction

Turtle graphics was part of the original Logo programming language developed by Wally Feurzig and Seymour Papert in 1966 to teach students to code.  &#x20;

{% embed url="<https://docs.google.com/presentation/d/1j43pi2ke_gB5iCcR04TuqqWPN7NaNwyx82bwfWJoNp8/edit?usp=sharing>" %}

You can use the CS50 Sandbox with the X Window option to use Turtle Graphics.

Imagine a robotic turtle starting at (0, 0) in the x-y plane. After an import turtle, give it the command turtle.forward(15), and it moves (on-screen!) 15 pixels in the direction it is facing, drawing a line as it moves. Give it the command turtle.right(25), and it rotates in-place 25 degrees clockwise.

By combining together these and similar commands, intricate shapes and pictures can be drawn.  Here's an example:

![Circles with different colors](/files/-LkJYHg9zBkhrxCPxzkW)

The first step in using Python's turtle graphics system is to import the turtle module.  Let's try using turtle in Python's interactive mode. &#x20;

```python
$ python
Python 3.7.1 (default, Feb 20 2019, 02:45:44) 
[GCC 7.3.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import turtle
```

## Turtle Commands

| Command                        | Description                                                                                           |
| ------------------------------ | ----------------------------------------------------------------------------------------------------- |
| turtle.forward(*distance*)     | Move the turtle forward by the specified *distance*, in the direction the turtle is headed.           |
| turtle.backward(*distance*)    | Move the turtle backward by *distance*, opposite to the direction the turtle is headed.               |
| turtle.home()                  | Move turtle to the origin – coordinates (0,0) – and set its heading to its start-orientation.         |
| turtle.penup()                 | Pull the pen up – no drawing when moving.                                                             |
| turtle.pendown()               | Pull the pen down – drawing when moving.                                                              |
| turtle.pencolor(*colorstring*) | Set pencolor to *colorstring*, which is a Tk color specification string, such as "red", "yellow" etc. |
| turtle.circle(*radius)*        | Draw a circle with given *radius*.                                                                    |
| turtle.shape("turtle")         | Sets the turtle shape to turtle.                                                                      |
| turtle.undo()                  | Undo (repeatedly) the last turtle action(s)                                                           |
| turtle.clear()                 | Erases all drawings that currently appear in the graphics window.                                     |

### Show Turtle

The Python turtle is initially position in the center of the graphics window.  To display the turtle in the window, you can use the turtle.showturtle() command, to hide the turtle, you can use the turtle.hideturtle() command.

```python
>>> turtle.showturtle()
```

The Python turtle is initially positioned in the center of the graphics window.  The arrowhead shows the direction that the turtle is currently facing. The default heading is 0 degree.

![Result of the turtle.showturtle() command](/files/-LkJaDLXwkGydU8LoUrX)

### Shapes

The turtle.shapes command sets the turtle shape to one of these shapes: “arrow”, “turtle”, “circle”, “square”, “triangle”, and “classic”.

```python
>>> turtle.shape("turtle")
```

![Result of the turtle.shape("turtle") command](/files/-LkJaZdipwKVX-DwtsI6)

### Forward and Backward

The turtle.forward(*distance*) or turtle.fw(*distance*) and turtle.backward(*distance*) or turtle.bk(*distance*) moves the turtle forward or backward by the specified *distance*, in the direction the turtle is headed.

```python
>>> turtle.forward(100)
```

![Result of the turtle.forward(100) command](/files/-LkJalC1ZkBDpx1M4u5G)

### Turning

You can turn the turtle to face a different direction by using either the turtle.right(angle) or turtle.left(angle) command. &#x20;

```python
>>> turtle.right(90)
```

![Result of the turtle.right(90) command](/files/-L__C_Tw0iwCFUq1mv2b)

These are the angles in a Cartesian or x-y plane.

![Cartesian Plane](/files/-L_X7Lkjy6QjJWTRV9BT)

### Pen Up and Down

The turtle.penup() command pulls the pen up so there will be no drawing when the pen moves.  The turtle.pendown() command pulls the pen down.

```python
>>> turtle.penup()
>>> turtle.pendown()
```

### Drawing Circles

The turtle.circle(radius) command makes the turtle draw a circle with a radius you specify.  For example.

```python
>>> turtle.circle(100)
```

![Result of the turtle.circle(100) command](/files/-L_X4fjrFsRi1dtWse2V)

### Drawing Dots

The turtle.dot(*size*, *color*) command draws simple dots.

```python
>>> turtle.dot(100, "red")
```

![Result of the turtle.dot(100, "red") command](/files/-L__DvFh7d8VmGz7W56L)

### Changing the Pen Size

You can use the turtle.pensize(*width*) command to change the width of the turtle's pen, in pixels. &#x20;

```python
>>> turtle.pensize(5)
```

### Changing the Drawing Color

You can use the turtle.pencolor(*color*) command to change the turtle's drawing color.  The color argument is the name of a color, as a string.

```python
>>> turtle.pencolor('red')
```

### Changing the Background Color

You can use the turtle.bgcolor(*color*) to change the background color of the turtle's graphics window.  The color argument is the name of a color, as a string.

```python
>>> turtle.bgcolor('green')
```

### Moving the Turtle to a Specific Location.

The pixel in the center of the graphics window is at the position (0,0) &#x20;

You can use the turtle.goto(*x, y*) command to move the turtle from its current location to a specific position in the graphics window.&#x20;

```python
>>> turtle.goto(100,100)
```

If the turtle's pen is down, a line will be drawn as the turtle moves.

![Coordinate Plane](/files/-L_XNjxelYvco_zIbeoL)

### Getting the Turtle's Current Position

You can use the turtle.pos() command to display the turtle's current position.

```python
>>> turtle.pos()
```

### Displaying Text in the Graphics Window

You can use the turtle.write(*text*) command to display text in the graphics window.

```python
>>> turtle.write("Hello, World!")
```

![Result of the turtle.write("Hello, World!") command](/files/-L_XOXcBKjsNcCinKXpJ)

### Resetting the Screen

* The turtle.reset() command erases all drawings that currently appear in the graphics window, resets the drawing color to black and resets the turtle to its original position at the center of the screen.
* The turtle.clear() command erases all drawings that currently appear in the graphics window.
* The turtle.clearscreen() command erases all drawings that currently appear in the graphics window.

```python
>>> turtle.reset()
>>> turtle.clear()
>>> turtle.clearscreen()
```

### Undo

The turtle.undo() command undoes the previous command.

```python
>>> turtle.undo()
```

## Reference

Python 3's Turtle Graphics Reference Page&#x20;

[https://docs.python.org/3.3/library/turtle.html](https://docs.python.org/3.3/library/turtle.html?highlight=turtle)


# Turtle Examples

## Square

{% embed url="<https://repl.it/@MatthewCheng1/Turtle-Examples>" %}

## Circle

{% embed url="<https://repl.it/@MatthewCheng1/Python-circle>" %}


# Turtle Activities

## Stick Figure

![Courtesy of self](/files/-LkLlfnDMxNdQ-D7QEi0)

## Olympic Rings

The Olympic flag was created under the guidance of Baron Coubertin in 1913 was first hoisted in 1920 in Antwerp, Belgium at the 1920 Summer Olympics. The five rings represent the five continents of the world.

![Source: Wikipedia](/files/-LkLjWsefAgnPGwaQ_zy)

## Philosopher's Stone

The Squared Circle is an alchemical symbol from the 17th century illustrating the interplay of the four elements of matter symbolizing the philosopher's stone.

![Source: Wikipedia](/files/-LkJjtmYCsztXvRo2irB)

## House and Trees

![Source: PinClipart.com](/files/-LkJljnJFkvn1QB-KBwV)

## Constellation Activity

A constellation is a group of stars that form an imaginary outline or pattern on a celestial sphere, typically representing an animal, mythological person or creature, a god or an inanimate object.  Find a constellation you would like to draw.

* Identify the coordinates for the stars and create dots for them.
* Display the names of each star.
* Connect the stars.

![Some constellations look like people or animals. Sagittarius looks like a teapot. Source: NASA](/files/-LkJZspToM0PMChxMUJj)


# Turtle Maze Problems

## Problems

1. Load the appropriate image&#x20;
2. Bring the turtle to the maze starting point
3. Figure out the commands to have your turtle find its way through the maze.

```python
import turtle
turtle.showturtle()
turtle.shape("turtle")
# load the appropriate image
turtle.bgpic('maze1.png')
turtle.penup()
# bring the turtle to the starting point
turtle.goto(-70, 210)
turtle.pendown()
turtle.pencolor("red")
# write your code below



# press enter in the Terminal to exit the program
input()
```

The link below loads the images into the CS50 Sandbox.  It also includes the source code above as maze1.py

<http://bit.ly/2UVEq1G>

## Problem 1

![](/files/-LoqNc71_WLaG7dKc5FD)

## Problem 2

![](/files/-LoqNhYm6aSXHR9ZFb13)

## Problem 3

![](/files/-LoqNns3UdrWhYe55ztt)

## Problem 4

![](/files/-LoqNruaXvj0HVzTYzHb)

## Problem 5

![](/files/-LoqNwf9rf0phZ-PU1k7)

## Problem 6

![](/files/-LoqO-vd7JArT6_gTBNo)

## Problem 7

![](/files/-LoqQeS_2F9y4cDTQtVh)

## Problem 8

![](/files/-LoqOHI1NmEzIbbPJb6t)

## Problem 9

![](/files/-LoqOLgbZVLvDSRZMUsU)

## Problem 10

![](/files/-LoqOOiLLsSSr1yfaLzd)


# Turtle Graphics with loops

## Shapes

To start, let's try some basic designs without loops. &#x20;

### Square

![](/files/-LabBdbNmdjk0_vvqgdB)

{% code title="square.py" %}

```python
import turtle
turtle.showturtle()
turtle.shape("turtle")
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
```

{% endcode %}

{% hint style="info" %}
To add color to your design, wrap the following lines of code before and after the turtle movements.
{% endhint %}

```python
turtle.fillcolor("green")
turtle.begin_fill()
turtle.end_fill()
```

![](/files/-Lae5cIM0RrtA9znIEga)

```python
import turtle
turtle.showturtle()
turtle.shape("turtle")
turtle.fillcolor("green")
turtle.begin_fill()
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.forward(50)
turtle.right(90)
turtle.end_fill()
```

{% hint style="info" %}
turtle.pencolor("red") # this statement changes the pen's color.
{% endhint %}

### Rectangle

Let's draw a rectangle using variables.  In Python, you name a variable and assign it a value.   Replace each length and angle with a variable.

{% code title="rectangle.py" %}

```python
import turtle
turtle.showturtle()
turtle.shape("turtle")
length1 = 100
length2 = 200
angle = 90
turtle.forward(length1)
turtle.right(angle)
turtle.forward(length2)
turtle.right(angle)
turtle.forward(length1)
turtle.right(angle)
turtle.forward(length2)
turtle.right(angle)

```

{% endcode %}

![](/files/-Lae8AfTjswlnkvkqy3H)

### Zigzag

### Star

![](/files/-LabCzFOqecNZOUehZ5d)

{% code title="zigzag.py" %}

```python
import turtle
length = 25
angle = 45
turtle.showturtle()
turtle.shape("turtle")
turtle.forward(length)
turtle.right(angle)
turtle.forward(length)
turtle.left(angle)
turtle.forward(length)
turtle.right(angle)
turtle.forward(length)
turtle.left(angle)
turtle.forward(length)
turtle.right(angle)
turtle.forward(length)
turtle.left(angle)
turtle.forward(length)
turtle.right(angle)
turtle.forward(length)
```

{% endcode %}

### Spiral

![](/files/-LabFDl4ly9naFIKqq14)

{% code title="spiral.py" %}

```python
import turtle
length = 10
angle = 90
turtle.showturtle()
turtle.shape("turtle")
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
turtle.forward(length+length)
turtle.right(angle)
length = length + 10
```

{% endcode %}

## Loops

Loops are used when you have a block of code that you want to repeat.  &#x20;

A for loop is used when you have a block of code which you want to repeat a fixed number of times.   The for loop iterates through the block of indented code.

|                   |                                           |
| ----------------- | ----------------------------------------- |
| for x in range(): | x is a variable that steps through values |
| \<do something>   | do something in the indented block        |

{% code title="for.py" %}

```python
for x in range(4):
    print(x)
```

{% endcode %}

```bash
$ python for.py
0
1
2
3
4
```

### Square

{% code title="square2.py" %}

```python
import turtle
turtle.showturtle()
turtle.shape("turtle")
for x in range(4):
    turtle.forward(50)
    turtle.right(90)
```

{% endcode %}

### Spiral

{% code title="spiral2.py" %}

```python
import turtle
length = 10
angle = 90
turtle.showturtle()
turtle.shape("turtle")
for x in range(10):
    turtle.forward(length+length)
    turtle.right(angle)
    length = length + 10
```

{% endcode %}

![](/files/-LaeFyQY-Nx7yWcgnGLV)

{% code title="spiral3.py" %}

```python
import turtle
angle = 91
turtle.showturtle()
turtle.shape("turtle")
for x in range(100):
    turtle.forward(x)
    turtle.left(angle)
```

{% endcode %}

![](/files/-LaeNNHjJyf9U_1MwXpn)

{% code title="circle.py" %}

```python
import turtle
angle = 91
turtle.showturtle()
turtle.shape("turtle")
for x in range(100):
    turtle.circle(x)
    turtle.left(angle)
```

{% endcode %}

### Polygons

| Shape         | Sides | Interior Angle |
| ------------- | ----- | -------------- |
| Triangle      | 3     | 60             |
| Quadrilateral | 4     | 90             |
| Pentagon      | 5     | 108            |
| Hexagon       | 6     | 120            |
| Heptagon      | 7     | 128.571        |
| Octagon       | 8     | 135            |
| Nonagon       | 9     | 140            |
| Decagon       | 10    | 144            |
| Hendecagon    | 11    | 147.273        |
| Dodecagon     | 12    | 150            |

{% code title="triangle.py" %}

```python
import turtle
length = 100
angle = 120
turtle.showturtle()
turtle.shape("turtle")
for i in range(3):
    turtle.forward(length)
    turtle.right(angle)
```

{% endcode %}

### Star

Using a loop, we can produce an eight point star.

![](/files/-LbD7qX9szv_yiVoeSCs)

{% code title="star1.py" %}

```python
import turtle
turtle.showturtle()
turtle.shape("turtle")
turtle.pencolor('green')
for x in range(13):
        turtle.forward(200)
        turtle.left(150)
```

{% endcode %}

What happens if we try changing the range and the left angle?

![](/files/-LbD8Wg6AXZY9VxQ657w)

{% code title="star2.py" %}

```python
import turtle
turtle.showturtle()
turtle.shape("turtle")
turtle.pencolor('purple')
for x in range(100):
        turtle.forward(200)
        turtle.left(175)
```

{% endcode %}

### Spiral Circle

![](/files/-LbDB3CeYsu2t2nrjflN)

{% code title="spiral.py" %}

```python
import turtle
turtle.showturtle()
turtle.shape("turtle")
turtle.pencolor('pink')
for i in range(180):
    turtle.forward(100)
    turtle.right(30)
    turtle.forward(20)
    turtle.left(60)
    turtle.forward(50)
    turtle.right(30)
    turtle.penup()
    turtle.setposition(0, 0)
    turtle.pendown()
    turtle.right(2)
```

{% endcode %}


# Turtle Snake

{% embed url="<https://docs.google.com/presentation/d/15-9l7QkQyJfcGAcrWBzCZ_J_583SorQXsxl3zqfd7eQ/edit?usp=sharing>" %}


# Turtle Graphics with Conditionals

## Conditionals

An if conditional statement can be True or False.  When the if statement executes, the condition is tested and if it is true, the indented block of code is executed. &#x20;

|                              |   |
| ---------------------------- | - |
| if \<conditional statement>: |   |
| \<do something>              |   |
| else:                        |   |
| \<do something>              |   |

If you have a pattern where every other statement alternates, you can use use the values of the stepper variable to determine if the value of the variable is odd or even.

### Star

![](/files/-LbD9D7stelcB0UoK9om)

{% code title="star3.py" %}

```python
import turtle
turtle.showturtle()
turtle.shape("turtle")
turtle.pencolor('red')
for x in range(20):
        turtle.forward(100)
        if x % 2 == 0:
            turtle.left(175)
        else:
            turtle.left(225)
```

{% endcode %}

### ZigZag

![](/files/-LbD9q6l8Hl3KMdMUhoa)

{% code title="zigzag2.py" %}

```python
import turtle
turtle.showturtle()
turtle.shape("turtle")
turtle.pencolor('red')
for x in range(10):
    if x % 2 == 0:
        turtle.forward(25)
        turtle.right(45)
    else:
        turtle.forward(25)
        turtle.right(45)
```

{% endcode %}

###


# Output

{% embed url="<https://docs.google.com/presentation/d/1KNFs4MhlXDs9vo8WI9LdDUhvhVnkwZ8tdlMR-AesKcI/edit?usp=sharing>" %}

## print function

The print function prints output to the console.

{% code title="hello.py" %}

```python
print("Hello World!")
```

{% endcode %}

{% code title="Terminal" %}

```bash
$ python hello.py 

```

{% endcode %}

{% code title="Output" %}

```
Hello World!
```

{% endcode %}

{% hint style="info" %}
Objects are automatically converted to string representations for printing.
{% endhint %}

Reference: <https://docs.python.org/3/library/functions.html#print>

## String Concatenation and Formatting

String concatenation is the operation of joining character strings.  In Python, there are several ways to concatenation strings. &#x20;

### Comma

```python
print("hello","world")
```

### String Concatenation

```python
print("hello" + " " + "world")
```

### String Interpolation

```python
print("{0} {1}".format("hello","world"))
```

### Format Literals&#x20;

Python 3.6 introduced format literals, with a more elegant syntax (less redundancy).

```python
greeting = "hello"
who = "humans"
print(f"{greeting} {who}")
```


# Output Examples

{% embed url="<https://repl.it/@MatthewCheng1/Python-Output>" %}


# Output Mistakes

## Mistake #1

What's the mistake in this code?  How would you fix it?

```python
print hello
```

{% embed url="<https://repl.it/@MatthewCheng1/Output-Mistake-1>" %}

## Mistake #2

Why does this code result in a mistake?  How would you fix it?

```python
print("hello)
```

{% embed url="<https://repl.it/@MatthewCheng1/Output-Mistake-2>" %}

## Mistake #3

Why does this code result in a mistake?  How would you fix it?

{% embed url="<https://repl.it/@MatthewCheng1/Output-Mistake-3>" %}


# Variables

## Introduction

In Math class, you learned that a variable is a symbol for a number that you don't know yet.  In Computer Science, a variable is information that is stored in a program.

{% embed url="<https://docs.google.com/presentation/d/12qaq8XfcTtMK1USXR9vO-hpnmCZlphi-OHMerYIP0Dg/edit?usp=sharing>" %}

## Variables in Python

* A variable name refers to a particular object.
* A variable is a location in memory where a programmer can store a value. &#x20;
* Variables are created when first assigned. &#x20;
* The type of the variable is determined by Python automatically.

{% hint style="info" %}
A Variable is data that can change.&#x20;
{% endhint %}

## Python Data Types

| Data Type | Explanation                                                                                                     | Examples             |
| --------- | --------------------------------------------------------------------------------------------------------------- | -------------------- |
| int       | positive or negative whole numbers                                                                              | 1, 2, 3, 4, 5        |
| float     | floating point numbers (numbers with a decimal)                                                                 | 1.1, 2.2, 3.3        |
| string    | a set of characters (letters, numbers, and/or special characters) enclosed by single or double quotation marks. | "hamster", 'gerbils' |
| boolean   | Boolean values are either True or False                                                                         | True, False          |

{% hint style="warning" %}
&#x20;Variable names can be any length.  However, stick to variable names that are short, sweet and to the point.  Good variable names in Python will make your code easy to read and understand.
{% endhint %}

## Variable Name Rules

| Rule                                                                     | Examples                                                                                                                                                                                                        |
| ------------------------------------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Must begin with a letter or underscore.                                  | x, y, points, robux, money, friends                                                                                                                                                                             |
| Other characters can be letters, numbers or underscore.                  | x2, roblox\_player, jail\_break                                                                                                                                                                                 |
| Are case sensitive                                                       | **student** is different than **Student**                                                                                                                                                                       |
| Python has keyword/reserved words that you cannot use as variable names. | False, class, finally, is, return, None, continue for, lambda, try, True, def, from, nonlocal, while, and, del global, not, with, as, elif, if, or, yield, assert, else, import, pass, break, except, in, raise |
| Can be any length greater than or equal to 1 but...                      | you’re the one who has to remember what it is!                                                                                                                                                                  |

{% hint style="danger" %}
Variable names are case sensitive.
{% endhint %}

## Assigning a value to a Variable

To assign a value to a variable, use the = sign.

```python
x = 3
name = "Sam"
robux = 100.50
```

## Variable Roles

Variables have typical uses that are called variable roles.  Variable roles are not the same as types of variables (integer, float, string, boolean, etc.) since the concept of roles is a classification telling what kind of a task a variable has in a certain program.

{% embed url="<https://docs.google.com/presentation/d/1VjP4oyFKJfGDoww18OaUF1Fz_m3-h7Ijj6Jh9iD8vf4/edit?usp=sharing>" %}

| Role         | Pattern                                                 | Example                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                     |
| ------------ | ------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| Constant     | Assigned once                                           | <p>Assigned at the beginning of a program or at the head of a code block.  By convention, make this variable name in all caps. </p><p></p><p>Example:</p><p><strong>RATE</strong> = 7</p>                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| Most recent  | Fluctuating                                             | <p>Assigned user input.</p><p></p><p>Example:</p><p><strong>name</strong> = input(“What’s your name? “)</p>                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                 |
| Accumulator  | Running total                                           | <p>1. Initialize</p><p>2. Accumulate</p><p>3. Print<br></p><p>Example:</p><p><strong>sum</strong> = 0 # initialize to 0.</p><p>for x in range(3):</p><p>   num = int(input("Give me a number: "))</p><p>   <strong>sum</strong> = <strong>sum</strong> + num</p><p>print(<strong>sum</strong>)</p>                                                                                                                                                                                                                                                                                                                          |
| Best-so-far  | Record holder                                           | <p>Keep track of the record holder while iterating.<br></p><p>Pattern:</p><p>1. Initialize to worst-possible value before the loop or first value in a sequence of values.</p><p>2. During iteration, compare to best-so-far and assign to the new value, if needed.</p><p>3. After the loop, best-so-far will be the best-so-far.<br></p><p>Example:</p><p>x = 0</p><p>while x < 3:</p><p>     num = int(input("Give me a number: "))</p><p>     if x == 0:</p><p>         <strong>max</strong> = num</p><p>     else:</p><p>         if num > max:</p><p>            <strong>max</strong> = num</p><p>     x = x + 1 </p> |
| One-Way Flag | <p>Variable will be reset once condition is met<br></p> | <p>Pattern:</p><p>1. Initialize the flag so the condition has not been met.</p><p>2. With each iteration, check for the condition and change the flag if true.<br></p><p>Example:</p><p><strong>done</strong> = False</p><p>while not done:</p><p>     <strong>done</strong> = True</p>                                                                                                                                                                                                                                                                                                                                     |
| Stepper      | Step through a pre-determined sequence of values        | <p>Iterates a specific number of times.</p><p></p><p>Example:</p><p><strong>x</strong> = 0</p><p>while <strong>x</strong> < 5:</p><p>    print(<strong>x</strong>)</p><p>    x = x + 1</p><p></p><p>for x in range(5):</p><p>    print(x)</p>                                                                                                                                                                                                                                                                                                                                                                               |
| Walker       | Elements of iterator                                    | <p>Elements of a list during iteration.<br></p><p>Example:</p><p>for <strong>x</strong> in friends:</p><p>   print(<strong>x</strong>)<br></p><p>Elements of a dictionary during iteration.<br></p><p>Example:</p><p>for <strong>key</strong> in d:</p><p>    print(key, d\[<strong>key</strong>])</p>                                                                                                                                                                                                                                                                                                                      |
| Temporary    | Needed only for a short period of time.                 | <p>The tax is computed into the temporary tax </p><p></p><p>Example:</p><p>income = float(input("Income: "))</p><p>TAXRATE = .25</p><p><strong>tax</strong> = TAXRATE \* income</p>                                                                                                                                                                                                                                                                                                                                                                                                                                         |


# Variable Data Type Examples

{% embed url="<https://repl.it/@MatthewCheng1/Python-Variable-Data-Types>" %}


# Variable Role Examples

{% embed url="<https://repl.it/@MatthewCheng1/Python-Variable-Roles>" %}


# Variables Mistakes

## Mistake #1

What's the mistake in this code?  How can you fix it?

{% embed url="<https://repl.it/@MatthewCheng1/Variables-Mistake-1>" %}

## Mistake #2

What's the mistake in this code?  How can you fix it?

{% embed url="<https://repl.it/@MatthewCheng1/Variables-Mistake-2>" %}


# Variables Problems

## Problem 1

print("Problem 1")

Assign the variable name to your name and combine it with the words, “Welcome to my program!”.

## Problem 2

print("Problem 2")

Create variables for name, street address, city, state and zip code.

Print your name and mailing address as it would appear on the outside of an envelope.

![](/files/-LqWaas3Gbn6ROHdNTxQ)

## Problem 3

print("Problem 3")

In this problem, you're going to write a paragraph about yourself.

Create the following variables and assign each to a sentence about yourself.

* sentence1
* sentence2
* sentence3
* sentence4
* sentence5

Print the paragraph.

## Problem 4

print("Problem 4")

The 8 parts of speech are a noun, verb, adjective, pronoun, preposition, conjunction and interjection. &#x20;

| part of speech | meaning                                                                                                                                                                                                               |
| -------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| noun           | a word (other than a pronoun) used to identify any of a class of people, places, or things ( common noun ), or to name a particular one of these ( proper noun ).                                                     |
| verb           | a word used to describe an action, state, or occurrence, and forming the main part of the predicate of a sentence, such as hear, become, happen.                                                                      |
| adjective      | a word or phrase naming an attribute, added to or grammatically related to a noun to modify or describe it.                                                                                                           |
| adverb         | a word or phrase that modifies or qualifies an adjective, verb, or other adverb or a word group, expressing a relation of place, time, circumstance, manner, cause, degree, etc. (e.g., gently, quite, then, there ). |
| preposition    | a word governing, and usually preceding, a noun or pronoun and expressing a relation to another word or element in the clause, as in “the man on the platform", "she arrived after dinner", "what did you do it for?" |
| conjunction    | a word used to connect clauses or sentences or to coordinate words in the same clause (e.g. and, but, if).                                                                                                            |
| interjection   | an exclamation, (e.g. ah!, dear me! ).                                                                                                                                                                                |

Create the following variables for each part of speech and assign appropriate values.

* noun&#x20;
* verb&#x20;
* adjective&#x20;
* adverb&#x20;
* preposition&#x20;
* conjunction&#x20;
* interjection

Print each variable on a single line.

## Problem 5

![Source: Mad Libs](/files/-LkTAqMikQeH5wSsu60j)

print("Problem 5")

Print a sentence about yourself using at least 4 variables from Problem 4.

## Problem 6

print("Problem 6")

Assign new values to the variables you created in Problem 5 about your friend. Print the new sentence.

## Problem 7

print("Problem 7")

How much money do you have?  Assign this value to the variable money.

Print a sentence using the variable money.


# Math

## Introduction

You can use Python to solve Math problems!

{% embed url="<https://docs.google.com/presentation/d/1HPQ1KvSYY341tlj7mXA7b2g76qBbz74V5XQAGeFgdHE/edit?usp=sharing>" %}

## Python Math Operators

| Symbol | Operation            |
| ------ | -------------------- |
| +      | addition             |
| -      | subtraction          |
| \*     | multiplication       |
| /      | division             |
| //     | integer division     |
| \*\*   | power or exponent    |
| %      | remainder or modulus |
| ()     | parenthesis          |

{% hint style="info" %}
&#x20;Python follows the Order of Operations, just like you learned in Math class.
{% endhint %}

| Order of Operations Precedence                | Symbols |
| --------------------------------------------- | ------- |
| Parentheses                                   | ()      |
| Exponent                                      | \*\*    |
| Multiplication, Division (from left to right) | \* / // |
| Addition, Subtraction (from left to right)    | + -     |

{% hint style="warning" %}
When doing Math in Python, you must specify multiplication when you want multiplication.  For example: 3(4 + 2) instead of 3 \* (4 + 2) will result in an error.
{% endhint %}

## import math

Python has a number of builtin math methods.

```python
import math

# square root
print(math.sqrt(2))

# pi
print(math.pi)
```

## Examples

Write Python code that does the following:

1. Assign the variable bday to the month of your bday.
2. Multiply bday by 5.
3. Add 6 to bday.
4. Multiply bday by 4.
5. Add 9 to bday.
6. Multiply bday by 5.
7. Add the number number of the day of your bday.
8. Subtract 165 from bday.
9. Print the value of bday.

```python
# Example birthday of 1/1
bday = 1
bday = bday * 5
bday = bday + 6
bday = bday * 4
bday = bday + 9
bday = bday * 5
bday = bday + 1
bday = bday - 165
print(bday)
```


# Math Examples

{% embed url="<https://repl.it/@MatthewCheng1/Python-Math-Examples>" %}


# Math Mistakes

## Problem #1

What's the mistake in this code?  How can you fix it?

{% embed url="<https://repl.it/@MatthewCheng1/Python-Math-Mistakes-1>" %}


# Math Problems

## Problem 1

print("Problem 1 - Rectangle Area")

Assign 5 to the variable l and 7 to variable w. Assign the variable Area according to the formula:

$$
Area=lw
$$

![](/files/-LjxbN_Un-wDdmW9jGLv)

Print the value of Area.

## Problem 2

print("Problem 2 - Square Area")

Assign 11 to the variable a. Assign the variable Area according to the formula:

$$
Area=a^2
$$

![](/files/-LjxbuTzjID0iLrnQG-e)

Print the value of Area.

## Problem 3

print("Problem 3 - Circle")

Assign 5 to the variable r. Assign the variable Area and Circumference according to the formula. Print the value of Area and Circumference. &#x20;

{% hint style="info" %}
To access the value of pi, import the Python math library
{% endhint %}

```python
import math # put this on line 1
print(math.pi) # this is the value of pi
```

$$
Area=πr^2
$$

$$
Circumference = 2πr
$$

![](/files/-LjxcNoBnM5D6Jf5dSiP)

Print the value of Area and Circumference.

## Problem 4

print("Problem 4 - Triangle Area")

Assign 11 to the variable b and 5 to the variable h. Assign the variable Area according to the formula.

$$
Area=\frac{1}{2} bh
$$

![](/files/-LjxfWeirl0GoqKT6bYO)

Print the value of Area.

## Problem 5

print("Problem 5 - Parallelogram Area")

Assign 5 to the variable b and 13 to the variable h. Assign the variable Area according to the formula.

$$
Area=bh
$$

![](/files/-Ljxftuaypg4VSMF7bAU)

Print the value of Area.

## Problem 6

print("Problem 6 - Trapezoid Area")

Assign 10 to h, 7 to a and 9 to b. Assign the variable Area according to the formula:

$$
Area=h\frac{a+b}{2}
$$

![](/files/-LjxgKMQW08QbDLi5sL_)

Print the value of Area.

## Problem 7

print("Problem 7 - Kite Area")

Assign 8 to p and 9 to q.

$$
A=\frac{pq}{2}
$$

![](/files/-LpyOwAn-5hysxyuFrsq)

## Problem 8

print("Problem 8 - Rectangular Prism Volume")

Assign 7 to l, 4 to w and 5 to h. Assign the variable Volume according to the formula:

$$
Volume=lwh
$$

![](/files/-LjxgfLFjqLqu2gBwt9w)

Print the value of Volume.

## Problem 9

print("Problem 9 - Cube Volume")

Assign 13 to a. Assign the variable Volume according to the formula:

$$
Volume = a^3
$$

![](/files/-Ljxgugi0v-dVkQzqifw)

Print the value of Volume.

## Problem 10

print("Problem 10 - Pyramid Volume")

Assign 6 to l, 9 to w and 8 to h. Assign the variable Volume according to the formula:

$$
V=\frac{lwh}{3}
$$

![](/files/-Ljxh3oHjyXFNt50lQz6)

Print the value of Volume.

## Problem 11

print("Problem 11 - Cylinder Volume")

Assign 13 to r, 4 to h. Assign the variable Volume according to the formula.

$$
Volume=πr^2h
$$

![](/files/-LjxhOAdeOFkpIsVPDLk)

Print the value of Volume.

## Problem 12

print("Problem 12 - Sphere Volume")

Assign 9 to r. Assign the variable Volume according to the formula.

$$
Volume=\frac{4}{3}\pi r^3
$$

![](/files/-LjxhcEF6K0FilKcnFPK)

Print the value of Volume.

## Problem 13

print("Problem 13 - Cone Volume")

Assign 5 to r and 12 to h. Assign the variable Volume according to the formula.

$$
Volume=\pi r^2\frac{h}{3}
$$

![](/files/-LjxhpC45-k49DZUK4hj)

Print the value of Volume.

## Problem 14

print("Problem 14 - Rectangular Solid Surface Area")

Assign 11 to l, 12 to w and 13 to h. Assign the variable SA according to the formula:

$$
SA=2(wl+hl+hw)
$$

![](/files/-Ljxi1edung1i2KtA2wL)

Print the value of SA.

## Problem 15

print("Problem 15 - Cube Surface Area")

Assign 14 to a. Assign the variable Area according to the formula.

$$
Area=6a^2
$$

![](/files/-LjxiEd9gFONR5QnnLd6)

Print the value of SA.

## Problem 16

print("Problem 16 - Sphere Surface Area")

Assign 15 to r. Assign the variable SA according to the formula.

$$
SA=4πr^2
$$

![](/files/-LjxiT6R48mexufdeUSC)

Print the value of SA.

## Problem 17

print("Problem 17 - Right Cylinder Surface Area")

Assign 9 to r. Assign 6 to h. Assign the variable SA according to the formula:

$$
SA=2πrh+2πr^2
$$

![](/files/-LjxikH_8lQ4kVp8E10E)

Print the Area.

## Problem 18

print("Problem 18 - Triangular Prism Surface Area")

Assign 5 to b. Assign 3 to h. Assign 9 to l. Assign 5 to s. Assign the variable SA according to the formula.

$$
SA=bh+2ls+lb
$$

![](/files/-LjxjEyBVsP_09-5M6Pv)

Print the value of SA.

## Problem 19

print("Problem 19 - Tetrahedron Surface Area")

Assign 9 to a.  Assign the variable SA according to the formula.

$$
SA=\sqrt3 a^2
$$

Print the value of SA.

{% hint style="info" %}
To take the square root of a number, use the math library.
{% endhint %}

```python
import math
math.sqrt(3)
```

![](/files/-LpyQou6nKzSwQyyfnxV)

## Problem 20

print("Problem 20 - Tetrahedron Volume")

Assign 13 to a.  Assign the variable Volume according to the formula.

$$
Volume=\frac{a^3}{6\sqrt2}
$$

![](/files/-LpyRGFR8KJUIKBtf8_6)

Print the value of Volume.


# Math Self Check

Test your knowledge of Python Math!

{% embed url="<https://docs.google.com/forms/d/e/1FAIpQLSc0a3g927hGo8zHuvmDX9T8GXC1S0j3qsv5xw1y00TJGMu_KQ/viewform?usp=sf_link>" %}


# Input

{% embed url="<https://docs.google.com/presentation/d/1WgJ4b9_3h2oQsJ3jjxh76G51pu-iaXkPy-KU3lSxAwc/edit?usp=sharing>" %}

## Introduction

Typically, programs take input from a user, process this input and give the user output.

![](/files/-LVZftDEj76s8O5GjyDD)

## input function

The input() function takes input from your console. It reads the input and converts it to a string.

## Variable Roles

![](/files/-Ld0udJ_c-fcYtF88LSU)

## Changing the data type of the input

| Function | Converts               | Example                                  |
| -------- | ---------------------- | ---------------------------------------- |
| int()    | converts to an integer | num = int(input("Give me an integer: ")) |
| float()  | converts to a float    | num = float(input("Give me a float: "))  |

{% hint style="info" %}
When using the input function, think about about what data type you want.
{% endhint %}

```python
name = input("What's your name? ")
num = int(input("Give me a number: "))
money = float(input("How much money do you have? "))
```

{% hint style="danger" %}
A common mistake is not matching the number of open parenthesis and closed parenthesis.
{% endhint %}

## Example

Write a program that prompts for two numbers. Print the sum, difference, product, and quotient of those numbers.  In addition, print the result of integer division and the modulus operator of those numbers.

{% code title="example1.py" %}

```python
num1 = int(input("Number 1: "))
num2 = int(input("Number 2: "))
print("Sum:", num1 + num2)
print("Difference:", num1 - num2)
print("Product:", num1 * num2)
print("Quotient:", num1 / num2)
print("Integer Division:", num1 // num2)
print("The Remainder of num1 divided by num2:", num1 % num2) 
```

{% endcode %}


# Input Examples

{% embed url="<https://repl.it/@MatthewCheng1/Python-Input-Examples>" %}


# Input Mistakes

## Mistake #1

What's the mistake in this code?  How can you fix it?

{% embed url="<https://repl.it/@MatthewCheng1/Python-if-mistakes>" %}

## Mistake #2

What's the mistake in this code?  How can you fix it?

{% embed url="<https://repl.it/@MatthewCheng1/Python-if-mistake-2>" %}


# Input Problems

## Problem 1

print("Problem 1")

Write a program that asks the user to enter their name.  Print a message that says hello to the user using his or her name.

## Problem 2

print("Problem 2")

Write a program that asks, "What is your favorite color?". Assign the input to the variable named color. Print the following statement, "My favorite color is \_\_\_\_" where \_\_\_\_ is the value of the variable color.

## Problem 3

print("Problem 3")

Write Python code that asks, "What town do you live in?". Assign the input to the variable named town. Print the following statement, "I live in \_\_\_\_" where \_\_\_\_ is the value of the variable town.

## Problem 4

print("Problem 4")

Write Python code that asks, "How many brothers do you have?". Assign the input to the variable named brothers.

Print the following statement, "I have \_\_\_\_ brothers." where \_\_\_\_ is the value of the variable brothers.

{% hint style="danger" %}
Brothers don't float.
{% endhint %}

Next, ask, "How many sisters do you have?". Assign the input to the variable named sisters.

Print the following statement, "I have \_\_\_\_ sisters." where \_\_\_\_ is the value of the variable sisters.

{% hint style="warning" %}
Sisters aren't strings.
{% endhint %}

Assign the variable siblings to the sum of brothers and sisters.

Print the following statement, "I have \_\_\_\_ siblings."

## Problem 5

print("Problem 5")

Write a program that asks the user to enter the length and width of a room. &#x20;

Assign the variable area according to the formula:

$$
Area = lw
$$

Assign the variable perimeter according to the formula:

$$
Perimeter=2l+2w
$$

Print the following statement, "The area of the rectangle is \_\_\_\_" where \_\_\_\_ is the area of the rectangle .

Print the following statement, "The perimeter of the rectangle is \_\_\_\_" where \_\_\_\_ is the perimeter of the rectangle.

## Problem 6

print("Problem 6")

Write Python code that asks, "What is the side of a square". Assign the input to the variable side.

Assign the variable area according to the formula:

$$
Area=s^2
$$

\
Assign the variable perimeter according to the formula.

$$
Perimeter=4s
$$

Print the following statement, "The area of the square is \_\_\_\_" where \_\_\_\_ is the area of the square.

\
Print the following statement, "The perimeter of the square is \_\_\_\_" where \_\_\_\_ is the perimeter of the square.

## Problem 7

print("Problem 7")

Write a program that asks the user how many feet and how many inches they are.  Compute and print the equivalent number in centimeters.

{% hint style="info" %}
One foot is 12 inches.  One inch is 2.54 centimeters.
{% endhint %}

## Problem 8

print("Problem 8")

Previously, you wrote a program that calculated the area of a square.  It is also possible to calculate the area of a triangle when all three sides are known.  Ask the user for s1, s2, s3.  Let&#x20;

$$
s=\frac{s1+s2+s3}{2}
$$

The area of a triangle can be calculated using the formula

$$
area=\sqrt{s (s-s1)(s-s2)(s-s3)}
$$

{% hint style="info" %}
To take the square root of a number, use the math library.
{% endhint %}

```python
import math
math.sqrt()
```

Print the area.

## Problem 9

print("Problem 9")

Ask the user for the number of days, hour, minutes and seconds.  Calculate the duration of time in seconds.

Print the total number of seconds in the duration.

## Problem 10

print("Problem 10")

![](/files/-M1OJ-JA1ZuwONbGMC8c)

You plan on getting a summer job at the end of the school year.

Write Python code that asks, “How much will you make per hour?” Assign the input to the variable rate. Then ask, “How many hours will you work per week?”. Assign the input to the variable hours.

Assign the variable money to the amount of money you’ll make.  What's the formula?

{% hint style="warning" %}
What's the formula?
{% endhint %}

Print the following statement, “If I work, I’ll make \_\_\_\_.” where \_\_\_\_ is the amount of money.

## Problem 11

print("Problem 11")

![Source: Republic Wireless](/files/-M1NcauE2B3L89UVjvWL)

Write Python code that asks, "How much data did you use this month in gigs". Assign the input to the variable gigs. Your phone company charges $15 for talk and text and $5 per gig.

Assign the variable total to the total amount of money you’ll owe this month.

{% hint style="warning" %}
What's the formula?
{% endhint %}

Print the following statement, "This month I will owe \_\_\_\_".

## Problem 12

print("Problem 12")

![](/files/-M1NbD3GTS15eXmSmGsc)

Write Python code that asks, "What is the temperature in Fahrenheit". Assign the input to the variable F.

Assign the variable celsius according to the formula:

$$
celcius=\frac{5}{9} (F-32)
$$

Print the following statement, "The temperature in Celsius is \_\_\_\_."

## Problem 13

print("Problem 13")

![Source: Nest](/files/-M1N_Nd5zP_PA7YOnO9N)

Write Python code that asks, "What is the temperature in Celsius". Assign the input to the variable C.

Assign the variable Fahrenheit according to the formula:

$$
fahrenheit = \frac{9}{5}C + 32
$$

Print the following statement, "The temperature in Fahrenheit is \_\_\_\_."

## Problem 14

print("Problem 14")

![Michal Klajban / CC BY-SA (https://creativecommons.org/licenses/by-sa/4.0)](/files/-M1Na9v4ch2wAylRjMby)

Write a program that asks for the length and width of a farmer's field in feet.  &#x20;

{% hint style="info" %}
There are 43,560 square feet in an acre.
{% endhint %}

Print the area of the field in acres.

## Problem 15

print("Problem 15")

![© Benoît Prieur / Wikimedia Commons](/files/-M1NauIla0AoLG8Eebwx)

Write a program that calculates how much the total bill at restaurant including tax and tip.  Ask the user the price of their appetizer, entree and dessert.  Calculate the tip as 18% of the meal amount.   New Jersey sales tax is currently 6.625%

To convert % to a decimal, divide by 100.  For example 18% = .18

Print the following:

* Subtotal (Appetizer, Entree and Dessert)
* Tax&#x20;
* Tip
* Grand Total (Subtotal, Tax, Tip)

## Problem 16

print("Problem 16")

![Source: Kean University](/files/-M1NQWqZGqZLuft8GS0T)

At Kean, the part-time (less than 12 credits) per credit rate is $389.00 plus $91.25 in mandatory fees.  Ask the user how many credits they are taking this semester (assume less than 12).  Print how much their tuition bill is.

## Problem 17

print("Problem 17")

Ask the user the total range of their car and the tank size in gallons.  MPG is calculated as total range divided by tank size. &#x20;

Print the MPG or miles per gallon of their car.

![Source: https://www.fueleconomy.gov](/files/-LqXda2UhTAiXMdaWQhT)

## Problem 18

print("Problem 18 - Simple Interest")

Write a program that calculates the accrued amount that includes principal and interest.  Ask the user for the Principal, rate and time.&#x20;

$$
A=P(1+rt)
$$

* A = Total Accrued Amount (principal + interest)
* Principal = Principal Amount
* r = Rate of Interest per year in decimal
* t = Time Period involved in years

Example annual percentage interest rates.  To convert % to decimal, divide by 100.

![Source: https://www.marcus.com/us/en/savings/high-yield-savings](/files/-LqXXcfC02RvIjLVhVBQ)

Print the total accrued amount.

## Problem 19

print("Problem 19 - Compound Interest")

Write a program that calculates compound interest on an investment or savings.

$$
A=P(1 + \frac{r}{n})^{nt}
$$

* A = Accrued Amount (principal + interest)&#x20;
* P = Principal Amount&#x20;
* r = Annual Nominal Interest Rate as a decimal&#x20;
* t = Time Involved in years
* n = number of compounding periods

Example annual percentage interest rates.  To convert % to decimal, divide by 100.  Assume quarterly compounding.

![Source: https://www.columbiabankonline.com/rates/cd](/files/-LqXZm3l8qewU6mgN8Q5)

Print the total accrued amount.

## Problem 20

print("Problem 20 - Credit Card Interest")

To calculate how much interest you’ll be charged on your credit card, you’ll need to know your average daily balance, the number of days in your billing cycle and your APR.

$$
interest =\frac{r}{365}(amount)(days)
$$

* r = Annual Nominal Interest Rate as a decimal
* amount = average amount you owe
* days = days in billing cycle

Example annual percentage interest rates.  To convert % to decimal, divide by 100.&#x20;

![Source: https://www.citi.com/credit-cards/credit-cards-comparison/citi.action?ID=credit-card-comparison](/files/-LqXbn-5lb0ZYwE5wreg)

Print the amount of interest on your monthly bill.


# Decisions

## Introduction

{% embed url="<https://docs.google.com/presentation/d/136WnUEaIXElZNGW8a_SJZwbqasvahbGurmYoPr8QLFc/edit?usp=sharing>" %}

Everyday, you’re faced with making decisions: what to eat, what to wear, etc. &#x20;

Conditional statements perform different computations or actions depending on whether a boolean condition evaluates to True or False. &#x20;

In real life, if it were raining, you might decide to take an umbrella.

![Decision Flowchart](/files/-Lcvln9SVyfphpyAZiUS)

### **Relational Operators and Boolean Expressions**

* A Relational Operator determines whether a specific relationship exists between two values.
* A Boolean expression tests if the conditional statement is True or False.

![](/files/-Ld0y-ZY9f9rcZWdNi4E)


# if

## Objective

After working through this lesson, you’ll be able to

* Write Python code using if statements.

{% embed url="<https://docs.google.com/presentation/d/1LVjHcUGZEipeqSxhIaeU_VREnpGd_uXT_RGQnqqr9nU/edit?usp=sharing>" %}

## Introductory Problem

Write Python code that asks:

* How many aunts do you have?
  * Assign the input to the variable aunts
* How many uncles do you have?
  * Assign the input to the variable uncles

{% code title="intro.py" %}

```python
aunts = int(input("How many aunts do you have? "))
uncles = int(input("How many uncles do you have? "))
print("I have",aunts,"aunts and",uncles,"uncles")
```

{% endcode %}

## if

The if conditional statement can be True or False.  When the if statement executes, the condition is tested and if it is true, the indented block of code is executed.  Otherwise, it is skipped.

![](/files/-Ld0pLRjMku32D6REBdp)

{% hint style="info" %}
Indentation is Python's method for grouping statements.
{% endhint %}

## Examples

### Example 1

Ask the user for a number.  Write if statements to determine.

* if the number is positive.
  * Print positive
* if the number negative
  * Print negative
* if the number is 0
  * Print is zero.

{% code title="" %}

```python
num = int(input("Give me a number: "))
if num > 0:
    print(num, "is positive")
if num < 0:
    print(num, "is negative")
if num == 0:
    print(num, "is zero")
```

{% endcode %}

### Example 2

Ask the user if it is hot today. &#x20;

* If the user enters "Yes", print "The summer is always hot!"
* If the user enters "No", print "It's time to move!".

{% code title="" %}

```python
hot = input("Is it hot today? ")
if hot == "Yes":
    print("It's always hot!")
if hot == "No":
    print("It's always cold!")
```

{% endcode %}

### Example 3

Ask the user how much money they have.

* If the user enters 99.99 or more, print "You're rich!"
* If the user enters less than 99.99, print "You're not rich!"

```python
money = float(input("How much money do you have? "))
if money >= 99.99:
    print("You're rich!")
if money < 99.99:
    print("You're not rich!")
```

### Example 4

Using the code from the Introductory Problem

* If the user has more aunts than uncles
  * Print "You have more aunts than uncles"
* If the user has more uncles than aunts
  * Print "You have more uncles than aunts"
* If the user has the same number of aunts and uncles
  * Print "You have the same number of aunts and uncles
* If the user does not have the same number of aunts and uncles
  * Print "You do not have the same number of aunts and uncles

```python
uncles = int(input("How many uncles do you have? "))
aunts = int(input("How many aunts do you have? "))
if aunts > uncles:
    print("You have more aunts than uncles")
if aunts < uncles:
    print("You have more uncles than aunts")
if aunts == uncles:
    print("You have the same number of aunts and uncles")
if aunts != uncles:
    print("You do not have the same number of aunts and uncles")
```


# if Examples

{% embed url="<https://repl.it/@MatthewCheng1/Python-if-Examples>" %}


# if Mistakes

## Mistake #1

What's the mistake in this code?  How can you fix it?

{% embed url="<https://repl.it/@MatthewCheng1/Python-if-Mistakes>" %}

## Mistake #2

What's the mistake in this code?  How can you fix it?

{% embed url="<https://repl.it/@MatthewCheng1/Python-if-Mistakes-2>" %}

## Mistake #3

What's the mistake in this code?  How can you fix it?

{% embed url="<https://repl.it/@MatthewCheng1/Python-if-Mistakes-3>" %}


# if Problems

## Problem 1

print(“Question 1”)

Ask your partner for a number. Write if statements to determine:

* Is the number positive&#x20;
  * If true, print positive&#x20;
* Is the number negative&#x20;
  * If true, print negative&#x20;
* Is the number 0&#x20;
  * If true, print the number is 0&#x20;
* Is the number 13&#x20;
  * If true, print the number is 13&#x20;
* Is the number -3&#x20;
  * If true, print the number is -3

## Problem 2

Write Python code that asks a user for what town Lakehurst Naval Base is located in. If the user enters “Toms River”, print correct.

What happens if you type “toms river” instead?&#x20;

## Problem 3

Write Python code that asks a user for the amount (price) of a pack of gum. What data type is the price?

If the amount is less than 1, print “I think this is a good price”. If the amount if greater than or equal to 1, print “I think this is expensive”

## Problem 4

Create a variable named roblox and ask the question, “do you want to play roblox”.

You want extra credit so you play Roblox with Mr Cheng’s daughter so you make the logical choice.

If the user inputs “yes” print “good choice”. If the user inputs “no”, print “Mr Cheng’s daughter will be very disappointed”

## Problem 5

She plays Work at a Pizza Place and earns 200 robux.

Create a variable called robux and assign it the value 200.

She plays for a few more hours and earns $50 for each hour she plays.

Ask the user how many hours she plays.

Add the initial amount she earned with the additional amount she made.

Print the total amount of Robux.

## Problem 6

Write Python code that prints the equation of a line in slope intercept form. Write Python code that asks:

* x1
* x2
* y1
* y2

If the slope is positive, print positive slope.  If the slope is negative, print negative slope.  If the slope is undefined, print vertical line.

## Problem 7

Ask the user, do you hear Laurel or Yanny?

If the user enters “Laurel”, print “doesn’t it sound like Yanny?”.&#x20;

If the user enters “Yanny”, print “doesn’t it sound like Laurel?”

## Problem 8

Ask the user to enter an abbreviation. &#x20;

* If the user enters "lol", print "laughing out loud".
* If the user enters "rofl", print "rolling on the floor laughing".
* If the user enters "lmk", print "let me know".
* If the user enters "smh", print "shaking my head".

## Problem 9

Ask the user, what is the net worth of Mark Zuckerberg. (do not enter commas when entering the number)

If the user enters 54500000000, print “yes and that’s a 54.5 billion”. If the user enters less than 54500000000, print “he has more money than that”. If the user enters more than 54500000000, print “that’s too little”.

## Problem 10

Ask the user, who bought Minecraft for 2.5 billion dollars?

If the user enters “Microsoft”, print “correct”. If the user does not enter “Microsoft”, print “incorrect”.


# if else

## Objective

After working through this lesson, you’ll be able to

* Write Python code using if else statements.

{% embed url="<https://docs.google.com/presentation/d/1NQhtvzPN7G2EXdMDqTsPdIf63u35Ugsek_ELtHz4HiQ/edit?usp=sharing>" %}

## Introductory Problem

Write Python code that asks:

* How many messages do you send to family per day&#x20;
* How many messages do you send to friends per day&#x20;

Write if statements to determine if you send more or less messages to family or friends per day.  Assume you do not send the same amount of messages to family or friends.

## Introduction

Sometimes you’ll want a catchall for other conditional cases. If the conditional statement evaluates to False, the else is executed.

![](/files/-Lr6wdzkB72-BE30p8U8)

## What's the difference between if and if/else?

* If you use two if statements, Python will evaluate both if statements to determine if they are True.
* With if/else, the else is executed only if the first condition is False.
* An if/else is faster than two if’s. If the first statement is False, Python will execute the else block.

{% hint style="warning" %}
Generally, it's good programming practice to have an else.  That way you know that the if part of the condition evaluated to False.
{% endhint %}

### Example 1

Rewrite the Introductory Problem using if/else.

```python
family = int(input("How many messages do you send to family? "))
friends = int(input("How many messages do you send to friends? "))
if family > friends:
    print("You send more messages to family")
else:
    print("You send more messages to friends")
```

### Example 2

Write Python code that asks a user how many minutes do you ride the bus? What data type is the input?

If the user enters 30 or less, print “not bad”. Else, print “that’s a long time”.

```python
mins = int(input("How many minutes do you ride the bus? "))
if mins <= 30:
    print("not bad")
else:
    print("that's a long time")
```

### Example 3

Mr Cheng’s daughter visits his classroom and wants you to play Roblox with her.

Write Python code that asks do want to play Roblox with her?

If the user enters “YES”, print “Mr Cheng will give you extra credit”. (The “YES” in all caps is intentional)

Else print “Now Mr Cheng will have to play Adopt Me with her”.

```python
play = input("Do you want to play Roblox with her? ")
if play == "YES":
    print("Mr Cheng gives you extra credit")
else:
    print("Now Mr Cheng will have to play Adopt Me with her")
```

### Example 4

Write Python code that asks a user how much money they have. What data type is the input?

If the user enters 9.90 or more, print “you have enough to buy a shirt”. (do not enter $)

Else, print “you do not have enough money”.

```python
money = float(input("How much money do you have? "))
if money >= 9.90:
    print("You have enough money to buy a shirt")
else:
    print("You do not have enough money")
```


# if else Examples

{% embed url="<https://repl.it/@MatthewCheng1/Python-if-else-Examples>" %}


# if else Problems

## Problem 1

Write Python code that asks a user for two numbers. Print the number that is the greatest. Print the number that is the least.

## Problem 2

Write Python code that asks a user for their password. If the user enters “1234567890”, print “that password is really easy to guess”.

Else print “good enough, I guess”.

## Problem 3

Write Python code that asks a user for their temperature. If the temperature is 100.4 or more, print “you have a fever”.

Else print “normal temperature”

## Problem 4

Write Python code that asks a user how many degrees is it in the Building. If the temperature is less than or equal to 70, print “feels chilly”.

Else print “comfy”.

## Problem 5

The USEPA developed the Air Quality Index (AQI) to report daily air quality to the public. The AQI tells you how clean your local air is, and what associated health effects might be a concern in your area. Think of the AQI as a yardstick that runs from 0 to 300. The higher the AQI value, the greater the level of air pollution and the greater the health concern.

Write Python code that asks a user what the AQI is today. If the user enters, 50 or less, print “Air Quality is Good”. Else print, “Air Quality is Moderate or Unhealthy”.

## Problem 6

Write Python code that asks a user how many pizza slices they want. The pizzeria charges $1.25 a slice if you order 10 slices or less and $1 a slice if you order more than 10 slices.

Print the total price depending on how many slices you order.

(Note: do not use the $ when assigning the price in your Python code)

## Problem 7

Write Python code that asks a user how many Youtube videos they watch per day. The average video is 7 minutes. If the user enters 5 or more, print “you watch a lot of videos”.

Else print “get more sleep”.

Print the total number of minutes the user watches videos.

## Problem 8

Write Python code that asks a user do you have a ShopRite card? Next, ask how many Apple or Pumpkin pies do they want to buy.

If the user enters “yes”, the user is charged 2.99 per pie. Else, the user is charged 4.99 per pie.

Print the total price.

## Problem 9

Write Python code asks the user for a number. If the number is divisible by 5, print the number if it is divisible by 5. Else print the number is not divisible by 5.

## Problem 10

Write Python code that asks a user for a number. Determine if the number is even or odd.

## Problem 11

Write Python code that asks a user for three numbers. Print the number that is the greatest. Print the number that is the least.


# if / if else Problems

{% hint style="danger" %}
Use if for Problems 1 - 10
{% endhint %}

## Problem 1

print(“Question 1”)

Ask the user for a number.

Write if statements to determine:

* Is the number 0&#x20;
  * If true, print the number is 0&#x20;
* Is the number 13&#x20;
  * If true, print the number is 13&#x20;
* Is the number -13&#x20;
  * If true, print the number is -13

## Problem 2

Write Python code that asks a user for what town Kean University is located in. If the user enters “Union”, print correct.

What happens if you type “union” instead? (This is for your own knowledge)

## Problem 3

Write Python code that asks a user for the amount (price) of a pack of gum. What data type is the price?

If the amount is less than 1, print "I think this is a good price". If the amount is greater than or equal to 1, print "I think this is expensive".

## Problem 4

Create a variable named bills and ask the question, “What president is on the banknote?”

Print the name of the President according to the chart:

| Amount |                    |
| ------ | ------------------ |
| 1      | George Washington  |
| 2      | Thomas Jefferson   |
| 5      | Abraham Lincoln    |
| 10     | Alexander Hamilton |
| 20     | Andrew Jackson     |
| 50     | Ulysses S. Grant   |
| 100    | Benjamin Franklin  |

## Problem 5

Many people say that one human year is equivalent to seven dog years.  Ask the user how old is the dog. &#x20;

If the user enters less than 2, print the dog is a baby.

If the user enters 2 or more, print the dog's age in human years.&#x20;

## Problem 6

Write Python code that asks:

* x1
* x2
* y1
* y2

Calculate the slope of the line.

$$
slope = \frac{y2 - y1}{x2 - x1}
$$

* If the slope is positive, print positive slope. &#x20;
* If the slope is negative, print negative slope. &#x20;
* If the slope is zero, print horizontal line.
* If the the denominator is 0, print vertical line.

## Problem 7

Ask the user, do you hear Laurel or Yanny?

If the user enters “Laurel”, print “doesn’t it sound like Yanny?”.&#x20;

If the user enters “Yanny”, print “doesn’t it sound like Laurel?”

## Problem 8

Ask the user to enter an abbreviation. &#x20;

* If the user enters "lol", print "laughing out loud".
* If the user enters "rofl", print "rolling on the floor laughing".
* If the user enters "lmk", print "let me know".
* If the user enters "smh", print "shaking my head".

## Problem 9

Ask the user, what is the net worth of Mark Zuckerberg. (do not enter commas when entering the number)

If the user enters 54500000000, print “yes and that’s a 54.5 billion”. If the user enters less than 54500000000, print “that's not much”. If the user enters more than 54500000000, print “I'll make more when I graduate”.

## Problem 10

Ask the user, who bought Minecraft for 2.5 billion dollars?

If the user enters “Microsoft”, print “correct”. If the user does not enter “Microsoft”, print “incorrect”.

{% hint style="danger" %}
Use if else for Problems 11 - 20&#x20;
{% endhint %}

## Problem 11

Write Python code that asks a user for two numbers. Print the number that is the greatest. Print the number that is the least.  Assume the numbers are not the same.

## Problem 12

Write Python code that asks a user for their password. If the user enters “1234567890”, print “that password is really easy to guess”.

Else print “good enough, I guess”.

## Problem 13

Write Python code that asks a user for their temperature. If the temperature is 100.4 or more, print “you have a fever”.

Else print “normal temperature”

## Problem 14

Write Python code that asks a user how many degrees is it in the Building. If the temperature is less than or equal to 70, print “feels chilly”.

Else print “comfy”.

## Problem 15

The USEPA developed the Air Quality Index (AQI) to report daily air quality to the public. The AQI tells you how clean your local air is, and what associated health effects might be a concern in your area. Think of the AQI as a yardstick that runs from 0 to 300. The higher the AQI value, the greater the level of air pollution and the greater the health concern.

Write Python code that asks a user what the AQI is today. If the user enters, 50 or less, print “Air Quality is Good”. Else print, “Air Quality is Moderate or Unhealthy”.

## Problem 16

Write Python code that asks a user how many pizza slices they want. The pizzeria charges $1.25 a slice if you order 10 slices or less and $1 a slice if you order more than 10 slices.

Print the total price depending on how many slices you order.

(Note: do not use the $ when assigning the price in your Python code)

## Problem 17

Write Python code that asks a user how many Youtube videos they watch per day. The average video is 7 minutes. If the user enters 5 or more, print “you watch a lot of videos”.

Else print “good job!”.

Print the total number of minutes the user watches videos.

## Problem 18

Write Python code that asks a user do you have a ShopRite card? Next, ask how many Apple or Pumpkin pies do they want to buy.

If the user enters “yes”, print "2.99 per pie". Else, print "4.99 per pie".

Print the total price.

## Problem 19 (Optional)

Write Python code asks the user for a number. If the number is divisible by 5, print the number if it is divisible by 5. Else print the number is not divisible by 5.

{% hint style="info" %}
The % (modulo) operator yields the remainder from the division of the first argument by the second.
{% endhint %}

## Problem 20 (Optional)

Write Python code that asks a user for a number. Print if the number is even or odd. &#x20;

{% hint style="info" %}
The % (modulo) operator yields the remainder from the division of the first argument by the second.
{% endhint %}


# if elif else

## Objective

After working through this lesson, you’ll be able to

* Write Python code using if else statements.

{% embed url="<https://docs.google.com/presentation/d/1rXKnSSkN3qWxhWasHOzN74RG_HX0vkzqE2J_Wd2aR9c/edit?usp=sharing>" %}

## Introductory Problem

Write Python code that asks for a number and assigns the input to the variable num.

Write if statements that print the messages:&#x20;

* num is positive.&#x20;
* num is negative.&#x20;
* num is 0.

## if elif else

Sometimes a problem will have multiple conditional cases.

![](/files/-Ld0oLTI0l1pgSkguO9I)

## Difference between if and if elif else

* Python will evaluate all three if statements to determine if they are true.&#x20;
* Once a condition in the if elif else statement is true, Python stop evaluating the other conditions.&#x20;
* Because of this, if elif else is faster than three if statements.

{% hint style="info" %}
The else is not required.
{% endhint %}

### Example 1

Write Python code that asks what type of gas do you want. The average car holds about 17 gallons of gas. Print the total price based on the type of gas and 15 gallons of gas.

| Type of Gas | Price per galloon |
| ----------- | ----------------- |
| regular     | $3.89             |
| plus        | $4.09             |
| premium     | $4.19             |
| diesel      | $4.59             |

* If the user enters “regular”, print the total price
* If the user enters “plus”, print the total price&#x20;
* If the user enters “premium”, print the total price&#x20;
* If the user enters “diesel”, print the total price&#x20;
* Else if the user enters something else, print invalid gas type

```python
gas = input("What type of gas do you want? ")
if gas == "regular":
    print("Regular Gas:",3.89*17)
elif gas == "plus":
    print("Plus Gas:",4.09*17)
elif gas == "premium":
    print("Premium Gas:",4.19*17)
elif gas == "diesel":
    print("Diesel Gas:",4.59*17)
else:
    print("Invalid Gas Type")
```


# if elif else Examples

{% embed url="<https://repl.it/@MatthewCheng1/Python-if-elif-else-Examples>" %}


# if elif else Problems

## Problem 1

Write Python code that asks the user for a number in the range of 1 through 7. Display the corresponding day of the week where&#x20;

* 1 for Monday
* 2 for Tuesday&#x20;
* 3 for Wednesday&#x20;
* 4 for Thursday
* 5 for Friday
* 6 for Saturday
* 7 for Sunday.&#x20;
* If the user enters a number outside the range of 1 - 7, print “error, out of range”.

## Problem 2

Write Python code that asks a user for the day of the week in English and translates it to Spanish. &#x20;

| English   | Spanish   |
| --------- | --------- |
| Sunday    | Domingo   |
| Monday    | Lunes     |
| Tuesday   | Martes    |
| Wednesday | Miercoles |
| Thursday  | Jueves    |
| Friday    | Viernes   |
| Saturday  | Sabado    |

If the user enters a word other than the ones above, print "Invalido".

## Problem 3

Write Python code that asks a user what year they were born in and then prints their Chinese Zodiac symbol.

| Year | Chinese Zodiac |
| ---- | -------------- |
| 1996 | Rat            |
| 1997 | Ox             |
| 1998 | Tiger          |
| 1999 | Rabbit         |
| 2000 | Dragon         |
| 2001 | Snake          |
| 2002 | Horse          |
| 2003 | Goat           |
| 2004 | Monkey         |
| 2005 | Rooster        |
| 2006 | Dog            |
| 2007 | Pig            |

## Problem 4

Write Python code that asks a user to enter a number from 1 through 10. The program should display the Roman numeral version of that number.&#x20;

| Number | Roman Numeral |
| ------ | ------------- |
| 1      | I             |
| 2      | II            |
| 3      | III           |
| 4      | IV            |
| 5      | V             |
| 6      | VI            |
| 7      | VII           |
| 8      | VIII          |
| 9      | IX            |
| 10     | X             |

If the number is outside of this range, print "we’ll work on that problem later".

## Problem 5

Write Python code that asks a user how much money they spend at the store sale.

* If they spend less than $75, they receive no discount.
* If the user spends $75 or more, they receive $15 off.&#x20;
* If the user spends $100 or more, they receive $25 off.&#x20;
* If they user spends $150 or more, they receive $50 off.&#x20;

Print the total of the order.

## Problem 6

Write Python code that asks a user how much money they spend at the store sale.&#x20;

![Source: The Children's Place](/files/-LrfWg46A2RsdmkWXmAT)

* If the user spends $60 or more, they receive 30% off.&#x20;
* If the user spends $50 or more, they receive 25% off.&#x20;
* Otherwise, the user will always save 20% off.

Print the total of the order.

## Problem 7

Write Python code that asks a user how much money they spend at the store sale.

![Source: Shopbop](/files/-LrfXjdJamM5cn0NeKsg)

The sale is 15% off $250+, 20% off $500+, 25% off $1000+.&#x20;

They will not receive a discount if they order less than $250.

Print the total of the order.

## Problem 8

Write Python code that asks a user to enter the magnitude of an earthquake on the Richter scale.  Print the descriptor based on the table.

![Source: U.S. Geological Survey](/files/-LrfK18nfJ75SUcKjuZS)

| Magnitude             | Descriptor |
| --------------------- | ---------- |
| Less than 2.0         | Micro      |
| 2.0 to less than 3.0  | Very Minor |
| 3.0 to less than 4.0  | Minor      |
| 4.0 to less than 5.0  | Light      |
| 5.0 to less than 6.0  | Moderate   |
| 6.0 to less than 7.0  | Strong     |
| 7.0 to less than 8.0  | Major      |
| 8.0 to less than 10.0 | Great      |
| 10.0 or more          | Meteoric   |

## Problem 9

Write Python code that asks the user for their letter grade.  Print the Grade Point based on the table.

| Letter | Grade Point |
| ------ | ----------- |
| A+     | 4.3         |
| A      | 4           |
| A-     | 3.7         |
| B+     | 3.3         |
| B      | 3.0         |
| B-     | 2.7         |
| C+     | 2.3         |
| C      | 2.0         |
| D+     | 1.3         |
| D      | 1.0         |
| F      | 0           |

If the letter is invalid, print an error message.

## Problem 10

Write Python code that asks the user for their total points.  Print the Letter Grade based on the table.

| Letter Grade | Out of 1000  |
| ------------ | ------------ |
| A            | 940 - 1000   |
| A-           | 900 - 939    |
| B+           | 870 – 899.9  |
| B            | 840 – 869.9  |
| B-           | 800 – 839.9  |
| C+           | 770 – 799.9  |
| C            | 700 – 769.9  |
| D            | 600 – 699.9  |
| F            | 599 or below |

## Problem 11

A cell phone plan charges $50 for up to 12 gigs of data, $60 for up to 30 gigs of data and $80 for up to 50 gigs of data. Write Python code that asks the user how much data they used last month and print the cost and add New Jersey sales tax (6.625%)

![Source: Boost Mobile](/files/-LrfHWAV9jKcZLo8OIU8)

## Problem 12

A shipping company charges a base rate based on the weight of a shipment.

![Source: Zipline Logistics](/files/-LrfZZS5Fbmw0kYbfiI_)

Write Python code that asks the user how much the weight of their shipment is.  Print the base price.

## Problem 13

A shipping company sells Bankers Boxes in Bundles of 12.  Write Python code that asks the user how boxes they want (assume it's a multiple of 12 and Model No. S-6522) and print the total cost.

![Source: Uline](/files/-Lrfaj_t06u7rPYFS4r1)


# nested if

## Objective

After working through this lesson, you’ll be able to

* Write Python coding using nested if statements.

{% embed url="<https://docs.google.com/presentation/d/1-W344Z0blrzMCeEDcuvSMwpAMLP7HoXMXR9mbHE_c48/edit?usp=sharing>" %}

## Introductory Problem

Ask the user if they are hungry. If the user replies yes, print “Goto the grocery store”. Else if the user replies no, print “Stay Home”. Else print “invalid choice”.

```python
hungry = input("Are you hungry? ")
if hungry == "Yes":
   print("Goto the Grocery Store")
elif hungry == "No":
   print("Stay Home")
else:
   print("Invalid choice")
```

## nested if

Sometimes you want to make a decision based on the result of a previous decision. One way to do this in Python is using nested conditionals, a second conditional executes only if the result of the first conditional is True.

![](/files/-Le4BJtber2zokuMudGn)

## Example 1

In the if “Yes” indented block, ask the user how much does chocolate cost. If the user enters a price less than or equal to a dollar, print “buy 3”. Else if the user enters a price more than a dollar, print “buy 1”.

{% code title="example2.py" %}

```python
hungry = input("Are you hungry? ")
if hungry == "Yes":
   print("Goto the Grocery Store")
   cost = float(input("How much does chocolate cost? "))
   if cost <= 1:
      print("Buy 3")
   else:
      print("Buy 1")
elif hungry == "No":
   print("Stay Home")
else:
   print("Invalid choice")
```

{% endcode %}

## Example 2

In the elif “no” indented block, ask the user, do you want to play Fortnite. If the user enters, yes, print “see you tomorrow morning”. Else if the user enters no, print “Go back to studying”.

{% code title="example3.py" %}

```python
hungry = input("Are you hungry? ")
if hungry == "Yes":
   print("Goto the Grocery Store")
   cost = float(input("How much does chocolate cost? "))
   if cost <= 1:
      print("Buy 3")
   else:
      print("Buy 1")
elif hungry == "No":
   print("Stay Home")
   fortnite = input("Do you want to play Fortnite? ")
   if fortnite == "yes":
      print("See you next week")
   elif fortnite == "no":
      print("Go back to studying")
else:
   print("Invalid choice")
```

{% endcode %}

## Example 3

Under print “Go back to studying”, ask the user what their favorite subject is. If the user inputs “History”, print “that’s my favorite subject too!” Else print “we don’t have things in common”.

{% code title="example4.py" %}

```python
hungry = input("Are you hungry? ")
if hungry == "Yes":
   print("Goto the Grocery Store")
   cost = float(input("How much does chocolate cost? "))
   if cost <= 1:
      print("Buy 3")
   else:
      print("Buy 1")
elif hungry == "No":
   print("Stay Home")
   fortnite = input("Do you want to play Fortnite? ")
   if fortnite == "yes":
      print("See you next week")
   elif fortnite == "no":
      print("Go back to studying")
      subject = input("What's your favorite subject? ")
      if subject == "History":
         print("That's my favorite subject too")
      else:
         print("We don't have things in common")
else:
   print("Invalid choice")
```

{% endcode %}


# nested if Examples

{% embed url="<https://repl.it/@MatthewCheng1/Python-nested-if-Examples>" %}


# nested if Problems

## Problem 1

Write Python code that asks the user if they are filing what status they are filing as. The choices are:

* Single
* Married Filing Jointly
* Head of Household

Ask the user what their income was. Subtract the appropriate deduction.  Note: Married Filing Separately has the same standard deduction as single.&#x20;

Print the amount of tax due.

![Source: Kiplinger](/files/-LrfcoGJDvV5ZLtA8ts6)

![Source: Kiplinger](/files/-LrfcDpsR26MJ4LzYhOT)

![Source: Kiplinger](/files/-LrfcLr7EjBlMxgYzsso)

## Problem 2

These rates apply to the Lincoln & Holland tunnels, the George Washington, Bayonne & Goethals bridges, and the Outerbridge Crossing.

Write Python code to determine the amount of money you pay at the toll depending on:

* Vehicle Type
* The number of axels
* EZPass Off Peak Hours
* EZPass Peak Hours
* EZPass
* Cash

Peak Hours

* Weekdays: 6-10 a.m., 4-8 p.m.
* Sat. & Sun.: 11 a.m.-9 p.m.

Off-Peak Hours

* All Other Times

Overnight Hours for Trucks

* Sundays-Thursdays, 10 p.m. until 6 a.m. the following morning

![Source: The Port Authority of New York and New Jersey](/files/-Lx_iOLVjJO5qCwxPdSd)


# Logical Operators

## Objective

After working through this lesson, you’ll be able to:

* Write Python code that uses logical operators to connect Boolean expressions.

## Introductory Problem

Write Python code to determine if you and your friend will get a fire emoji.

Ask the user, "Have you snapped with your friend for the past 3 days? ")

* If yes, print "you snapped with your friend"&#x20;
* If no, print "you have not snapped with your friend"

Ask the user, "Has your friend snapped with you for the past 3 days"

* If yes, print "your friend snapped with you"
* If no, print "your friend has not snapped with you"

If the answer to both questions is yes, then print, you started a Snapstreak!

{% code title="intro.py" %}

```python
sent = input("Have you snapped with your friend for the past 3 days? ")
if sent == "yes":
   print("you snapped with your friend")
elif sent == "no":
   print("you have not snapped with your friend")
received = input("Has your friend snapped with you for the past 3 days? ")
if received == "yes":
   print("your friend snapped with you")
elif received == "no":
   print("your friend has not snapped with you")
if sent == "yes":
   if received received == "yes":
      print("you started a Snapstreak!")
```

{% endcode %}

Logical operators allow you to connect Boolean expressions to create a compound expression.

| Operator | Meaning                                                                                                                                        |
| -------- | ---------------------------------------------------------------------------------------------------------------------------------------------- |
| and      | Connects two Boolean expressions into one compound expression. Both subexpressions must be true for the compound expression to be true.        |
| or       | Connects two Boolean expressions into one compound expression. One or both subexpressions must be true for the compound expression to be true. |
| not      | Reverses the truth of its operand                                                                                                              |

## Example 1

Rewrite the Introductory Problem using the logical and operator.  If both conditions are true, print, you started a Snapstreak! Else print, not so friendly yet.

{% code title="example1.py" %}

```python
sent = input("Have you snapped with your friend for the past 3 days? ")
if sent == "yes":
   print("you snapped with your friend")
elif sent == "no":
   print("you have not snapped with your friend")
received = input("Has your friend snapped with you for the past 3 days? ")
if received == "yes":
   print("your friend snapped with you")
elif received == "no":
   print("your friend has not snapped with you")
if sent == "yes" and received == "yes":
   print("you started a Snapstreak!")
else:
   print("not so friendly yet")
```

{% endcode %}

## Example 2

Snapchat decides to change its criteria for creating a Snapstreak. Now only one user has to send a message to the other for three days.  Change the code to satisify the new condition.

{% code title="example2.py" %}

```python
sent = input("Have you snapped with your friend for the past 3 days? ")
if sent == "yes":
   print("you snapped with your friend")
elif sent == "no":
   print("you have not snapped with your friend")
received = input("Has your friend snapped with you for the past 3 days? ")
if received == "yes":
   print("your friend snapped with you")
elif received == "no":
   print("your friend has not snapped with you")
if sent == "yes" or received == "yes":
   print("you started a Snapstreak!")
else:
   print("not so friendly yet")
```

{% endcode %}

## Example 3

Hundred emoji.  Ask the user:

* how many days in a row have you sent your friend a message?
* how many days in a row has your friend has sent you a message? &#x20;

If you and your friend have sent a message to each other for more than 100 days in a row, print you receive a hundred emoji.  Otherwise, print not there yet.

{% code title="example3.py" %}

```python
dayssent = int(input("How many days in a row have you sent your friend a message? "))
daysreceived = int(input("How many days in a row has your friend sent you a message? "))
if dayssent >= 100 and daysreceived >= 100:
   print("you receive a hundred emoji")
else:
   print("not there yet")
```

{% endcode %}


# Logical Operators Examples

{% embed url="<https://repl.it/@MatthewCheng1/Python-logical-operators-Examples>" %}


# Adventure Game Project

{% embed url="<https://docs.google.com/document/d/1wciXBKuC5UdEwxYigN1PN4hg3Fb1SR0LCK5znYWi2g4/edit?usp=sharing>" %}


# Loops

A loop is used to repeatedly execute a statement. &#x20;

A while loop executes statements repeatedly while a condition is true.

A for loop iterates through each value of a sequence.

In this section, you'll explore while and for loops.


# while loop - count up

## Introduction

{% embed url="<https://docs.google.com/presentation/d/1AjjEWWYHkzchI36kPRuC9pFnBSihVYZhATW42ZItpic/edit?usp=sharing>" %}

## Introductory Problem

Ask the user, "what is your favorite programming language".  If they enter Python, print, "Python is my favorite too!" 5 times. &#x20;

```python
fav = input("What is your favorite programming language? ")
if fav == "Python":
    print("Python is my favorite too!")
    print("Python is my favorite too!")
    print("Python is my favorite too!")
    print("Python is my favorite too!")
    print("Python is my favorite too!")
```

## while loop

A while loop executes an indented block of code, or instructions, repeatedly while a condition is true.  Previously, you learned about if statements that executed an indented block of code while a condition was true.  You can think of a while loop like an if condition but the indented block of code executes more than once.  Hence, a loop.

![](/files/-Ld0qJWMmEcT1pBE2wGX)

## Variable Roles

Recall that a stepper variable iterates, or loops, a specific number of time&#x73;**.**

![](/files/-Ld0qcvH-d0fjritjUCO)

{% hint style="info" %}
Programmers us&#x65;**`x`**&#x6F;&#x72;**`i`**&#x61;s a stepper variable.
{% endhint %}

## Common Mistakes

{% hint style="danger" %}
**Infinite Loops**

An infinite loop is a loop that runs forever.  It can only be stopped by killing the program. If there are output statements in the loop, these lines will flash by on the screen.  To kill the program, press Ctrl+C in the Terminal. Or click on CS50 IDE -> Restart your Workspace.
{% endhint %}

{% hint style="warning" %}
**Never Starts**

Because the first action of a while loop is to evaluate the Boolean expression, if that expression is False, the indented block of code will never be executed.
{% endhint %}

{% hint style="warning" %}
**Off by one**

Another common error you may encounter is being off by one.  Change the initial stepper value or the condition to correct this.
{% endhint %}

## while loop Examples

### Example 1

Again, ask the user, "what is your favorite programming language".   This time, print "Python is my favorite too!" 5 times using a while loop.

{% hint style="info" %}
Python programmers typically start counting at 0.  This will become more clear when we introduce lists. &#x20;
{% endhint %}

Steps:

* Initialize the stepper variable x to 0.
* Combine while with a condition that will execute 5 times.
* Print "Python is my favorite language!"&#x20;
* Increment the stepper variable.

{% tabs %}
{% tab title="example1.py" %}

```python
x = 0
while x < 5:
    print("Python is my favorite language!")
    x = x + 1
```

{% endtab %}
{% endtabs %}

### Example 2

Using a while loop, print numbers from 1 to 5. &#x20;

{% hint style="warning" %}
What value can you initialize the stepper variable to?
{% endhint %}

{% tabs %}
{% tab title="example2.py" %}

```python
x = 1
while x <= 5:
    print(x)
    x = x + 1
```

{% endtab %}
{% endtabs %}

or

{% tabs %}
{% tab title="example2.py" %}

```python
x = 1
while x < 6:
    print(x)
    x = x + 1
```

{% endtab %}
{% endtabs %}

{% hint style="danger" %}
The placement of x = x + 1 in the while loop matters. &#x20;

If you print x after x = x + 1, the value will be different than if you printed it before.
{% endhint %}

### Example 3

Using a while loop, print odd numbers from 1 to 99.&#x20;

{% hint style="warning" %}
What value can you initialize the stepper variable to? What can you increment the variable by?
{% endhint %}

{% tabs %}
{% tab title="example3.py" %}

```python
x = 1
while x < 100:
    print(x)
    x = x + 2
```

{% endtab %}
{% endtabs %}

or

{% tabs %}
{% tab title="example3.py" %}

```python
x = 1
while x <= 99:
    print(x)
    x = x + 2
```

{% endtab %}
{% endtabs %}

### Example 4

Print the sum of the first 10 numbers.  For example: 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 + 9 + 10

Create a variable called sum and initialize it to 0.

* What value can you initialize the stepper variable to?
* How can you use x to calculate the sum?

![](/files/-Ld0vX4W2sLAt64Wm09v)

{% tabs %}
{% tab title="example4.py" %}

```python
x = 1
sum = 0
while x <= 10:
    sum = sum + x
    x = x + 1
print("Sum:", sum)
```

{% endtab %}
{% endtabs %}

### Example 5

Ask the user for a number 3 times using a while loop.  Print the sum of the 3 numbers.

{% tabs %}
{% tab title="example5.py" %}

```python
x = 0
sum = 0
while x < 3:
    num = int(input("Number: "))
    sum = sum + num
    x = x + 1
print("Sum:", sum)
```

{% endtab %}
{% endtabs %}

## Conclusion

* In your own words, what is a while loop?&#x20;
* Give a simple example of something you do over and over again everyday.
* Explain the role of the stepper variable when the while loop counts up.
* How is using a while loop more efficient than the solution to the introductory problem?


# Examples

{% embed url="<https://repl.it/@MatthewCheng1/FlimsyRoyalblueTask>" %}

{% embed url="<https://repl.it/@MatthewCheng1/while-loop-example-2>" %}


# Problems

\# count up

## Problem 1

Using a while loop, print numbers from 1 to 10.

![](/files/-LvcJODc3Q1Ec3M17yPi)

## Problem 2

Ask the user what town they live in.  Using a while loop, print the name of their town 4 times.

![](/files/-LvcJg-6uxuALhRdIGa1)

## Problem 3

Using a while loop, print the powers of 2 from $$2^0$$to$$2^9$$&#x20;

![](/files/-LvcLQ3TXsFvjDSX1y3j)

## Problem 4

Using a while loop, print even numbers from 0 to 100.

## Problem 5

Using a while loop, print the sum of the first 100 numbers. (1 + 2 + 3 + ... + 100)

![](/files/-LvcJxBOztt3kikexiEk)

## Problem 6

You work for five days.  Using a while loop, ask the user how much money they make each day. Print how much money they have after five days.

![](/files/-LvcKUcwhuezD8vsi0gg)

## Problem 7

First, ask the user for their name.  Second, ask the user how many times they want to print their name.  Using a while loop, print the user's name the number of times they specified.

![](/files/-LvcKpcIllc-trHLC82m)

## Problem 8

Ask the user for a number.  Using a while loop, print the squares from 1 to this number.

For example, if the user enters 10, you'll program will print:

![](/files/-LvcJ7nhHjnuk1-bWMwZ)

## Problem 9

Ask the user for two numbers, a and b. Print the sum of all the numbers between a and b (inclusive).

## Problem 10

Ask the user for two numbers, a and b.  Using a while loop, print the odd numbers between a and b (inclusive).  How do you figure out if a number is even or odd?

## Problem 11

Ask the user for two numbers, a and b.  Using a while loop, print the sum of the odd numbers between a and b (inclusive).

## Problem 12

You put $10,000 into a bank account that earns 5% interest per year.  The interest formula is:

$$
A=P(1+r)^t
$$

$$A=amount$$&#x20;

$$P=Principal$$&#x20;

$$r=rate$$(in %)

$$t=time$$(in years)&#x20;

a) Print the balance per year until the time in years.

b) How many years will it take for the account balance to double the original investment?  Estimate this by inputting different amounts of time.

c) How many years does it take to triple?

![](/files/-LyWC_AcmytrCfxYdrmS)

### Challenge

c) The Swiss National Bank (SNB) is charging a 0.75 percent fee on large deposits at the central bank, a cornerstone of its monetary policy since January 2015 which is aimed at weakening Switzerland’s currency. &#x20;

If Swiss banks paid 970 million Swiss francs ($1 billion) in negative interest rate charges in the first six months of 2017, how much in deposits do Swiss banks have?

How many years will it take for the balance to be 0.<br>


# while loop - countdown

## Introduction

{% embed url="<https://docs.google.com/presentation/d/1vO70827sd3dxRknwshKedkLPBi2InJaTpkfqFXAuFJQ/edit?usp=sharing>" %}

## Introductory Problem

Ask the user what food they would like to eat everyday.  Using a while loop, print their favorite food 5 times.

{% tabs %}
{% tab title="intro.py" %}

```python
x = 0
food = input("What type of food do you like to eat? ")
while x < 5:
    print(food)
    x = x + 1
```

{% endtab %}
{% endtabs %}

## while loop <a href="#while-loop" id="while-loop"></a>

A while loop executes an indented block of code, or instructions, repeatedly while a condition is true. Previously, you learned about if statements that executed an indented block of code while a condition was true. You can think of a while loop like an if condition but the indented block of code executes more than once. Hence, a loop.

![](/files/-Ld0rUkV8JUo6Cey0hu5)

## Variable Roles

Recall that a stepper variable iterates, or loops, a specific number of time&#x73;**.**

![](/files/-Ld0rn3l0wcDMfrTA1_g)

{% hint style="info" %}
Programmers us&#x65;**`x`**&#x6F;&#x72;**`i`**&#x61;s a stepper variable.
{% endhint %}

## while loop Examples

### Example 1

Rewrite the Do Now to print the user’s favorite food 5 times by decrementing the variable rather than incrementing.

Steps:

* Initialize the stepper variable x to 5.
* Ask the user what they like to eat everyday.
* Using a while loop, create a condition that will execute 5 times.
* Print variable.
* Decrement the stepper variable.

{% tabs %}
{% tab title="example1.py" %}

```python
x = 3
food = input("Favorite Food: ")
while x > 0:
    print(food)
    x = x - 1
```

{% endtab %}
{% endtabs %}

### Example 2

Using a while loop, print even numbers from 10 to 1.

What value can we initialize the stepper variable to?

{% tabs %}
{% tab title="example2.py" %}

```python
x = 10
while x > 0:
    print(x)
    x = x - 2
```

{% endtab %}
{% endtabs %}

### **Example 3**

Using a while loop, ask the user for a number 3 times.   Where in the program should we ask the user for the number?  Inside the loop, or outside the loop?

Create a temporary variable named squared that squares the number.  Create another temporary variable named cubed that cubes the number.

Print the values of squared and cubed.

{% tabs %}
{% tab title="example3.py" %}

```python
x = 3
while x > 0:
    num = int(input("Number: "))
    squared = num * num
    print("Squared:",squared)
    cubed = num ** 3
    print("Cubed:",cubed)
    x = x - 1

```

{% endtab %}
{% endtabs %}

### **Example 4**

You eat a Pepperoni Pizza slice which is 400 calories and now want to burn off these calories for 10 minutes.  You burn 11 calories per minute running. Create a chart to represent how many minutes you have left to exercise and how many calories you have left to burn off.

Steps:

* Create a variable named calories and initialize it to 400.
* Before the while loop, add the following lines to create your chart. &#x20;
  * print("Mins\tCalories")
  * "\t" means tab.

{% tabs %}
{% tab title="example4.py" %}

```python
print("Mins\tCalories")
calories = 400
x = 10
while x >= 0:
    print(x,"\t",calories)
    calories = calories - 11
    x = x - 1
```

{% endtab %}
{% endtabs %}

## Conclusion

* In your own words, what is a while loop?  What is a real life example when you count down?
* Explain the role of the stepper variable when the while loop counts down.

## &#x20;<br>


# Examples

{% embed url="<https://repl.it/@MatthewCheng1/Python-while-loop-countdown-Examples>" %}


# Problems

\# countdown

## Problem 1

Using a while loop, print numbers from 50 to 0.

## Problem 2

Using a while loop, print odd numbers from 100 to 1.

## Problem 3

Using a while loop, print even numbers from 200 to 100.

## Problem 4

Use a while loop to ask the user for 5 numbers.  Print the average of those numbers.

## Problem 5 (optional)

Use a while loop to ask the user for 7 numbers.  Print the maximum number.

## Problem 6 (optional)

Use a while loop to ask the user for 6 numbers.  Print the minimum number.

## Problem 7

You play Roblox and have 5000 Robux.

You want to buy 3 items. In a while loop, ask the user how much each item costs.

Display the amount of Robux you have to start and the amount you have remaining.

## Problem 8

You eat a Chicken Burrito which is 1165 calories and now want to burn off these calories.

You burn 8 calories per minute walking around.

Use a while loop to display a chart to display how many calories you have left to burn off from 60 minutes to 0.

After your exercise, you get even more hungry and eat a Big Mac which is 540 calories. Add these calories to the amount you have left after walking.

You burn 10 calories per minute running.

Use another while loop to display a chart to display how many calories you have left to burn off from 30 minutes to 0.

## Problem 9

Use a while loop to display a table of Celsius temperatures from 20 to 10 and their Fahrenheit equivalents.

The formula for converting a temperature from Celsius to Fahrenheit is:

$$
F=\frac{9}{5}C + 32
$$

Before the while loop, add the following these lines to create your chart.

print("Celsius\tFahrenheit")&#x20;

print("----------------------")

## Problem 10

Use a while loop to display a table of Fahrenheit temperatures from 100 to 85 and their Celsius equivalents.

The formula for converting a temperature from Fahrenheit to Celsius is:

$$
C=\frac{5}{9}(F-32)
$$

Before the while loop, add the following these lines to create your chart.

print("Fahrenheit\tCelsius") print("----------------------")

##


# while loop - sentinel value

## Objective

After working through this lesson, you’ll be able to

* Write Python code using a while loop with a sentinel value.

## Introductory Problem

Using a while loop, ask the user for the minutes of their bus/car ride 3 times.  Print the sum of these numbers

{% code title="intro.py" %}

```python
x = 3
sum = 0
while x > 0:
    ride = int(input("How long? "))
    sum = sum + ride
print("Sum:",sum)
```

{% endcode %}

## while loop (sentinel)

Previously, you learned how to write loops that read and process a sequence of values. Today you will learn about while loops with sentinel values. A sentinel value denotes the end of a data set, but it is not part of the data. A loop that uses a sentinel value is called a sentinel-controlled loop.

|                           |                                                |
| ------------------------- | ---------------------------------------------- |
| 1 \<variable = input>     | Ask the user for a value                       |
| 2 while \<condition>:     | while loop executes while condition is True    |
| 3      \<do something>    | do something inside the while loop             |
| 4     \<variable = input> | Ask the user for a value again                 |
| 5 \<do something>         | (optional) do something outside the while loop |

{% hint style="info" %}
Use a variable named data to store the input value.
{% endhint %}

{% hint style="warning" %}
Don't use a float for equality checking in the condition because the values are approximated;.  &#x20;
{% endhint %}

## Examples

### Example 1

Using a while loop, ask the user how long their bus ride was this month until they enter 0.  Print the sum of these numbers.

Steps:

* Initialize a variable sum to 0.
* Ask "How long? (enter 0 to end): “
* Create a condition that will execute until the user enters 0.
* Sum the inputs
* Print the sum after the user enters &#x30;**.**

{% code title="example1.py" %}

```python
sum = 0
data = int(input("How long? (enter 0 to end) "))
while data != 0:
    sum = sum + data
    data = int(input("How long? (enter 0 to end) "))
print("Sum:",sum)
```

{% endcode %}

{% hint style="info" %}
The input value 0 is the sentinel value for these loops.
{% endhint %}

### Example 2

Using a while loop, ask the user for the length of their bus/car ride until the user enters 0.  Print the average of these number&#x73;**.**

Initialize a counter variable to 0.  Every time a number is entered, increment the variable.

{% code title="example2.py" %}

```python
sum = 0
x = 0
data = int(input("How long? (enter 0 to end) "))
while data != 0:
    sum = sum + data
    x = x + 1
    data = int(input("How long? (enter 0 to end) "))
average = sum / x
print("Average:",average)
```

{% endcode %}

### Example 3

Using a while loop, ask the user for the length of their bus/car ride until the user enters 0.  Print the maximum of these numbers.  Initialize max to the value of the first inpu&#x74;**.**

{% code title="example3.py" %}

```python
sum = 0
x = 0
data = int(input("How long? (enter 0 to end) "))
while data != 0:
    if x == 0:
        max = data
    else:
        if data > max:
            max = data
    x = x + 1
    data = int(input("How long? (enter 0 to end) "))
print("Max:",max)
```

{% endcode %}

### Example 4

Using a while loop, ask the user to enter numbers until they enter 0.  Print the total number of even number&#x73;**.**

{% code title="example4.py" %}

```python
evens = 0
data = int(input("Give me a number (enter 0 to end): "))
while data != 0
    if data % 2 == 0:
        evens = evens + 1
    data = int(input("Give me a number (enter 0 to end): "))
print("Evens:",evens)
```

{% endcode %}

## Conclusion

* What is an example of when you would use a while loop that does not have a fixed number of inputs?
* Explain the role of the sentinel variable.

## <br>

<br>


# Problems

## Problem 1

Using a while loop, ask the user how many minutes they’ve watched YouTube until the user enters 0. Print the value of the shortest YouTube video.

## Problem 2

Currently, the price of 1 USD is 80 Robux.

Using a while loop, ask the user to enter an amount in USD and print the result in Robux until the user enters 0

## Problem 3

Currently the price of 1 USD is .87 Euros.

Using a while loop, ask the user to enter an amount in USD and print the result in Euros until the user enters 0

## Problem 4

Currently the price of Bitcoin is 1 Bitcoin to 4000 USD.

Using a while loop, ask the user to enter an amount in Bitcoin and print the result in USD until the user enters 0

## Problem 5

Using a while loop, ask the user how many minutes they’ve watched YouTube each day this month until they enter 0.

Print the sum, average, maximum.

## Problem 6

Using a while loop, ask the user to enter numbers until they enter 0.

Print the total number of odd numbers.

## Problem 7

The notation n! Represents the factorial of a nonnegative number n. The factorial of n is the product of all the nonnegative integers 1 to n.

For example, 5! = 5 *4* 3 *2* 1 = 120.

Write Python code that lets the user enter a nonnegative integer and then uses a while loop to calculate the factorial of that number. Print the factorial.


# while loop - sentinel menu

## Objective

After working through this lesson, you’ll be able to

* Write Python code using a while loop with a sentinel value to create a menu.

## Introductory Problem

Using a while loop, ask the user how many snaps they’ve sent each day for the past 5 days.  Print the sum of these numbers.

{% code title="intro.py" %}

```python
sum = 0
x = 0
while x < 5:
    snaps = int(input("How many snaps did you send" ))
    sum = sum + snaps
print(sum)
```

{% endcode %}

## while loop - sentinel menu

Previously, you learned how to write loops that read and processed a sequence of values until it reached a sentinel value.  Recall that a sentinel value marks the end of a data set, but it is not part of the data set. A loop that uses a sentinel value in this way is called a sentinel-controlled loop.  Today, you'll use a while loop with a sentinel value to create a menu system.  This is also known as a game loop.

![](/files/-Ld100SxyORCtHFnAUt_)

{% hint style="info" %}
The variable role of done is a One-Way Flag.
{% endhint %}

![](/files/-Ld1eH2L7uzani0hbIM-)

## Examples

### Example 1

Initialize the variable done to False. &#x20;

Create a while loop with the condition not done. &#x20;

Print these lines:

print("Menu")

print("S - Start")

print("Q - Quit")

If the user enters S, print "Starting Game".

Else if the user enters Q, print "Exiting Game", and assign done to True.

{% code title="example1.py" %}

```python
done = False
while not done:
    print("Menu")
    print("S - Start")
    print("Q - Quit")
    choice = input(":: ")
    if choice == "S":
        print("Starting Game!")
    elif choice == "Q":
        print("Exiting Game!")
        done = True
    else:
        print("Invalid Choice")
```

{% endcode %}

### **Example 2**

Create a new menu item "B - Bus Ride"\
Ask the user how many minutes they ride the bu&#x73;**.**\
If the user enters less than 30, print "not long", else print "too long".

{% code title="example2.py" %}

```python
done = False
while not done:
    print("Menu")
    print("S - Start")
    print("B - Bus Ride")
    print("Q - Quit")
    choice = input(":: ")
    if choice == "S":
        print("Starting Game!")
    elif choice == "Q":
        print("Exiting Game!")
        done = True
    elif choice == "B":
        bus = int(input("How long is your bus ride? "))
        if bus < 30:
            print("not long")
        else:
            print("too long")
    else:
        print("Invalid Choice")
```

{% endcode %}

### Example 3

Create a new menu item "N - Number"

Ask the user for a number.  If they enter an even number, print even.  Else if they print an odd number, print odd.

{% code title="example3.py" %}

```python
done = False
while not done:
    print("Menu")
    print("S - Start")
    print("B - Bus Ride")
    print("N - Number")
    print("Q - Quit")
    choice = input(":: ")
    if choice == "S":
        print("Starting Game!")
    elif choice == "Q":
        print("Exiting Game!")
        done = True
    elif choice == "B":
        bus = int(input("How long is your bus ride? "))
        if bus < 30:
            print("not long")
        else:
            print("too long")
    elif choice == "N":
        num = int(input("Number: "))
        if num % 2 == 0:
            print("even")
        else:
            print("odd")
    else:
        print("Invalid Choice")
```

{% endcode %}

## Conclusion

* In your own words, what is a sentinel?  What are real life examples of sentinels?
* Explain the role of the One-Way Flag variable when using a while loop with a sentinel value to create a menu.

<br>

\ <br>


# Problems

## Problem 1

Create another menu item called

print("E - Convert Euros")

Currently 1 Euro equals 1.14 USD.

Print the equivalent amount of money in USD. Enter Euros and test several amounts.

## Problem 2

Create another menu item called

print("C - Convert Bitcoin")

Currently 1 Bitcoin equals 3407 USD.

Print the equivalent amount of money in USD. Enter Bitcoins and test several amounts.

## Problem 3

Create another menu item called

print("R - Robux")

Currently 1 USD equals 80 Robux.

Print the equivalent amount of money in Robux.

## Problem 4

Create another menu item called

print("SUM - Sum numbers")

Using a while loop, ask the user how many minutes they’ve studied this month until the user enters -1.

Print the sum.

## Problem 5

Create another menu item called

print("F - Factorial")

The notation n! Represents the factorial of a nonnegative number n. The factorial of n is the product of all the nonnegative integers 1 to n.

For example, 5! = 5 *4* 3 *2* 1 = 120.

Use a while loop to calculate the factorial of that number. Print the factorial.


# for loop - range (one argument)

## Objective

After working through this lesson, you’ll be able to

* Write Python code using the for loop using the range function with one argument.

{% embed url="<https://docs.google.com/presentation/d/1AveaRWfw_gFcn-pLx33Wiw9HOFfon5pJtx-cGOwJGPk/edit?usp=sharing>" %}

## Introductory Problem

You worked on while loop menu code previously.  Run the code below and make sure you understand how it works.&#x20;

{% code title="menu.py" %}

```python
done = False
while not done:
    print("Menu")
    print("S - Start")
    print("Q - Quit")
    choice = input("Choice: ")
    if choice == "S":
        print("Start")
    elif choice == "Q":
        print("Exiting Menu!")
        done = True
```

{% endcode %}

{% hint style="info" %}
done is a Boolean variable and True is the sentinel value.
{% endhint %}

Add code for the Intro menu item when the user selects I. &#x20;

Using a while loop, print your name 5 times. &#x20;

{% code title="intro.py" %}

```python
done = False
while not done:
    print("Menu")
    print("I - Intro")
    print("Q - Quit")
    choice = input("Choice: ")
    if choice == "I":
        print("Introductory Problem")
        x = 0
        name = input("What's your name? ")
        while x < 5:
            print(name)
    elif choice == "Q":
        print("Exiting Menu!")
        done = True
```

{% endcode %}

## for loop

Previously, you used while loops to iterate over a range of integer values.  Now you will use a for loop with the range function with one argument.

![](/files/-Ld1TFkOIEArjlGIZDcn)

{% hint style="info" %}
Programmers us&#x65;**`x`**&#x6F;&#x72;**`i`**&#x61;s a stepper variable.
{% endhint %}

![](/files/-Ltvzdp9BHZsEci0pMfn)

## Examples

### Example 1

Add a Menu Item E1 - Example 1

Using a for loop, print your name 5 times.

{% code title="example1.py" %}

```python
done = False
while not done:
    print("Menu")
    print("I - Intro")
    print("Q - Quit")
    choice = input("Choice: ")
    if choice == "I":
        print("Introductory Problem")
        x = 0
        name = input("What's your name? ")
        while x < 5:
            print(name)
    elif choice == "Q":
        print("Exiting Menu!")
        done = True
    elif choice == "E1":
        print("Example 1")
        name = input("What is your name? ")
        for i in range(5):
            print(name)
```

{% endcode %}

### Example 2

Add a Menu Item E2 - Example 2

Using a for loop, print numbers from 0 to 4.

{% code title="example2.py" %}

```python
done = False
while not done:
    print("Menu")
    print("S - Start")
    print("E2 - Example 2")
    print("Q - Quit")
    choice = input("Choice: ")
    if choice == "S":
        print("Starting Game!")
    elif choice == "Q":
        print("Exiting Menu!")
        done = True
    elif choice == "E2":
        print("Example 2")
        for i in range(5):
            print(i)
```

{% endcode %}

### Example 3

Add a Menu Item E3 - Example 3

Using a for loop, ask the user for 3 numbers.  Print the sum of numbers.

Initialize the variable sum to 0.

{% code title="example3.py" %}

```python
done = False
while not done:
    print("Menu")
    print("S - Start")
    print("E3 - Example 3")
    print("Q - Quit")
    choice = input("Choice: ")
    if choice == "S":
        print("Starting Game!")
    elif choice == "Q":
        print("Exiting Menu!")
        done = True
    elif choice == "E3":
        print("Example 3")
        sum = 0
        for i in range(3):
            num = int(input("Number: "))
            sum = sum + num
        print(sum)
```

{% endcode %}

### Example 4

Add a Menu Item E4 - Example 4

Using a for loop, create the table to show the numbers 0 to 10 and their squares.  Create a header:

print("Number\tSquared")

{% code title="example4.py" %}

```python
done = False
while not done:
    print("Menu")
    print("S - Start")
    print("E4 - Example 4")
    print("Q - Quit")
    choice = input("Choice: ")
    if choice == "S":
        print("Starting Game!")
    elif choice == "Q":
        print("Exiting Menu!")
        done = True
    elif choice == "E4":
        print("Number\tSquared")
        for i in range(11):
            print(i,"\t",i**2)
```

{% endcode %}

## Conclusion

* In your own words, what is a for loop?
* What are the differences between a while loop and a for loop.




---

[Next Page](/llms-full.txt/1)

