Skip to content
Snippets Groups Projects

Compare revisions

Changes are shown as if the source revision was being merged into the target revision. Learn more about comparing revisions.

Source

Select target project
No results found

Target

Select target project
  • HLI877/cs220-lecture-material
  • DANDAPANTULA/cs220-lecture-material
  • cdis/cs/courses/cs220/cs220-lecture-material
  • GIMOTEA/cs220-lecture-material
  • TWMILLER4/cs220-lecture-material
  • GU227/cs220-lecture-material
  • ABADAL/cs220-lecture-material
  • CMILTON3/cs220-lecture-material
  • BDONG39/cs220-lecture-material
  • JSANDOVAL6/cs220-lecture-material
  • JSABHARWAL2/cs220-lecture-material
  • GFREDERICKS/cs220-lecture-material
  • LMSUN/cs220-lecture-material
  • RBHALE/cs220-lecture-material
  • MILNARIK/cs220-lecture-material
  • SUTTI/cs220-lecture-material
  • NMISHRA4/cs220-lecture-material
  • HXIA36/cs220-lecture-material
  • DEPPELER/cs220-lecture-material
  • KIM2245/cs220-lecture-material
  • SKLEPFER/cs220-lecture-material
  • BANDIERA/cs220-lecture-material
  • JKILPS/cs220-lecture-material
  • SOERGEL/cs220-lecture-material
  • DBAUTISTA2/cs220-lecture-material
  • VLEFTWICH/cs220-lecture-material
  • MOU5/cs220-lecture-material
  • ALJACOBSON3/cs220-lecture-material
  • RCHOUDHARY5/cs220-lecture-material
  • MGERSCH/cs220-lecture-material
  • EKANDERSON8/cs220-lecture-material
  • ZHANG2752/cs220-lecture-material
  • VSANTAMARIA/cs220-lecture-material
  • VILBRANDT/cs220-lecture-material
  • ELADD2/cs220-lecture-material
  • YLIU2328/cs220-lecture-material
  • LMEASNER/cs220-lecture-material
  • ATANG28/cs220-lecture-material
  • AKSCHELLIN/cs220-lecture-material
  • OMBUSH/cs220-lecture-material
  • MJDAVID/cs220-lecture-material
  • AKHATRY/cs220-lecture-material
  • CZHUANG6/cs220-lecture-material
  • JPDEYOUNG/cs220-lecture-material
  • SDREES/cs220-lecture-material
  • CLCAMPBELL3/cs220-lecture-material
  • CJCAMPOS/cs220-lecture-material
  • AMARAN/cs220-lecture-material
  • rmflynn2/cs220-lecture-material
  • zhang2855/cs220-lecture-material
  • imanzoor/cs220-lecture-material
  • TOUSEEF/cs220-lecture-material
  • qchen445/cs220-lecture-material
  • nareed2/cs220-lecture-material
  • younkman/cs220-lecture-material
  • kli382/cs220-lecture-material
  • bsaulnier/cs220-lecture-material
  • isatrom/cs220-lecture-material
  • kgoodrum/cs220-lecture-material
  • mransom2/cs220-lecture-material
  • ahstevens/cs220-lecture-material
  • JRADUECHEL/cs220-lecture-material
  • mpcyr/cs220-lecture-material
  • wmeyrose/cs220-lecture-material
  • mmaltman/cs220-lecture-material
  • lsonntag/cs220-lecture-material
  • ghgallant/cs220-lecture-material
  • agkaiser2/cs220-lecture-material
  • rlgerhardt/cs220-lecture-material
  • chen2552/cs220-lecture-material
  • mickiewicz/cs220-lecture-material
  • cbarnish/cs220-lecture-material
  • alampson/cs220-lecture-material
  • mjwendt4/cs220-lecture-material
  • somsakhein/cs220-lecture-material
  • heppenibanez/cs220-lecture-material
  • szhang926/cs220-lecture-material
  • wewatson/cs220-lecture-material
  • jho34/cs220-lecture-material
  • lmedin/cs220-lecture-material
  • hjiang373/cs220-lecture-material
  • hfry2/cs220-lecture-material
  • ajroberts7/cs220-lecture-material
  • mcerhardt/cs220-lecture-material
  • njtomaszewsk/cs220-lecture-material
  • rwang728/cs220-lecture-material
  • jhansonflore/cs220-lecture-material
  • msajja/cs220-lecture-material
  • bjornson2/cs220-lecture-material
  • ccmclaren/cs220-lecture-material
  • armstrongbag/cs220-lecture-material
  • eloe2/cs220-lecture-material
92 results
Show changes
Showing
with 12022 additions and 0 deletions
%% Cell type:code id: tags:
``` python
# Warmup 1
# Get the user's name using the input function.
# Then, print out 'Hello, NAME'
```
%% Cell type:code id: tags:
``` python
# Warmup 2
# Ask the user for a number, then tell them the sqrt of it.
# HINT: sqrt needs to be imported from math!
```
%% Cell type:code id: tags:
``` python
# Warmup 3
# Fix the code below. What type of error(s) did you fix?
x = input("Tell me a number! ")
is-even = (x % 2 == 0)
print("That number is even: " + is-even)
```
%% Cell type:markdown id: tags:
# Creating Functions
## Readings
- Parts of Chapter 3 of Think Python,
- Chapter 5.5 to 5.8 of Python for Everybody
- Creating Fruitful Functions
%% Cell type:markdown id: tags:
## Learning Objectives
- Explain the syntax of a function header:
- def, ( ), :, tabbing, return
- Write a function with:
- correct header and indentation
- a return value (fruitful function) or without (void function)
- parameters that have default values
- Write a function knowing the difference in outcomes of print and return statements
- Explain how positional, keyword, and default arguments are copied into parameters
- Make function calls using positional, keyword, and default arguments and determine the result.
- Trace function invocations to determine control flow
%% Cell type:markdown id: tags:
## More Warmup
Let's try some more problems not covered in Friday's lecture!
%% Cell type:code id: tags:
``` python
# On the line below, import the time module
start_time = time.time()
x = 2**1000000000 # a very long computation
end_time = time.time()
difference = end_time - start_time
# Seperate each time with a '\n'
print(start_time, end_time, difference)
```
%% Cell type:code id: tags:
``` python
help(time.time)
```
%% Cell type:code id: tags:
``` python
# From the math module, import only the log10 function
# Then, print the log base 10 of 1000
```
%% Cell type:code id: tags:
``` python
# This one is done for you as an example!
# Note: importing with 'wildcard' * is generally considered bad practice
from math import * # allows us to use all functions without writing math
print(pi)
```
%% Cell type:code id: tags:
``` python
# Try importing and printing 'pi' the proper way!
```
%% Cell type:markdown id: tags:
## Functions
%% Cell type:code id: tags:
``` python
# Write a function that cubes any number
# The first line is called the function header
# Notice that all the other lines are indented the same amount (4 spaces)
# The best practice in Jupyter Notebook is to press tab
# If you don't run the cell, Jupyter Notebook won't know about the function
# We'll use PythonTutor to help us out!
# https://pythontutor.com/
```
%% Cell type:code id: tags:
``` python
# Now we call/invoke the cube function!
```
%% Cell type:code id: tags:
``` python
# In the bad_cube function definition, use print instead of return
def bad_cube(side):
pass
```
%% Cell type:code id: tags:
``` python
# Explain what goes wrong in these function calls.
x = bad_cube(5)
print(x)
```
%% Cell type:markdown id: tags:
## `return` vs `print`
- `return` enables us to send output from a function to the calling place
- default `return` value is `None`
- that means, when you don't have a `return` statement, `None` will be returned
- `print` function simply displays / prints something
- it cannot enable you to produce output from a function
%% Cell type:code id: tags:
``` python
# Write a function that determines if one number is between two other numbers
# return a boolean ... True or False
def is_between(lower, num, upper):
pass
# you can call a function in the same cell that you defined it
```
%% Cell type:code id: tags:
``` python
# Example 3: write a function get_grid that works like this:
# get_grid(5, 3, "@") returns the string
# @@@@@
# @@@@@
# @@@@@
# Let's practice Incremental Coding
# first, try to do this with string operators and literals
```
%% Cell type:code id: tags:
``` python
# then, try to do this with variables
width = 5
height = 3
symbol = '#'
```
%% Cell type:code id: tags:
``` python
# now, try to write a function
# think about what would be good names for the parameters
```
%% Cell type:code id: tags:
``` python
# Finally, add in a parameter for a title that appears above the grid
def get_grid_with_title(width, height, symb, title='My Grid'):
pass
```
%% Cell type:code id: tags:
``` python
print(get_grid_with_title(7, 7, title='CS220 Grid', symb='&'))
```
%% Cell type:markdown id: tags:
## Types of arguments
- positional
- keyword
- default
Python fills arguments in this order: positional, keyword,
%% Cell type:code id: tags:
``` python
def add3(x, y = 100, z = 100):
"""adds three numbers""" #documentation string
print ("x = " + str(x))
print ("y = " + str(y))
print ("z = " + str(z))
return x + y + z
addition_of_3 = add3(100, 10, 5)
print(addition_of_3)
# TODO: 1. sum is a bad variable, discuss: why. What would be a better variable name?
# TODO: 2. what type of arguments are 100, 10, and 5?
help(add3)
```
%% Cell type:code id: tags:
``` python
print(add3(x = 1, z = 2, y = 5)) #TODO: what type of arguments are these?
```
%% Cell type:code id: tags:
``` python
add3(5, 6) # TODO: what type of argument gets filled for the parameter z?
```
%% Cell type:markdown id: tags:
Positional arguments need to be specified before keyword arguments.
%% Cell type:code id: tags:
``` python
# Incorrect function call
add3(z = 5, 2, 7)
# TODO: what category of error is this?
```
%% Cell type:code id: tags:
``` python
# Incorrect function definition
# We must specify non-default arguments first
def add3_bad_version(x = 10, y, z):
"""adds three numbers""" #documentation string
return x + y + z
```
%% Cell type:code id: tags:
``` python
# Incorrect function call
add3(5, 3, 10, x = 4)
# TODO: what category of error is this?
```
%% Cell type:code id: tags:
``` python
# TODO: will this function call work?
add3(y = 5, z = 10)
```
%% Cell type:code id: tags:
``` python
# TODO: will this function call work?
add3()
```
%% Cell type:markdown id: tags:
## fruitful function versus void function
- fruitful function: returns something
- ex: add3
- void function: doesn't return anything
- ex: bad_add3_v1
%% Cell type:code id: tags:
``` python
# Example of void function
def bad_add3_v1(x, y, z):
print(x + y + z)
print(bad_add3_v1(4, 2, 1))
```
%% Cell type:code id: tags:
``` python
print(bad_add3_v1(4, 2, 1) ** 2) # Cannot apply mathematical operator to None
```
%% Cell type:markdown id: tags:
### `return` statement is final
- exactly *one* `return` statement gets executed for a function call
- immediately after encountering `return`, function execution terminates
%% Cell type:code id: tags:
``` python
def bad_add3_v2(x, y, z):
return x
return x + y + z # will never execute
bad_add3_v2(50, 60, 70)
```
%% Cell type:markdown id: tags:
## Tracing
- Try tracing this manually...
- ...then use [PythonTutor](https://pythontutor.com/visualize.html#code=def%20func_c%28%29%3A%0A%20%20%20%20print%28%22C%22%29%0A%0Adef%20func_b%28%29%3A%0A%20%20%20%20print%28%22B1%22%29%0A%20%20%20%20func_c%28%29%0A%20%20%20%20print%28%22B2%22%29%0A%0Adef%20func_a%28%29%3A%0A%20%20%20%20print%28%22A1%22%29%0A%20%20%20%20func_b%28%29%0A%20%20%20%20print%28%22A2%22%29%0A%0Afunc_a%28%29&cumulative=false&heapPrimitives=nevernest&mode=edit&origin=opt-frontend.js&py=3&rawInputLstJSON=%5B%5D&textReferences=false)
%% Cell type:code id: tags:
``` python
def func_c():
print("C")
def func_b():
print("B1")
func_c()
print("B2")
def func_a():
print("A1")
func_b()
print("A2")
func_a()
```
%% Cell type:code id: tags:
``` python
# Explain worksheet, start part one of each problem
# This worksheet has questions very similar to your exam!
```
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# Warmup 1: Jupyter Notebook stuck in [*]?
# Press the stop button! It's probably waiting for input.
# Otherwise, restart the kernal! (and run the cells)
x = int(input("Type in a number: "))
print("The number is " + str(x), x + 1, x + 2, x + 3, x + 4, sep=" then ", end="!\n")
```
%% Cell type:code id: tags:
``` python
# Warmup 2: Write a function that prints the factorial of parameter num
def do_factorial(num):
pass
```
%% Cell type:code id: tags:
``` python
# Warmup 3: Complete the code to print a treasure map where an X is placed
# treasure_row, treasure_col (starting from 0)
def print_treasure_map(symbol='-', height=4, width=4, treasure_row=2, treasure_col=2):
i = 0
while ???: # TODO: Complete the loop condition for printing out each row.
j = 0
while j < width:
if ???: # TODO: Complete the if condition for checking if we print an X or the symbol.
print('X', end="")
else:
print(symbol, end="")
j += ??? # TODO: Complete the statement so we do not run into an infinite loop.
print()
i += 1
print_treasure_map()
print_treasure_map(width=10, height=10)
print_treasure_map('#', 7, 4, treasure_row=0, treasure_col=1)
print_treasure_map('.', 5, 8, 3, 6)
```
%% Cell type:markdown id: tags:
# CS220: Lecture 12
## Learning Objectives
After this lecture you will be able to...
- Iterate through a dataset using for idx in range(project.count())
- Compute the frequency of data that meets a certain criteria
- Find the maximum or minimum value of a numeric column in a dataset
- Use break and continue in for loops when processing a dataset
- Handle missing numeric values when computing a maximum/minimum
- Use the index of a maximum or minimum to access other information about that data item
%% Cell type:code id: tags:
``` python
import project
```
%% Cell type:code id: tags:
``` python
help(project)
```
%% Cell type:code id: tags:
``` python
# Get the total # of responses
project.count()
```
%% Cell type:code id: tags:
``` python
# Get the first student's primary major.
# With indices, we always start from 0!
project.get_primary_major(0)
```
%% Cell type:code id: tags:
``` python
# Example 1: Print and Break
for i in range(project.count()):
print (i, project.get_primary_major(i))
if i == 10:
break
```
%% Cell type:code id: tags:
``` python
# TODO: Write the same code as above using a while loop!
```
%% Cell type:code id: tags:
``` python
# Example 2: How many students are not in Computer Science?
non_cs = 0
for i in range(project.count()):
major = project.get_primary_major(i)
if major == "Computer Science":
continue
non_cs += 1
print(non_cs, "out of", project.count(), "are non-cs!")
```
%% Cell type:code id: tags:
``` python
# TODO: How many students are in Data Science or Statistics?
# BONUS: Can you express this as a percentage?
# BONUS+: ...rounded to 2 decimal places?
```
%% Cell type:code id: tags:
``` python
# max = 0 # don't use built-in function names as variables
max_age = 0
for i in range(project.count()):
student_age = project.get_age(i)
if student_age > max_age:
max_age = student_age
print("The oldest student is", max_age)
# HINT: Did everyone fill out an age?
```
%% Cell type:code id: tags:
``` python
# TODO: What is the age of the youngest student?
```
%% Cell type:code id: tags:
``` python
# Example 5: How many early birds are there below the age of 21?
early_birds = 0
for i in range(project.count()):
sleep_habit = project.get_sleep_habit(i)
age = project.get_age(i)
if age != "":
age = int(age)
if ???: # TODO Complete this condition!
early_birds += 1
print("There are", early_birds, "early birds below the age of 21.")
```
%% Cell type:code id: tags:
``` python
# TODO: What percentage of 20-year-olds are early birds?
# BOUNUS: How can we generalize our code to 'What percentage of x-year-olds are early birds?'
```
%% Cell type:code id: tags:
``` python
# Other tasks for you to try...
# - What is the average age of the class?
# - What is the class's favorite pizza topping?
# - What is the most popular major?
# - For all students that have another major, print out what it is.
# - What zip code do the majority of pineapple-eating night owls live in?
```
__student__ = []
def __init__():
import csv
"""This function will read in the csv_file and store it in a list of dictionaries"""
__student__.clear()
with open('cs220_survey_data.csv', mode='r', encoding='utf-8') as csv_file:
csv_reader = csv.DictReader(csv_file)
for row in csv_reader:
__student__.append(row)
def count():
"""This function will return the number of records in the dataset"""
return len(__student__)
def get_lecture(idx):
"""get_lecture(idx) returns the lecture of the student in row idx"""
return __student__[int(idx)]['Lecture']
def get_section(idx):
"""get_lecture(idx) returns the section of the student in row idx"""
return __student__[int(idx)]['section']
def get_age(idx):
"""get_age(idx) returns the age of the student in row idx"""
return __student__[int(idx)]['Age']
def get_primary_major(idx):
"""get_primary_major(idx) returns the primary major of the student in row idx"""
return __student__[int(idx)]['Primary major']
def get_other_majors(idx):
"""get_other_majors(idx) returns the secondary major of the student in row idx"""
return __student__[int(idx)]['Other majors']
def get_zip_code(idx):
"""get_zip_code(idx) returns the residential zip code of the student in row idx"""
return __student__[int(idx)]['Zip Code']
def get_pizza_topping(idx):
"""get_pizza_topping(idx) returns the preferred pizza toppings of the student in row idx"""
return __student__[int(idx)]['Pizza topping']
def get_cats_or_dogs(idx):
"""get_cats_or_dogs(idx) returns whether student in row idx likes cats or dogs"""
return __student__[int(idx)]['Cats or dogs']
def get_runner(idx):
"""get_runner(idx) returns whether student in row idx is a runner"""
return __student__[int(idx)]['Runner']
def get_sleep_habit(idx):
"""get_sleep_habit(idx) returns the sleep habit of the student in row idx"""
return __student__[int(idx)]['Sleep habit']
def get_procrastinator(idx):
"""get_procrastinator(idx) returns whether student in row idx is a procrastinator"""
return __student__[int(idx)]['Procrastinator']
def get_song(idx):
"""get_procrastinator(idx) returns the student in row idx favorite song"""
return __student__[int(idx)]['Song']
__init__()
This diff is collapsed.
This diff is collapsed.