Rules for this Student Notes:
1. Don’t write silliness
*
Copy and paste your code here to see it running: https://pythontutor.com/visualize.html#mode=edit
# Notes from class of 8/7/24
```
emojis = ["❌", "⚔️", "🫥", "💺"]
for bob in emojis:
print("I'm in the loop")
print("Still in the loop")
print(bob)
print("still here")
print("Now I'm not")
```
**Output:**
> I am in the loop
> ❌
> Still here
> I’m in the loop
> ⚔️
> Still here
> I’m in the loop
> 🫥
> Still here
> I’m in the loop
> 💺
> Still here
> Now I’m not
Loopsies 4 times because there are 4 emojis
Bob is the loop variable
Random does not work by itself it needs to be random.choice to make a difference in life
If something is true and you want it to work you must INDENT
Elif = “or else,if”
Else=”or else”
---
_command c to copy_
_command v to paste_
_command a select all_
_command z means to undo_
---
```
== is a question
6==7—> False
x==y—> we don’t know because x and y are undefined
x=6 is an assignment
X is pointing to 6 therefore x is declaring itself to be 6
```
Modern and advanced thermostat that can tell three things (cold,warm,hot)
```
if temp <60:
print(“cold”)
elif temp < 70:
print(“warm”)
else:
print (“Hot”)
```
Loop to randomly pick the temperature
```
import random
for i in range(10):
temp = random.randint(30,100)
if temp < 60:
print("cold!")
elif temp < 70:
print("warm")
else:
print("hot!")
```
# Doing math with numbers
```
x = 7
print(x + 2) # prints 9
print(x / 2) # prints 3.5
print(x**2) # **2 means x times x, so it prints 49
```
# 2024-08-16
Homework answers
```
"""
HOMEWORK PROBLEM 1:
Write some code that, if you have score = <some number> , it prints A if it’s 90 or above, B if it’s 80 or above, etc.
HOMEWORK PROBLEM 2:
Write some code that goes through the numbers 1 through 10, and prints the number squared
Check the notes for a reminder of how to do “a number squared” in python.
"""
score = 47
if score >= 90:
print("a")
elif score >= 80:
print("b")
elif score >= 70:
print("c")
elif score >= 60:
print("d")
else:
print("f------")
# PROBLEM 2
for num in range(1, 11):
print(num**2)
```
## Making websites
http://zerotocode.org/milestones/introduction-to-html/
https://codeframe.co/f/c7325cd9743e/e3b0c44298fc.html
Streamlite unbias way to do stuff
https://streamlit.io/playground
# 2024-09-23
**Whenever you do anything thing on the streamlit app in the streamlit app it runs the whole app from top to bottom**
Str stands for string
"Ok um, so we've seen integers, booleans, and floats."
-Zachary Blackwood
Streamlit widgets: https://docs.streamlit.io/develop/api-reference/widgets
# How do I edit my app?
1. Go to https://streamlit.io/playground
2. sign in with github
3. and click on edit codespace after you click on the three dots next to your project.
🌺
when indents are used then the function runs but when the indents stop it then the function stops. (sorry if this makes no sense)
HELLO MOO DENG LOVERS!!!🦛
I am on notes
-🌺Felicity🌺
a good reason for functions is they can do a bunch of things all at once.🥳
September 30 2024
Class notes
```
import streamlit as st
num1 = st.number_input("num1", value=4)
num2 = st.number_input("num2", value=5)
st.write("num1 + num2 =", num2+num1)
```
Homework=Make a calculator that can plus, minus, times, and divide. Using buttons.
Good reason for functions: they can do a bunch of things all at once like.... COOOL PROGRAM, ice cream, fatty the cagt etc.
# 🌺**To use a funtion, just call out its name (With parenthesis at the end)**
respect your elders
st.button makes buttons
st.writes writes
st..... = ......
```
def hello(name):
print("this is the hello link thing")
print("I am still in the thing")
print("I think it is called a loop")
print("ya it is called a loop")
print("now I am not in the loop!!")
print("wow it is true I am not in it!!! wow")
```
Multiple inputs, put commas between them
# output of a function ALWAYS starts with "return"
**function can have inputs, outputs, and multiple of each**
snuffalufagous
🥳
Program: https://python-fiddle.com/saved/61QvenSO6G5LECWZH6hi
Latest:
https://python-fiddle.com/saved/klZiTSlQAOaU5IMRCZWk
# Example Code from 2024-10-08
```
import streamlit as st
import random
def get_grade(test_score):
if test_score == 100:
grade = "A+"
elif test_score >= 90:
grade = "A"
elif test_score >= 80:
grade = "B"
elif test_score >= 70:
grade = "C"
else:
grade = "F"
return grade
test_score = st.slider("What is your test score?")
grade = get_grade(test_score)
st.write(grade)
# HOMEWORK: Make the get_roll function work!
st.write("Roll two dice and get the result")
num_sides = st.slider("How many sides should your dice have?", min_value=2, max_value=20)
roll = get_roll(num_sides)
st.write("Roll is:", roll)
```
Class 10/14/24
Homework for this class:
import streamlit as st
import random
# 2024-10-14
# HOMEWORK: Make the get_roll function work!
```python
def get_roll(num_sides):
first_roll=random.randint(1,num_sides)
second_roll=random.randint(1,num_sides)
roll=(first_roll+second_roll)
return roll
st.write("Roll two dice and get the result")
num_sides = st.slider("How many sides should your dice have?", min_value=2, max_value=20)
roll = get_roll(num_sides)
st.write("Roll is:", roll)
st.button("Reroll")
```
```python
def get_roll(num_sides, num_dice):
total = 0
for i in range(num_dice):
roll = random.randint(1, num_sides)
total = total+roll
return total
```
# Lists
to have a list there must be[]
```python
my_list = ["Emory", "Felicity", "Katedagr8", "El", "El2"]
st.write(my_list)
# How can I get the first person in the list?
my_list[0]
```
to get the last in a list do
```
my_list[-1]
```
to replace something
```
my_list[-1] = "Moo Deng"
```
this is how you could change something in your list if needed
☹️
this can be helpful for multiple things
# Dictionaries
```python
# Dictionary
# has 1 or more
# key: value
stuff = {
"Light": "Bright stuff",
"Dark": "Not light",
}
student = {
"Name": "Bobby Georgensen",
"Favorite color": "Blue",
"Ice cream": "Mint",
"Age": 8,
}
# To get values out of
# a dictionary
# dict_name[KEY]
student["Favorite color"]
```
# Number 1 rule in Notes:
**NO SILLINESS**
# October 21, 2024
lists have [] square brackets and , comma
dictionaries have {} braces and Key colon value
To get an item out of a list say the name of the list then [] then a number. To get the first 0 to get second 1 ect. Last item -1
To get an item out of a dictionary [] and the key. (sometimes slap "")
if you do to some places the 1st flor will be the 2nd flor
hellohellohello
Class Notes 10/21/24
F-String
f"some string {Some_variable} more stuff"
answer = 6 * 4 / 27 + 165 -12
st.write(f"The answer is {answer}!")
# October 28, 2024
### (the day before Felicity's B'day!!!)
boo
How to install a pithon pacage in your codespace:
If your app ever stops working, type, `streamlit run streamlit_app.py` at the bottom
```
streamlit run streamlit_app.py
```
## TO INSTALL A PACKAGE
1. 🌺`pip install pyjokes`!🥧😂
2. in requirements.txt put `pyjokes`
---
import streamlit as st
It should be blank
use get joke
If you just put the name of the package, streamlit will tell you things about it!If you put . your editor will tell you what you can do.
Saint Write!!!
Then, it will tell you a bad, nerdy joke!
Woohoo!
```response = requests.get("https://jsonplaceholder.typicode.com/users/1")```
when you change the number at the end you get a different user
```https://pokeapi.co/api/v2/pokemon/1/```
Notes from class 11/11/24
# November 11 2024
if you put f in st.write you can do this
```
name = "bob"
st.write(f"hello {name}. that is beutiful name.")
```
and it will print `hello bob. that is a beutiful name`
## TO INSTALL A PACKAGE
1. 🌺`pip install PACKAGE_NAME`!🥧😂
2. in requirements.txt put `PACKAGE_NAME`
except, use the actual name of the package (like `requests`, or `streamlit-extras`) instead of PACKAGE_NAME
# 2024-11-18
How do I keep track of what has happened in my program?
Examples:
* Cash register
* Calculator
* Google (history)
* GPS
* Video game
STATE
*append records history
In streamlit, whenever you push a button, or use another widget, it reruns the app from top to bottom.
THIS DOESN'T WORK
```python
import streamlit as st
my_stuff = []
if st.button("Add a thing"):
my_stuff.append("A thing!")
st.write(str(my_stuff))
```
SESSION STATE
st.session_state=dictionary
-keeps history of what has happened in the app
-also keeps track of how many times the button has been pressed
boolion=true or false
st.checkbox=a single boolion
streamlit--> docs_--> can find specific things
```python
import streamlit as st
output = st.checkbox("Brush your teeth")
st.write(output)
todos = {
"Brush your teeth": False,
"Comb your hair": False,
"Wake up": True,
}
st.write(todos)
if st.button("Add a new item"):
...
if "my_stuff" not in st.session_state:
st.session_state["my_stuff"] = []
if st.button("Add a thing"):
st.session_state["my_stuff"].append("A thing!")
st.write("SESSION STATE:")
st.write(str(st.session_state))
```
https://streamlit.io/playground
#### November 25, 2024
```python
import streamlit as st
st.write("Hello☺️! This is a helpful daily schedule to help you be more: Fabulously Encouraging, Lovely, Incredible, Careing, Incomprehendibly Trustworthy, Yummilicious!")
# Part 1:
# This puts some starting values in the list of todos
if "TODO_LIST" not in st.session_state:
st.session_state["TODO_LIST"] = ["Clean Room", "Check Mailbox"]
# Part 2:
# Gives you a box to write in
# And then there's a button
# If you push that button, it adds the thing you typed to the list
title = st.text_input("Add your own", "(example, have a Christmas party)")
if st.button("add a thing"):
st.session_state["TODO_LIST"].append(title)
# Part 3:
# For each item in your list, it makes a checkbox
for checkbox in st.session_state["TODO_LIST"]:
st.checkbox(checkbox)
#st.write("SESSION STATE:")
#st.write(str(st.session_state))
```
This was the homework assigned and it shows how to make a list and then have a loop that prints each value off each time
#####BIG PROJECT
-use at least one dictionary or list
-be fun
-be interactive
-use at least one loop
-
DUE DECEMBER 16 2024
a with in python is kind of like a loop it says all of these things are related to each other groups things together
st.chat_message
st.chat_input
Learn more about streamlit chat commands https://docs.streamlit.io/develop/tutorials/llms/build-conversational-apps
Silly Example:
```python!
import streamlit as st
question = st.chat_input("What can I do for you today?")
# If they haven't put in a question yet, don't keep going
if question is None:
st.stop()
with st.chat_message("user"):
st.write(question)
if question == "help":
with st.chat_message("assistant"):
st.write("I'll save you!!!")
```
# 2024-12-02
### Streamlit layout tools
https://docs.streamlit.io/develop/api-reference/layout
Expander / popover
```python!
with st.expander("Click here to learn more"):
st.write("Secret stuff")
st.write("Secret stuff")
st.write("More secret stuff")
st.write("Not secret")
```
```python!
with st.popover("Click here to learn more"):
st.write("Secret stuff")
st.write("Secret stuff")
st.write("More secret stuff")
st.button("Press me")
st.write("Not secret")
```
Columns
```python!
col1, col2, col3 = st.columns(3)
with col1:
st.header("A cat")
st.image("https://static.streamlit.io/examples/cat.jpg")
with col2:
st.header("A dog")
st.image("https://static.streamlit.io/examples/dog.jpg")
with col3:
st.header("An owl")
st.image("https://static.streamlit.io/examples/owl.jpg")
```
Sidebar
```python!
with st.sidebar:
st.button("Where am I?")
st.write("I'M IN THE SIDEBAR")
```
Tabs
```python!
import streamlit as st
kate, emory, cupcake, elizabeth = st.tabs(["Kate", "Emory", "Cupcake", "Elizabeth"])
with cupcake:
st.write("Cupcake?")
with kate:
st.write("This is the Kate tab!")
```
# 2024-12-09
1. Toast
```python
if st.button("Do something"):
st.toast("Done!", icon='😍')
```
Nice for little notifications
Looks like this:

2. Editing Data (like a list)
```python=
# If you want to just edit a single STRING
name = st.text_input("Enter your name")
st.write(name)
# If you want to edit a LIST!
name_list = st.data_editor(
["Felicity", "Elsie", "Emory", "Kate The Great"],
num_rows="dynamic"
)
st.text(name_list)
```
3. This is how you save data:
```import streamlit as st
from sqlitedict import SqliteDict
def save_data(name, data):
with SqliteDict("example.sqlite", autocommit=True) as db:
db[name] = data
def get_data(name):
with SqliteDict("example.sqlite") as db:
try:
return db[name]
except KeyError:
st.error(f"Data named {name} not found")
return None
name = st.text_input("What's the name of the data?")
save, load = st.tabs(["Save data", "Load data"])
with save:
st.write("Data to save:")
numbers = st.data_editor([1, 2, 3, 4, 5], num_rows='dynamic')
if st.button("Save"):
save_data(name, numbers)
st.toast(f"Data saved to `{name}`")
with load:
if st.button("Load"):
st.toast(f"Loading data `{name}`")
st.write(get_data(name))
```
3. Saving Data
https://github.com/blackary/blank-app/blob/main/pages/save_data.py
```python=
import streamlit as st
from sqlitedict import SqliteDict
def save_data(name, data):
with SqliteDict("example.sqlite", autocommit=True) as db:
db[name] = data
def get_data(name):
with SqliteDict("example.sqlite") as db:
try:
return db[name]
except KeyError:
st.error(f"Data named {name} not found")
return None
```
This is an example of using a loop in Streamlit:
```python
image_urls = ["imageofcat1.jpeg" "imageofcat2.jpeg" "imageofcat3.jpeg"]
for picture in image_urls:
st.image(picture)
```
This is a list
* Item 1
* Item 2
* Item 3
* Then oyu do that!
## Class 20-1-25
Using Functions
*Snakecase names
*short names
*don't have them do a million things
*there are many ways that you can write functions
*you can call functions from inside functions!
### Half-time
`say -v '?'`
`say -v Grandma How are you`