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 6166 additions and 0 deletions
File added
File added
File added
File added
File added
File added
File added
This diff is collapsed.
**/.ipynb_checkpoints/**
**/__pycache__/**
\ No newline at end of file
name = input("Hello! What's your name? ")
print("It's nice to meet you, " + name)
%% Cell type:code id: tags:
``` python
# Warmup 1
# Create 3 variables.
# Assign each one a data value of a different type.
my_cool_num = 34
name = "Cole"
score1 = 12.2
```
%% Cell type:markdown id: tags:
### Python Variable Names
*Python* requires that variables...
- Only use letters a-z (upper and lower), numbers, and underscores.
- Don’t start with a number
- Don’t use Python keywords (e.g., `and`, `False`, etc)
In addition, *CS220 Course Staff* ask that variables...
- Only use the English alphabet and numbers
- Use snake_case for variable names (as opposed to camelCase or PascalCase)
- Make variable names *meaningful*
Python won't run for the first set of rules; CS220 course staff will take off points for the second set of rules.
%% Cell type:code id: tags:
``` python
# Warmup 2
# Decide if the following variables are valid in Python.
# Write VALID or INVALID next to them.
# INVALID: my.name = "Meena"
# INVALID: 1st_place = "Andy"
# INVALID: stop&go = False
# INVALID: False = 100
# VALID: end_game = True
```
%% Cell type:code id: tags:
``` python
# Warmup 3
print(True and not False) # Write your prediction here!
print(type((5 // 1.2))) # Write your prediction here!
print(1 <= 2 and "a" < "A") # Write your prediction here!
print(1 <= 2 or "a" < "A") # Write your prediction here!
print(len("2") + 1) # Write your prediction here!
```
%% Output
True
<class 'float'>
False
True
2
%% Cell type:code id: tags:
``` python
# Warmup 4
# Calculate how old a dog is in dog years given the year they were born
# 1 year is equal to 7 dog years!
# e.g. a dog born in 2019 is 28 years old (7 * 4)
year_born = 2017
dog_years = (2023 - year_born) * 7
print("Your dog is " + str(dog_years) + " years old!")
```
%% Output
Your dog is 42 years old!
%% Cell type:code id: tags:
``` python
# Warmup 5
# Given the number of seconds, compute the number of hours, minutes, and seconds.
# e.g. if seconds is 65, the correct output (with \n in-between) is 0 1 5
# e.g. if seconds is 192, the correct output (with \n in-between) is 0 3 12
# e.g. if seconds is 3739, the correct output (with \n in-between) is 1 2 19
seconds = 3739
# First, we have to get the number of hours.
# There are 60 * 60 = 3600 seconds in an hour, so
# we use integer division to get the whole number of hours.
hours = seconds // 3600
# What we have left over is the remainder of seconds.
# We use the modulos operator to get the remainder.
seconds = seconds % 3600
# Same thing for minutes!
# We use integer division to get the whole number of minutes.
minutes = seconds // 60
# What we have left over is the remainder of seconds.
seconds = seconds % 60
# Print out our results
print(hours)
print(minutes)
print(seconds)
```
%% Output
1
2
19
%% Cell type:markdown id: tags:
# CS220: Lecture 05
## Learning Objectives
- Call `input()` to accept and process string input
- Call type cast functions to convert to appropriate type: `int()`, `bool()`, `float()`, `str()`
- Concatenate values onto strings within a print function by converting to `str()`
- Using correct vocabulary, explain a function call
- call/invoke, parameter, argument, keyword (named) arguments, return value
- Use `sep`, `end` keyword arguments with the print() function
- Use some common built-in functions such as round(), abs()
- import functions from a built-in module using `import`, `from`
- Call functions in modules using the attribute operator `.`
%% Cell type:markdown id: tags:
### Vocabulary
| Term | Definition |
| :- | :- |
| function definition | a grouping of lines of code; a way for us to tell our program to run that entire group of code |
| call / invoke | a statement that instructs the program to run all the lines of code in a function definition, and then come back afterward |
| parameter | variable that receives input to function |
| argument | value sent to a function (lines up with parameter) |
| keyword (named) argument | argument explicitly tied to a parameter |
| return value | function output sent back to calling code |
%% Cell type:markdown id: tags:
### Previously Used Functions.
We have used functions before! Namely `print`, `type`, and `len`.
What parameters did they have; what arguments did we send them?
%% Cell type:code id: tags:
``` python
print("hello world")
print(len("apples"))
print(type(1 < 2))
```
%% Output
hello world
6
<class 'bool'>
%% Cell type:markdown id: tags:
Let's take a closer look at the `print` function.
1. Use the [official Python reference](https://docs.python.org/3/library/functions.html#print)
2. Use the [w3schools reference](https://www.w3schools.com/python/ref_func_print.asp)
3. Use the `help` function
%% Cell type:code id: tags:
``` python
help(print)
```
%% Output
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
%% Cell type:code id: tags:
``` python
print("1", "two", "3!")
```
%% Output
1 two 3!
%% Cell type:code id: tags:
``` python
# Can you add a keyword argument that will connect the names with the word 'and'?
print('Bob', 'Alice', 'Dylan', 'Gretchen', sep=' and ')
```
%% Output
Bob and Alice and Dylan and Gretchen
%% Cell type:code id: tags:
``` python
# Can you add a keyword argument that will make the output appear on a single line?
print('Good', end=' ')
print('Morning!')
```
%% Output
Good Morning!
%% Cell type:code id: tags:
``` python
# Guess what will get printed
print("hello", "world", sep = "|", end = ";\n")
print("its", "so", "cold", sep = "^", end = "...\n")
print("*" * 4, "#" * 6, sep = "\t", end = "<END>")
print("*" * 6, "#" * 8, sep = "||", end = "<END>")
print("\n", end = "")
```
%% Output
hello|world;
its^so^cold...
**** ######<END>******||########<END>
%% Cell type:markdown id: tags:
### Type Conversion Functions
| Function | Purpose |
| :- | :- |
| `int(value)` | Turns `value` into an integer |
| `float(value)` | Turns `value` into a float |
| `str(value)` | Turns `value` into a string |
| `bool(value)` | Turns `value` into a boolean |
%% Cell type:code id: tags:
``` python
# This code works!
name = input("Enter your name: ")
print(type(name))
print("Hello " + name + "!")
```
%% Output
Enter your name: Cole
<class 'str'>
Hello Cole!
%% Cell type:code id: tags:
``` python
# This code doesn't work! Try to fix it.
age = input("Enter your age: ")
print(type(age))
age = int(age)
age = age + 10 # we can shorten this to age += 10
print("In 10 years, you will be " + str(age))
```
%% Output
Enter your age: 25
<class 'str'>
In 10 years, you will be 35
%% Cell type:code id: tags:
``` python
# This code doesn't work! Try to fix it.
temp = input("Enter your temperature: ")
print(type(temp))
temp_ok = float(temp) < 101.1
print(type(temp_ok))
print("You can enter lab: " + str(temp_ok))
```
%% Output
Enter your temperature: 98.7
<class 'str'>
<class 'bool'>
You can enter lab: True
%% Cell type:markdown id: tags:
### Other Built-In Functions
We can refer to [this resource](https://www.w3schools.com/python/python_ref_functions.asp) to see other built-in functions in Python. Let's practice using `round` and `abs`.
%% Cell type:code id: tags:
``` python
# Print the help documentation for the round function
print(help(round))
# Print the help documentation for the abs function
print(help(abs))
```
%% Output
Help on built-in function round in module builtins:
round(number, ndigits=None)
Round a number to a given precision in decimal digits.
The return value is an integer if ndigits is omitted or None. Otherwise
the return value has the same type as the number. ndigits may be negative.
None
Help on built-in function abs in module builtins:
abs(x, /)
Return the absolute value of the argument.
None
%% Cell type:code id: tags:
``` python
# Round the number 84.7
round(84.7)
```
%% Output
85
%% Cell type:code id: tags:
``` python
# Round the number 19.74812 to the second decimal place
round(19.74812, ndigits=2)
```
%% Output
19.75
%% Cell type:code id: tags:
``` python
# Get the absolute value of -12
abs(-12)
```
%% Output
12
%% Cell type:code id: tags:
``` python
# Get the square root of 81
# This was a trick question! Math is not built-in. We must import it below.
```
%% Cell type:markdown id: tags:
### Importing From Other Modules
We'll look at two other common modules (collections of functions): `math` and `random`.
There are a few ways we can do this...
- We can write `import <module_name>` and use a function by `<module_name>.<function_name>`.
- We can write `from <module_name> import <function_name>` and use a function(s) directly by its name.
- We can write `from <module_name> import *` and directly use any function by name.
%% Cell type:code id: tags:
``` python
# Normally we like to have our imports at the top of our notebook
import math
import random
```
%% Cell type:code id: tags:
``` python
# Use the . (attribute accessor)
math.sqrt(17)
```
%% Output
4.123105625617661
%% Cell type:code id: tags:
``` python
# Import the function directly
from math import sqrt, cos
print(sqrt(17))
print(cos(91))
```
%% Output
4.123105625617661
-0.9943674609282015
%% Cell type:code id: tags:
``` python
# Import all functions directly
from math import *
print(tan(100))
print(sin(9183))
```
%% Output
-0.5872139151569291
-0.12435083079901083
%% Cell type:code id: tags:
``` python
from random import randint
print(randint(1,10))
# wrong way to call randint
#print(random.randint(1,10))
```
%% Output
2
%% Cell type:code id: tags:
``` python
```
%% Cell type:code id: tags:
``` python
# Warmup 1
# Create 3 variables.
# Assign each one a data value of a different type.
```
%% Cell type:markdown id: tags:
### Python Variable Names
*Python* requires that variables...
- Only use letters a-z (upper and lower), numbers, and underscores.
- Don’t start with a number
- Don’t use Python keywords (e.g., `and`, `False`, etc)
In addition, *CS220 Course Staff* ask that variables...
- Only use the English alphabet and numbers
- Use snake_case for variable names (as opposed to camelCase or PascalCase)
- Make variable names *meaningful*
Python won't run for the first set of rules; CS220 course staff will take off points for the second set of rules.
%% Cell type:code id: tags:
``` python
# Warmup 2
# Decide if the following variables are valid in Python.
# Write VALID or INVALID next to them.
# my.name = "Meena"
# 1st_place = "Andy"
# stop&go = False
# False = 100
# end_game = True
```
%% Cell type:code id: tags:
``` python
# Warmup 3
print(True and not False) # Write your prediction here!
print(type((5 // 1.2))) # Write your prediction here!
print(1 <= 2 and "a" < "A") # Write your prediction here!
print(1 <= 2 or "a" < "A") # Write your prediction here!
print(len("2") + 1) # Write your prediction here!
```
%% Cell type:code id: tags:
``` python
# Warmup 4
# Calculate how old a dog is in dog years given the year they were born
# 1 year is equal to 7 dog years!
# e.g. a dog born in 2019 is 28 years old (7 * 4)
year_born = 2017
dog_years = ???
print("Your dog is " + str(dog_years) + " years old!")
```
%% Cell type:code id: tags:
``` python
# Warmup 5
# Given the number of seconds, compute the number of hours, minutes, and seconds.
# e.g. if seconds is 65, the correct output (with \n in-between) is 0 1 5
# e.g. if seconds is 192, the correct output (with \n in-between) is 0 3 12
# e.g. if seconds is 3739, the correct output (with \n in-between) is 1 2 19
seconds = 3739
```
%% Cell type:markdown id: tags:
# CS220: Lecture 05
## Learning Objectives
- Call `input()` to accept and process string input
- Call type cast functions to convert to appropriate type: `int()`, `bool()`, `float()`, `str()`
- Concatenate values onto strings within a print function by converting to `str()`
- Using correct vocabulary, explain a function call
- call/invoke, parameter, argument, keyword (named) arguments, return value
- Use `sep`, `end` keyword arguments with the print() function
- Use some common built-in functions such as round(), abs()
- import functions from a built-in module using `import`, `from`
- Call functions in modules using the attribute operator `.`
%% Cell type:markdown id: tags:
### Vocabulary
| Term | Definition |
| :- | :- |
| function definition | a grouping of lines of code; a way for us to tell our program to run that entire group of code |
| call / invoke | a statement that instructs the program to run all the lines of code in a function definition, and then come back afterward |
| parameter | variable that receives input to function |
| argument | value sent to a function (lines up with parameter) |
| keyword (named) argument | argument explicitly tied to a parameter |
| return value | function output sent back to calling code |
%% Cell type:markdown id: tags:
### Previously Used Functions.
We have used functions before! Namely `print`, `type`, and `len`.
What parameters did they have; what arguments did we send them?
%% Cell type:code id: tags:
``` python
print("hello world")
print(len("apples"))
print(type(1 < 2))
```
%% Cell type:markdown id: tags:
Let's take a closer look at the `print` function.
1. Use the [official Python reference](https://docs.python.org/3/library/functions.html#print)
2. Use the [w3schools reference](https://www.w3schools.com/python/ref_func_print.asp)
3. Use the `help` function
%% Cell type:code id: tags:
``` python
help(print)
```
%% Cell type:code id: tags:
``` python
print("1", "two", "3!")
```
%% Cell type:code id: tags:
``` python
# Can you add a keyword argument that will connect the names with the word 'and'?
print('Bob', 'Alice', 'Dylan', 'Gretchen')
```
%% Cell type:code id: tags:
``` python
# Can you add a keyword argument that will make the output appear on a single line?
print('Good')
print('Morning!')
```
%% Cell type:code id: tags:
``` python
# Guess what will get printed
print("hello", "world", sep = "|", end = ";\n")
print("its", "so", "cold", sep = "^", end = "...\n")
print("*" * 4, "#" * 6, sep = "\t", end = "<END>")
print("*" * 6, "#" * 8, sep = "||", end = "<END>")
print("\n", end = "")
```
%% Cell type:markdown id: tags:
### Type Conversion Functions
| Function | Purpose |
| :- | :- |
| `int(value)` | Turns `value` into an integer |
| `float(value)` | Turns `value` into a float |
| `str(value)` | Turns `value` into a string |
| `bool(value)` | Turns `value` into a boolean |
%% Cell type:code id: tags:
``` python
# This code works!
name = input("Enter your name: ")
print(type(name))
print("Hello " + name + "!")
```
%% Cell type:code id: tags:
``` python
# This code doesn't work! Try to fix it.
age = input("Enter your age: ")
print(type(age))
age = age + 10 # we can shorten this to age += 10
print("In 10 years, you will be " + str(age))
```
%% Cell type:code id: tags:
``` python
# This code doesn't work! Try to fix it.
temp = input("Enter your temperature: ")
print(type(temp))
temp_ok = temp < 101.1
print("You can enter lab: " + str(temp_ok))
```
%% Cell type:markdown id: tags:
### Other Built-In Functions
We can refer to [this resource](https://www.w3schools.com/python/python_ref_functions.asp) to see other built-in functions in Python. Let's practice using `round` and `abs`.
%% Cell type:code id: tags:
``` python
# Print the help documentation for the round function
# Print the help documentation for the abs function
```
%% Cell type:code id: tags:
``` python
# Round the number 84.7
```
%% Cell type:code id: tags:
``` python
# Round the number 19.74812 to the second decimal place
```
%% Cell type:code id: tags:
``` python
# Get the absolute value of -12
```
%% Cell type:code id: tags:
``` python
# Get the square root of 81
```
%% Cell type:markdown id: tags:
### Importing From Other Modules
We'll look at two other common modules (collections of functions): `math` and `random`.
There are a few ways we can do this...
- We can write `import <module_name>` and use a function by `<module_name>.<function_name>`.
- We can write `from <module_name> import <function_name>` and use a function(s) directly by its name.
- We can write `from <module_name> import *` and directly use any function by name.
%% Cell type:code id: tags:
``` python
# Normally we like to have our imports at the top of our notebook
import math
import random
```
%% Cell type:code id: tags:
``` python
# Use the . (attribute accessor)
math.sqrt(17)
```
%% Cell type:code id: tags:
``` python
# Import the function directly
from math import sqrt
print(sqrt(17))
```
%% Cell type:code id: tags:
``` python
from random import randint
print(randint(1,10))
# wrong way to call randint
#print(random.randint(1,10))
```
%% Cell type:code id: tags:
``` python
# Import all functions directly
from math import *
```
%% Cell type:code id: tags:
``` python
# Warmup 1
# Get the user's name using the input function.
# Then, print out 'Hello, NAME'
name = input("What is your name? ")
print("Hello,", name)
```
%% Output
What is your name? Cole
Hello, Cole
%% 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!
import math
num = float(input("What number would you like to root? "))
rt_num = math.sqrt(num)
print("The sqrt of " + str(num) + " is " + str(rt_num))
```
%% Output
What number would you like to root? 81
The sqrt of 81.0 is 9.0
%% 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 = (float(x) % 2 == 0)
print("That number is even: " + str(is_even))
```
%% Output
Tell me a number! 9
That number is even: False
%% 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
import time
start_time = time.time()
x = 2**1000000000 # a very long computation
end_time = time.time()
# Change the line below to compute the time difference
difference = end_time - start_time
# Seperate each time with a '\n'
print(start_time, end_time, difference, sep='\n')
```
%% Output
1695004233.8965383
1695004246.588747
12.692208766937256
%% Cell type:code id: tags:
``` python
help(time.time)
```
%% Output
Help on built-in function time in module time:
time(...)
time() -> floating point number
Return the current time in seconds since the Epoch.
Fractions of a second may be present if the system clock provides them.
%% Cell type:code id: tags:
``` python
# From the math module, import only the log10 function
from math import log10
# Then, print the log base 10 of 1000
log10(1000)
```
%% Output
3.0
%% 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)
```
%% Output
3.141592653589793
%% Cell type:code id: tags:
``` python
# Try importing and printing 'pi' the proper way!
from math import pi
print(pi)
# or
import math
print(math.pi)
```
%% Output
3.141592653589793
3.141592653589793
%% Cell type:markdown id: tags:
## Functions
%% Cell type:code id: tags:
``` python
# Write a function that cubes any number
def cube(side):
return side ** 3
# 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!
print(cube(5))
print(cube(4) + cube(-3))
print(cube(cube(2)))
```
%% Output
125
37
512
%% Cell type:code id: tags:
``` python
# In the bad_cube function definition, use print instead of return
def bad_cube(side):
print(side ** 3)
```
%% Cell type:code id: tags:
``` python
# Explain what goes wrong in these function calls.
# bad_cube does not return anything, it only prints to the screen
# So we return None, and store it in x.
x = bad_cube(5)
print(x)
```
%% Output
125
None
%% 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):
return lower <= num <= upper # also: num >= lower and num <= upper
# you can call a function in the same cell that you defined it
print(is_between(3, 7, 21))
print(is_between(2, 14, 5))
print(is_between(100, cube(5), 200))
```
%% Output
True
False
True
%% 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
width = 5
height = 3
symbol = '#'
print(((symbol * 5) + '\n') * 3)
```
%% Output
#####
#####
#####
%% Cell type:code id: tags:
``` python
# then, try to do this with variables
width = 5
height = 3
symbol = '#'
print(((symbol * width) + '\n') * height)
```
%% Output
#####
#####
#####
%% Cell type:code id: tags:
``` python
# now, try to write a function
# think about what would be good names for the parameters
def get_grid(width, height, symb):
return (((symb * width) + '\n') * height)
my_grid = get_grid(5, 3, "*");
# do some code
2**1000000000
# ...
print(my_grid)
```
%% Output
*****
*****
*****
%% 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'):
row = (symb * width) + '\n'
grid = ((row) * height)
return title + '\n' + grid
```
%% Cell type:code id: tags:
``` python
print(get_grid_with_title(7, 7, title='CS220 Grid', symb='&'))
```
%% Output
CS220 Grid
&&&&&&&
&&&&&&&
&&&&&&&
&&&&&&&
&&&&&&&
&&&&&&&
&&&&&&&
%% 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)
```
%% Output
x = 100
y = 10
z = 5
115
Help on function add3 in module __main__:
add3(x, y=100, z=100)
adds three numbers
%% Cell type:code id: tags:
``` python
print(add3(x = 1, z = 2, y = 5)) #TODO: what type of arguments are these?
# These are keyword arguments
```
%% Output
x = 1
y = 5
z = 2
8
%% Cell type:code id: tags:
``` python
add3(5, 6) # TODO: what type of argument gets filled for the parameter z?
# 5 and 6 are positional arguments.
# z has a default argument of 100.
```
%% Output
x = 5
y = 6
z = 100
111
%% 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?
# Syntax Error
```
%% Output
Cell In[22], line 2
add3(z = 5, 2, 7)
^
SyntaxError: positional argument follows keyword argument
%% 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?
# Runtime Error
```
%% Cell type:code id: tags:
``` python
# TODO: will this function call work?
add3(y = 5, z = 10)
# No, we are missing an argument for x
```
%% Cell type:code id: tags:
``` python
# TODO: will this function call work?
add3()
# No, we are missing an argument for x
```
%% 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
# 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
```