Skip to content
Snippets Groups Projects
Commit 783a4944 authored by LOUIS TYRRELL OLIPHANT's avatar LOUIS TYRRELL OLIPHANT
Browse files

added louis lec 5 functions

parent b9c2a655
No related branches found
No related tags found
No related merge requests found
%% Cell type:markdown id: tags:
## Warmup
%% Cell type:code id: tags:
``` python
# Warmup 1
# Create 3 variables.
# Assign each one a data value of a different type.
# Open the debugger to view these variables.
```
%% Cell type:code id: tags:
``` python
# Warmup 2
# Write expressions that meet the following criteria:
# exp 1 -- use the "or" operator that prevents division by zero
# using short-circuiting
# exp 2 -- use the "and" operator that prevents division by zero
# using short-circuiting
```
%% Cell type:code id: tags:
``` python
# Warmup 3
# 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 4
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 5
# 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 6
# 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:
## Reminder
* a **literal value** is when you type the value yourself (e.g. `"hello"`, `3.14`, `True`)
* a **variable** is a named memory location that stores a value that can change as the program runs -- know the rules for variable names (also use meaninful names)
* An **assignment statement** is of the form `variable = expression`
* **Errors** can be divided into three categories:
* Syntax errors
* Runtime errors
* Semantic errors
* **Jupyterlab features**: use debugger to view kernel state, ways of running Python code, shortcuts
%% 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:markdown id: tags:
# Using Functions
## Readings
- [Downey Ch 3 ("Function Calls" to "Composition")](https://greenteapress.com/thinkpython2/html/thinkpython2004.html)
- [Python for Everybody, 5.1 - 5.4](https://runestone.academy/ns/books/published//py4e-int/functions/toctree.html)
## 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 `.`
- JupyterLab Features: Notebook cell Types (Code, Markdown, Raw) and Properties (Editable vs. Read-only)
%% 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: `print()`, `type()`, and `len()`
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:
## New Functions For Type Conversion
| 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 all functions from the module 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 dir() to see a directory list of the things (functions) in a module
dir(math)
```
%% Cell type:code id: tags:
``` python
# Then use help() on the name of the function you want to use
# notice that to access the functions from the module you must use dot-notation since we imported
# the module
help(math.sqrt)
```
%% Cell type:code id: tags:
``` python
# Use the . (attribute accessor)
result = math.sqrt(17)
print(result)
```
%% Cell type:code id: tags:
``` python
# Import the function directly
# then ONLY the sqrt function is imported and you do NOT use dot-notation
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, since only the function was imported, not the module
#print(random.randint(1,10))
```
%% Cell type:code id: tags:
``` python
# Import all functions directly
# Now all functions from that module can be used directly, no need to use dot-notation
from math import *
```
%% Cell type:markdown id: tags:
## JupyterLab Features -- Cell Properties
### Cell Type
The cells in a notebook have different properties. One of the most important is the cell's type. On the notebook's menubar, you can see the cells type in the drop-down menu. A cell can be `Raw`, `Markdown`, or `Code`.
![Screenshot 2024-09-12 at 5.04.19 PM.png](attachment:9279cd39-a0ab-4c23-bf4f-a00fe8fdd4fd.png)
`Code` cells are ones where you enter Python commands, `Markdown` cells hold formatted text, and `Raw` cells are ones that do not get converted when exporting from a notebook to some other file type.
### Editable vs. Read-Only cells
If you click the gear icon on the right sidebar and look under the `common tools` section you can see if a cell has been marked as read-only or editable. This can be used to protect from accidentally changing the content of a cell.
<img src="attachment:26314fdb-40a3-4999-af02-6f6686f3211f.png" width="50%" alt="Property Inspector">
%% Cell type:markdown id: tags:
## Summary
You learned how to call **functions** and pass **parameters** to the **arguments** of the function. You can pass parameters by position or by keyword argument. Some functions send a value back, called the **return value**. You learned how to **import** functions from a **module** and call those functions. We looked specifically at type conversion functions, the input() function, some other built-in functions, and functions from the math and random modules.
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