Skip to content
Snippets Groups Projects
Commit 03741d75 authored by Anna Meyer's avatar Anna Meyer
Browse files

add lab2

parent 70c24c7f
No related branches found
No related tags found
No related merge requests found
# lab2: Python Modes and Programming
In the lecture this week, we learned about three ways to run Python: interactive mode, script mode, and notebook "mode" (people outside of CS220 won't use that vocabulary for notebooks, hence the quotes). In this lab, you'll practice those three modes. You'll also get practice with operators, modular arithmetic, and Boolean logic.
To get started, please create a `lab2` directory inside your `cs220` directory (if you haven't already). Then, open a terminal and use `cd` to navigate to `lab2` (review the steps from [lab1](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/sum23/labs/lab1) in case you are unsure of how to use cd and/or get the pathname of the `lab2` directory).
## Learning Objectives
After completing this lab, you will be able to...
* Run Python code using interactive mode, script mode, and notebook "mode",
* Write Python expressions containing mathematical, comparison, and Boolean operators,
* Identify correct operator precedence order,
* Apply parentheses to override operator precedence in your expression when needed,
* Translate English statements into Python expressions,
* Write correct Boolean expressions with subparts separated by Boolean operators of `or` and `and`.
------------------------------
## Segment 1: Interactive Mode (Python Shell)
Let's start by looking at interactive mode, where code is executed one line at a time. Interactive mode is typically used for doing quick syntax checks. For a new Python programmer, the interactive mode is very helpful to try out simple examples.
### Task 1.1: Determine your Python version.
Run `python --version` in the terminal. You might see something like this:
```
Python 3.10.6
```
If it says something like 2.X.X, try running `python3 --version` instead. If you need to run the latter, please use `python3` whenever we say `python` in the directions this semester.
Many commands support some type of version argument. How do you think you could figure out the version of Jupyter?
**NOTE:** If your Python version is **NOT** 3.9.X or 3.10.X, then you have failed to install Python as per the specifications of this course, and this may cause some unexpected errors in future projects. Right now, you should continue with this lab with your current version of Python (as long as everything is working, currently). But it is recommended that you attend Office Hours and install the correct version of Python to prevent problems later in the summer.
### Task 1.2: Use `pwd` to verify that you are in the `lab2` directory.
The command `pwd` is a command line argument that stands for **P**rint **W**orking **D**irectory.
If the `pwd` command prints out a different directory path than your `lab2` directory path, use `cd` commands to move to the correct working directory. See [lab1](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/sum23/labs/lab1#task-15-navigate-to-the-lab1-directory) if you don’t recall how to use `cd` commands to navigate to a directory.
### Task 1.3: Start Python in **interactive** mode.
Type `python` and press Enter.
You should see something roughly like this (details will vary):
```
Python 3.9.13 (main, Aug 25 2022, 23:51:50) [MSC v.1916 64 bit (AMD64)] :: Anaconda, Inc. on win3
Type "help", "copyright", "credits" or "license" for more information.
>>>
```
Those `>>>` symbols are a Python prompt. This means you can type Python code, but your shell commands will not work until you exit Python again. Recall that we learned about shell commands in [lab1](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/sum23/labs/lab1#commonly-used-terminalpowershell-commands). Examples of shell commands include `cd`, `ls`, `mkdir`, etc.
### Task 1.4: Run Python in interactive mode.
Try typing this Python code:
```python
print("hi")
```
then press Enter. The message `hi` should be printed.
### Task 1.5: Try running a shell command in interactive mode.
Ensure you still see the `>>>` prompt, then type `pwd` again and press Enter. This should give you the following error because `pwd` is only valid in the shell (not Python):
```
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'pwd' is not defined
```
### Task 1.6: Exit interactive mode.
You can exit the interactive mode by typing in `exit()` and pressing Enter (which works on both Mac and Windows).
Alternatively, on Mac, you can do this with Control + D (hold down the Control key, then press the D key at the same time).
Alternatively, on Windows, you can use Control + Z and Enter (hold down the Control key, then press the Z key at the same time; release both, then press the Enter key).
### Task 1.7: Try running Python code in the shell.
Now that you've exited, try running both `pwd` and `print("hi")` again. This time, the former should work and the latter should fail (because we're in the shell, and the former is a shell command whereas the latter is Python code).
### Task 1.8: Re-enter interactive mode
Type `python` and press Enter.
### Task 1.9: Evaluate Python expressions
Type each of the below expressions, predict the output and then press Enter, to confirm that you are getting the expected output.
* `10/4`
* `10//4`
* `10%4`
* `not False`
* `not not True`
* `not not not True`
* `2*1000`
* `"2"*1000` (what's the difference between this one and the previous one?)
* `2**1000` (and what about this one?)
* `1/0` (should fail)
* `"ha"*100`
* `"ha\n"*100`
* `print("ha\n"*100)`
* `print("ha\n\n"*100)`
### Task 1.10: Exit interactive mode.
That's the end of the first segment! Take a moment to summarize for yourself what you learned. If you aren't sure about anything above, feel free to ask Anna or Adi for help. If you feel good, move on.
------------------------------
## Segment 2: Boolean Logic, Order of Operations, and Modular Arithmetic
In this section, you'll get more practice downloading and running existing notebooks.
### Task 2.1: Download `bool.ipynb`, `ops.ipynb`, and `mod.ipynb`
You can find them in the `lab2` folder of this GitLab Repo - which is where you are now. Download these files to your local `lab2` folder.
You need to follow the same procedure as you did to download files in `lab1`. In other words, do the following:
1. At the top of this page, Left-click on the file you want to download (for example, say `bool.ipynb`).
2. Right-click on the `Open raw` (<img src="images/raw_gitlab_button.png" width="30">) button.
3. Choose `Save Link As...` (or similar) as in this image below.
<img src="images/raw_gitlab.png" width="300">
4. Navigate to your `lab2` folder in the pop-up.
5. Ensure that you download the file with the proper extension:
* Windows users: ensure that `Save as type` is **not** `Text Document`, but "All Files".
* MAC users: replace the `.txt` extension with `.ipynb`.
6. Press Enter
(Note that on some Macs, `save link as` isn't working. If so, the Download button should work instead - just check that the file type is .ipynb.)
**Warning**: Verify that your file is saved as `bool.ipynb` and not `bool.txt` or `bool.ipynb.txt`. Reminder: we recommend you use the Chrome browser to avoid issues (other browsers might automatically change extensions of files to .txt when downloaded).
### Task 2.2: Open Jupyter in your `lab2` folder.
Go back to your open terminal. If you have closed it, review Task 1.2 to verify you are in the `lab2` directory. Now run `jupyter notebook`. You should see something like the following:
<img src="images/notebooks.png" width="1000" alt="The file tab opened in Jupyter listing the bool.ipynb, ops.ipynb, and mod.ipynb files">
You can now click on any of the three notebooks you've downloaded to view the contents. The exercises you should do with each notebook are described below.
**WARNING:** Your Terminal window should now look something like this:
<img src="images/jupyter_shell.PNG" width="700">
Even though we'll be working in the web browser now, **NEVER** close this terminal window where you typed `jupyter notebook` until you're done -- if you do, Jupyter will crash and you will lose any unsaved work.
If you need to use other Terminal/PowerShell commands, **open a new Terminal/PowerShell window**.
### Task 2.3: Complete the `bool.ipynb` notebook.
Open the notebook, complete the directions in each cell, and run the cell. If you are unsure of what to do, ask your TA/PM.
### Task 2.4: Complete the `ops.ipynb` notebook.
The `ops.ipynb` notebook is split into 2 sections. It is **very important** for you to
carefully go through the second section in particular. As a new programmer, you will learn some very important lessons in this section, which will help you avoid some nasty bugs in your code.
### Task 2.5: Complete the `mod.ipynb` notebook.
The `mod.ipynb` notebook will teach you about 'modular arithmetic' and is also split into 2 sections. In the first section, you will get acquainted with modular arithmetic, and in the second section, you will use modular arithmetic to solve a few simple word problems.
------------------------------
## Segment 3: Script mode (IDLE editor)
Script mode is the most commonly used mode for writing production Python code (that is code written at a company). In this course, we will only be writing code in notebook "mode". So this section will be the only place where you will briefly learn about script mode.
Now let's look at IDLE, which will help us write a Python script.
### Task 3.1: Open IDLE
Remember that you are currently running Jupyter on your previous Terminal window.
So, you cannot execute any more Shell commands from that window. Instead, you must
**open a new Terminal/PowerShell window**, and navigate back to the `lab2` directory
on the new Terminal. Do **not** close the old Terminal/PowerShell window unless you want
to close your Jupyter notebook.
We will now create a new file called `laugh.py` in IDLE (short for Integrated Development and Learning Environment, but it's a fancy text editor). From Shell mode (that is, not Python interactive mode), type `idle laugh.py`. This would normally open up a file named `laugh.py` in IDLE if it already existed, but since it doesn't, it will create a new empty file named `laugh.py`.
If you are using macOS, try the command `idle3 laugh.py`
**Warning**: If you are using macOS and the `idle3 laugh.py` command did not work, then directly open IDLE from `Finder` and save the new file as `laugh.py`.
### Task 3.2: Write some code in IDLE.
Paste the following into the editor:
```python
print("ha " * 10 + "!")
```
### Task 3.3: Run code in IDLE.
From the run menu, click `Run Module` (saving your file if necessary); or, you can accomplish the same by pressing `F5` on your keyboard.
You should see a new window pop up. In this window, you should see:
```
ha ha ha ha ha ha ha ha ha ha !
```
along with `>>>` underneath. What do you think those arrows signify?
### Task 3.4: Use Python interactive mode in IDLE.
Type or paste `print("hello")` in the pop-up `>>>` prompt and press Enter.
Now close the pop-up.
### Task 3.5: Investigate how script mode handles code that doesn't use print().
Remove the print in your file, so it looks like this:
```python
"ha " * 10 + "!"
```
Run your code again (e.g., with `F5`). Notice how it doesn't show any of your output? In interactive mode, prints usually aren't necessary, but they are in script mode. Add back the print, save, then close any IDLE windows that are open.
### Task 3.6: Run the Python program you wrote from the shell (back to your terminal).
```
python laugh.py
```
Did it work? If you are on a MAC, try `python3 laugh.py` if `python laugh.py` fails.
### Task 3.7: `circle.py` program
Let's try to create a second program:
1. Run `idle circle.py` (`idle3 circle.py` on macOS)
2. Paste `print((8/2)**2 * 3.14)`
3. Run the program (either in idle with `F5`, or by exiting idle and running `python circle.py` in the shell)
The program computes the area of a circle. *Can you figure out what the diameter of that circle is by reading the code?*
That's the end of this segment! Take a moment to summarize for yourself what you learned.
---
## Segment 4: Otter tests check for project submission
This segment is informational only and has no tasks. Starting with project P2, your work is not complete when you submit the project on Gradescope. It is your responsibility to make sure that your project clears auto-grader tests on the Gradescope test system. Otter test results should be available in a few minutes after your submission. You should be able to see both PASS / FAIL results for the 20 test cases and your total score, which is accessible via Gradescope Dashboard.
You **must** review the project's rubric and make sure that you have followed the directions provided in the project to solve the questions. The rubric is meant to reinforce your understanding of the project's directions. TAs and graders will be following the rubric to make deductions on your project submission during manual grading. Rubrics will become progressively stricter as we make progress during this semester.
To get full credit for this lab, you must acknowledge to Anna that you understand Segment 4's instructions.
If you finished early, you can get started on [P2](https://git.doit.wisc.edu/cdis/cs/courses/cs220/cs220-lecture-material/-/tree/main/sum23/projects/p2)! Good luck!
%% Cell type:markdown id: tags:
# Boolean Logic
Let's get practice with boolean data types and boolean operators.
Each input cell will contain a statement in English and the corresponding Python variables to represent the sentence. The variables will either have pre-assigned Boolean values (`True` / `False`) or you will have to fill out the values, as per the provided direction.
Recall that in Python, we use the following syntax for assigning values to variables
`some_variable = some_value`
The `=` is the assignment operator.
%% Cell type:code id: tags:
``` python
# To pass a class, you must
# a) Show up to lectures
# AND
# b) Do the assignments
showed_to_lectures = True
did_assignments = True
passed = showed_to_lectures and did_assignments
# what do you think the value of passed will be?
# your answer here:
passed
```
%% Cell type:code id: tags:
``` python
showed_to_lectures = False
did_assignments = False
passed = showed_to_lectures and did_assignments
# what do you think the value of passed will be this time?
# your answer here:
passed
```
%% Cell type:code id: tags:
``` python
showed_to_lectures = True
did_assignments = False
passed = showed_to_lectures and did_assignments
# what do you think the value of passed will be this time?
# your answer here:
passed
```
%% Cell type:code id: tags:
``` python
# To take this class, you must
# a) take all the prerequisites
# OR
# b) have an exemption from the professor
took_prereqs = True
has_exemption = True
can_take = took_prereqs or has_exemption
# what do you think the value of can_take will be this time?
# your answer here:
can_take
```
%% Cell type:code id: tags:
``` python
took_prereqs = False
has_exemption = False
can_take = took_prereqs or has_exemption
# what do you think the value of can_take will be this time?
# your answer here:
can_take
```
%% Cell type:code id: tags:
``` python
took_prereqs = True
has_exemption = False
can_take = took_prereqs or has_exemption
# what do you think the value of can_take will be this time?
# your answer here:
can_take
```
%% Cell type:code id: tags:
``` python
# A car passes its smog test if
# a) Its tailpipe emissions are clean
# AND
# b) It does NOT have a Check Engine Light
# What values of these boolean variables will result in a pass?
# replace the ... with your code
clean_tailpipe = ...
has_CEL = ...
# DO NOT EDIT THIS LINE
passes_smog = clean_tailpipe and not has_CEL
# TODO: Display passes_smog
```
%% Cell type:code id: tags:
``` python
# You should take your jacket off when going through airport security if
# a) The jacket contains metal
# OR
# b) You do not have a Known Traveler account
# What values of these variables will
# force this traveler to take off their jacket?
# replace the ... with your code
jacket_contains_metal = ...
is_known_traveler = ...
# DO NOT EDIT THIS LINE
should_remove_jacket = jacket_contains_metal or not is_known_traveler
# TODO: Display should_remove_jacket
```
%% Cell type:code id: tags:
``` python
# replace the ... with <, >, or == to make the whole statement True
((5 ... -10) or (20 ... -20)) and (34 ... 34)
```
%% Cell type:code id: tags:
``` python
# replace the ... with <, >, or == to make the whole statement True
((1 ... -10) and (30 ... -35)) and not ((356 ... 366) or (-24 ... 37))
```
%% Cell type:markdown id: tags:
Check in with Anna or Adi and show the last expression. If you have any questions, please ask Anna or Adi.
%% Cell type:markdown id: tags:
# Images
Images from lab-p2 are stored here.
sum23/labs/lab2/images/autoGrader_results.png

210 KiB

sum23/labs/lab2/images/jupyter_shell.PNG

62.4 KiB

sum23/labs/lab2/images/notebooks.png

94.2 KiB

sum23/labs/lab2/images/raw_gitlab.png

112 KiB

sum23/labs/lab2/images/raw_gitlab_button.png

4.52 KiB

%% Cell type:markdown id: tags:
# Modular Arithmetic
What time does an analog clock show one hour after twelve o'clock? Not 13 o'clock (that doesn't exist) -- instead, it wraps back around to 1 o'clock. This is a weird kind of arithmetic, where adding doesn't always make a number larger.
This alternative arithmetic is called **modular arithmetic**, and we can use the modulo operator (`%`) in Python to perform modular addition. However, there's a twist concerning the clock: in CS, we count from 0, so if we were to have a **CS clock**, it would go from 0 o'clock to 11 o'clock (instead of from 1 o'clock to 12 o'clock).
%% Cell type:markdown id: tags:
## 1. Exploring modular arithmetic
You'll see many cells of the form `X%12`. This computation is answering the question: if we start at 0 o'clock and wait X hours, what time is it? The `%12` part means time wraps around at 12 o'clock, meaning that there is no 12 o'clock, just 0 o'clock again (remember we have a CS clock that goes from 0 to 11 o'clock).
Run the cells in this section to get a sense of how this CS clock works.
%% Cell type:code id: tags:
``` python
0 % 12
```
%% Cell type:code id: tags:
``` python
1 % 12
```
%% Cell type:code id: tags:
``` python
2 % 12
```
%% Cell type:code id: tags:
``` python
3 % 12
```
%% Cell type:code id: tags:
``` python
4 % 12
```
%% Cell type:code id: tags:
``` python
5 % 12
```
%% Cell type:code id: tags:
``` python
6 % 12
```
%% Cell type:code id: tags:
``` python
7 % 12
```
%% Cell type:code id: tags:
``` python
8 % 12
```
%% Cell type:code id: tags:
``` python
9 % 12
```
%% Cell type:code id: tags:
``` python
10 % 12
```
%% Cell type:code id: tags:
``` python
11 % 12
```
%% Cell type:code id: tags:
``` python
# wraps back to 0!
12 % 12
```
%% Cell type:code id: tags:
``` python
13 % 12
```
%% Cell type:code id: tags:
``` python
14 % 12
```
%% Cell type:code id: tags:
``` python
15 % 12
```
%% Cell type:code id: tags:
``` python
16 % 12
```
%% Cell type:code id: tags:
``` python
17 % 12
```
%% Cell type:code id: tags:
``` python
18 % 12
```
%% Cell type:code id: tags:
``` python
19 % 12
```
%% Cell type:code id: tags:
``` python
20 % 12
```
%% Cell type:code id: tags:
``` python
21 % 12
```
%% Cell type:code id: tags:
``` python
22 % 12
```
%% Cell type:code id: tags:
``` python
23 % 12
```
%% Cell type:code id: tags:
``` python
# wraps back to 0!
24 % 12
```
%% Cell type:code id: tags:
``` python
25 % 12
```
%% Cell type:code id: tags:
``` python
26 % 12
```
%% Cell type:markdown id: tags:
## 2. Solve math problems by using the modulo operator
For each question below, write a Python expression using `%` to answer the question. The first two questions here have already been answered. Answer the remaining questions in this section by yourself.
%% Cell type:code id: tags:
``` python
# What time will it be 6 hours after 9 o'clock?
(9+6) % 12
```
%% Output
3
%% Cell type:code id: tags:
``` python
# What time was 2 hours before 1 o'clock?
(1-2) % 12
```
%% Output
11
%% Cell type:code id: tags:
``` python
# What time was 4 hours before 2 o'clock?
```
%% Cell type:code id: tags:
``` python
# What time will it be 12 hours after 6 o'clock?
```
%% Cell type:code id: tags:
``` python
# What time will it be 13 hours after 6 o'clock?
```
%% Cell type:code id: tags:
``` python
# What time will it be 24 hours after 6 o'clock?
```
%% Cell type:code id: tags:
``` python
# What time will it be 25 hours after 6 o'clock?
```
%% Cell type:markdown id: tags:
Check in with Anna or Adi and show the last expression. If you have any questions, please ask Anna or Adi.
%% Cell type:markdown id: tags:
%% Cell type:markdown id: tags:
# Order of Simplification / Precedence
Python has operator-precedence rules to determine which operator to execute first if an expression contains multiple operators.
Ordered from highest to lowest precedence:
<div>
<img src="attachment:precedence.png" width="600"/>
</div>
Of course, the Python programmer (you!) can add parentheses to change the order in which the operators are executed, thereby changing the result.
%% Cell type:markdown id: tags:
### Rules for order of Simplification / Precedence:
1. First work within parentheses
2. Do higher precedence first
3. Break ties left to right (exception: exponent ** operator)
%% Cell type:markdown id: tags:
## 1. Using parentheses, fix each cell to get the correct result.
For each of the following problems, you are only allowed to add parentheses, and you need to get the expression to evaluate to the required value.
For example, for the first problem below, `3 ** 4 - 1` evaluates to `80`, so you should change it to `3 ** (4 - 1)`, thereby getting `27`.
%% Cell type:code id: tags:
``` python
# Add parentheses to get 27
3 ** 4 - 1
```
%% Output
80
%% Cell type:code id: tags:
``` python
# Add parentheses to get 0
-2 - 2
```
%% Output
-4
%% Cell type:code id: tags:
``` python
# Add parentheses to get 0.5
1 / 1 + 1
```
%% Output
2.0
%% Cell type:code id: tags:
``` python
# Add parentheses to get 1
100 + 5 % 2
```
%% Output
101
%% Cell type:code id: tags:
``` python
# Add parentheses to get False
not True or True
```
%% Output
True
%% Cell type:code id: tags:
``` python
# Add parentheses to get True
False == True and False
```
%% Output
False
%% Cell type:markdown id: tags:
## 2. Correct way to write boolean expressions.
You should always write boolean expressions in an expanded manner (examples below).
This is a **very important** lesson to learn early as a new programmer.
Make sure you go through this section very carefully, and flag your TA/PM if you have any difficulty with this section.
%% Cell type:code id: tags:
``` python
# Is 3 + 4 equal to 6 or 7? In English, you would say that this statement is True.
# Now let's learn the improper way of translating this into Python expression
# Incorrect way
3 + 4 == 6 or 7
# In the above expression, what is the operator precedence? Please go back and refer to the precedence table
# Now, run this cell and see the strange answer you are getting
```
%% Cell type:code id: tags:
``` python
# Why did we get 7 for the above cell's output?
# Operator with the highest precedence: +
# So, you evaluate 3 + 4 first and now you get:
7 == 6 or 7
# Operator with te next highest precedence: ==
# So, you now evaluate 7 == 6.
# 7 == 6 gives you False
# Operator left behind: or
False or 7
# This here is bad! You should never compare a non-boolean value with a boolean operator!
# So now you know why you got 7 when you executed `3+4 == 6 or 7`
```
%% Cell type:code id: tags:
``` python
# What will be the output?
print(False or True)
print(False or False)
print(False or "hi") # bad comparison
print(False or 7) # bad comparison
```
%% Cell type:markdown id: tags:
### Important lesson: never use boolean operator on a non-boolean value
So, always write boolean expressions with proper expansion
%% Cell type:code id: tags:
``` python
# Is 3 + 4 equal to 6 or 7? In English, you would say that this statement is True.
# Now let's learn the proper way of translating this into Python expression
# Correct way
3 + 4 == 6 or 3 + 4 == 7
```
%% Cell type:code id: tags:
``` python
# Translate this into Python expression
# Was today's lecture instructed by Mike or Gurmail? (Mike and Gurmail taught the Spring 2023 version of the course)
instructor = "Mike"
... == ... or ...
# Try changing the instructor variable assignment to "Gurmail" or "Andy"
```
%% Cell type:markdown id: tags:
**LESSON**: It's tempting to chain a bunch of `or` operators together when trying to compare one value against a bunch of values. But this:
```
x == a or b or c or d
```
doesn't work. You need to individually compare each value:
```
x == a or x == b or x == c or x == d
```
The same applies for the `and` operator as well.
%% Cell type:markdown id: tags:
Check in with your TA and show the last expression. If you have any questions, please ask the TA / PM.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment