[ad] Food Insecurity Survey
Q&A
Q: what is self.?
A:self.
allows us to reference attributes within the class. So, if there’s an attributename
and you want to use its value within a method, you would stateself.name
.
Q: Do class attributes always go on the outside of init?
A: Yup! An attribute (variable assigned) outside of init will always be a class attribute.
Q: What specific topics exactly should we be studying on for this weeks oral exam?
A: List, string, and dictionary methods. And, methods generally - understanding that they operate directly on an object and the difference between in place and NOT in place
Q: Will we cover Inheritance?
A: I will mention its existence and show an example but will NOT test you on it and we will NOT do any practice problems/assessment questions that deal with it.
Q: im still confused on the item method that we used for the spotify class. were we supposed to know how to use that?
A: Yup - take a look back at the previous lecture methods - that’s where we introduced it and did an example specifically focused on it.
Q: I would like an in depth demonstration on how to use f-strings in a function. Are there two sets of quotation marks when creating an f-string?
A: There are quotes to start and end the string and the lowercase f before the stringf"______"
and then what you want to be in the string goes between the quotes. If you want to get a variable’s value in the string you put it in{}
.
Q: i feel like i still dont understand the concept of classes even though its fairlu simple. what else can o do to figure this out
A: Go to lab! Spend time on the questions in lab; ask staff questions. If uncertain after working on your own, chat with any staff in office hours! And, you can ask an LLM for additional examples to walk through!
Course Announcements
Due this week:
CL6 due Fri
A4 due Sun
Notes:
Reminder to sign up for Oral exam 2 slot (link also on Canvas homepage)
If you have a few minutes, please complete the Food Insecurity Survey before 5/26 <- there’s an optional quiz on Canvas with the link too
At 11AM, it was brought to my attention that I linked to the wrong chapter for VQ11. There WAS a filepaths chapter/video.
everyone who did the quiz, will receive full credit
Probably good to watch the file path video after class today too
Command Line, Scripts & Modules#
file paths (absolute and relative)
command line & shell commands
scripts and modules
import
from
as
There is a textbook chapter on command line. This was NOT required reading ahead of class today. But, FYI.
Jupyter Notebooks are a helpful tool, but they’re bulky.
File Systems#
When you click through the folders (directories) on your computer, you’re interacting with this hierarchical system.
Absolute vs. Relative Paths#
Absolute Paths#
root specifies the ‘highest’ directory in the file structure (the start).
An absolute file path starts with a slash /
specifying the root directory.
Relative Paths#
Command Line#
The command line allows us to:
create files
edit files
run python scripts
etc.
…without clicking on anything.
The Terminal#
The terminal is where you can type these commands into the command line.
Accessing the terminal…
possible on your computer
and on PrairieLearn
Shell Commands#
…can be run in the terminal and Jupyter notebooks
pwd
: Print working directory#
# print working directory
!pwd
ls
: List files in a directory#
# list files (list segments)
!ls
mkdir
: Make a new directory#
# make directory
!mkdir dir_name
touch
: Create a file#
# create an empty file
!touch new_file.py
cd
: Change directory#
# change directory
!cd ~/
Here, we saw ~/
.
~
specifies the user’s home directory of your computereach directory is separated with a slash (
/
)
mv
: Move a file#
# move file
# notice the relative file path
!mv new_file.py dir_name/
cat
: Print the contents of a file#
!cat dir_name/new_file.py
Activity: On your own#
Open up a terminal <- this can be done on PrairieLearn!
Change location to a directory of your choice OR create a new directory
Create a new file
## test out here
Python Files#
Script vs. Module File#
Scripts#
Module Files#
Remember: if you’re writing code, you cannot just click through to the file you want. You need to specify using code where the file you want is.
This is where understanding file paths is critically important.
Text Editors#
Terminal Based Text Editors#
There are text editors designed to be used within a terminal, such as vim
, emacs
, or nano
.
Note: I am mentioning these as an FYI. You are NOT required to use them for this course.
vim#
vim
is a terminal based text-editor. Type vim filename
in command line to open a file in vim.
vim
has different modes:
click
escape
+i
to enter edit mode (insert mode).This will let you write text / code into the file
To escape vim, press
escape
then type:wq
and enter to save and quit vimIf you want to exit without saving, you can do
:!q
to force quit without saving
Non-Terminal Text Editors#
For writing code (outside of notebooks and the terminal), you probably want a code-focused IDE (i.e. Visual Studio Code) or stand-alone text editor (i.e. Sublime
).
Namespaces & Scope#
Each Jupyter Notebook has its own Namespace.
If you have two notebooks open at the same time, they don’t know about eachother or what variables have been created in the other.
Names that are defined and available in a given namespace are in scope.
That is, the scope of an object is where it is available to / from.
# see what's stored in global namespace
a = 3
b = 15
%whos
Modules & Packages#
Modules are stored in Python files (.py). We can import these files into our namespace, to gain access to the module within Python.
In A3 you had to import the package: nltk
:
package is a whole bunch of modules
a module stores python (.py) files
when imported, we have access to its functionality
import
#
import
is a keyword to import external code into the local namespace.
Why do it this way (importing modules)?
Minimize startup costs
Functions in different packages could have the same name - break programs
import
example: random module#
import random
# random.sample() documentation
random.sample?
# Random example
to_choose_from = ['1', '2', '3', '4', '5']
number_to_choose = 2
chosen = random.sample(to_choose_from, number_to_choose)
print(chosen)
Imports: from
& as
#
from
and as
allows us to decide exactly what objects to import into our namespace, and what we call them (in our namespace).
# Import a specific object from a module
from random import choice
## do NOT have to type module name
## using this approach
## to call this
choice(to_choose_from)
# Import a module with a specific name in our namespace
# used when module names are long
import collections as cols
## collections is not defined
## this code will fail
collections.
# this is how you would do it
cols.
# putting it all together
# Import a specific thing and give it a specific name
from string import punctuation as punc
Activity: imports#
Please complete the Google Form: https://forms.gle/1sqLhCfFfGV8sJiR9
# If you want to check the imports
# import collections as col
# from statistics import mean as average
# from os import path
# from random import choice, choices
import ascii_letters from string
Importing Custom Code I#
Why do this?
Having a whole bunch of functions in a Jupyter Notebook will start to get clutered.
Also, they’re not reusable later without copying them into your new notebook.
Modules avoid this!
module: remote.py
#
If you want to practice using import with the remote
example in lecture, store the code in the next cell in a text file saved as remote.py
. Be sure this is saved in the same directory (folder) as the notebook from which you’re trying to call it.
def my_remote_function(input_1, input_2):
"""A function from far away.
This function returns the sum of the two inputs.
"""
return input_1 + input_2
def choice(list_to_choose_from):
"""Choose and return an item from a list.
Notes: I am a custom choice function: I am NOT from `random`.
Hint: my favorite is the last list item.
"""
return list_to_choose_from[-1]
class MyNumbers():
kind_of_thing = 'numbers'
def __init__(self, num1, num2):
self.num1 = num1
self.num2 = num2
def add(self):
return self.num1 + self.num2
def subtract(self):
return self.num2 - self.num1
# Import some custom code
from remote import my_remote_function
# Investigate our imported function
my_remote_function?
# Run our function
my_remote_function(2, 1)
Importing Custom Code II#
# Import a class class from an external module
from remote import MyNumbers
# Define an instance of our custom class
nums = MyNumbers(2, 3)
type(nums)
# Check
nums.add()
# Check the definition of the code we imported
nums.add??
Name Conflicts#
from random import choice
# choice is currently from random module
choice?
choice([1, 2, 3, 4, 5])
from remote import choice
# now it's from my remote module
choice?
choice([1, 2, 3, 4, 5])
While you can have functions with the same name in two different places…do your best to avoid this.
It’s Python legal but bad for your nerves.
A note on *
#
If you see from module import *
this means to import everything (read as ‘from module import everything’).
This is generally considered not to be the best, as it is then unclear in your code exactly where the functionality came from.
# a valid way to import
from random import choice
choice([2,3,4])
2
# a valid way to import
import random
random.choice([2,3,4])
4
## AVOID THIS; WHY I DIDN'T PUT IT IN YOUR NOTES; DON'T DO IT
from random import *
choice([2,3,4,])
script: remote_script.py
#
If you want to run your own script example in lecture, store the code in the next cell in a text file saved as remote_script.py
. Be sure this is saved in the same directory (folder) as the notebook from which you’re trying to call it.
from remote import MyNumbers
nums = MyNumbers(2, 3)
print("nums value: ", nums.num1, nums.num2)
print("nums type: ", type(nums))
# run the script
!python remote_script.py
Executing Python Files#
From the command line, you can execute a Python script using the python
command:
python dir_name/new_file.py
Activity: scripts & modules#
Please complete the Google Form: https://forms.gle/dHxriVi3wen7MYdk7
END OF MATERIAL COVERED ON E2