Chapter 11 and more Flashcards
What’s the only thing that will spit out a float from two intergers despite there being no remainder
Division
How do you perform an exponent equation (n to the 3rd power)
3 ** 3
What are the formatting codes for
integers
floating point numbers
To use comma separators
Percentage format
Exponent(scientific) notion
Exponent (scientific) notion with capital E
integers - :n
floating point numbers :f
To use comma separators :,
Percentage format :%
Exponent(scientific) notion :e
Exponent (scientific) notion with capital E :E
Find the square root of a number using the math import.
Remember to use formatting
import math
number = input(“Please enter a number: “)
number = int(number)
result = math.sqrt(number)
print(“The square root of {:n} is {:6f}”.format(number, result))
To find a full list of math uses, see pg 208
round numbers to the nearest whole number
a = 4.2
print(round(a))
The problem with float is that python stores floats as fractions, but converts it to decimal upon print, this doesn’t always work well. When we need a precise version of a float, what would we do?
from decimal import decimal
a = decimal(“2.3”)
b = decimal(“1.9”)
c = decimal(“8.4”)
result = a + b + c
print(str(result))
Python doesn’t have a dedicated function or module for percentages, what should you do?
multiply by 100 and add a percent sign at the end
What is mean, median, mode, and standard deviation?
Mean is the average of a data set, found by adding all numbers in the data set and then dividing by the number of values in the set123.
Median is the middle value when a data set is ordered from least to greatest. If there are 2 numbers in the middle, the median is the average of those 2 numbers134.
Mode is the number that occurs most often in a data set. Count how many times each number occurs in the data set. The mode is the number with the highest tally. It’s ok if there is more than one mode14.
Standard Deviation - how much does data deviate from the average.
Measures how spread out data is.
Low standard deviation - date closely clustered around mean
High - data dispersed over wider range
Is the data point standard and expected, or unusual and unexpected?
Is the extra ounce of soda in this bottle to be expected or is this something we need to look more into?
Calculate mean, median, mode, and standard deviation
print these out as floats using formatting
import statistics
numbers = [ 1, 4, 17, 62, 12, 84, 5, 8, 21 ]
mean = statistics.mean(numbers)
median = statistics.median(numbers)
mode = statistics.median(numbers)
stdev = statistics.stdev(numbers)
print(“mean: {:f}”.format(mean))
print(“median: {:f}”.format(median))
print(“mode: {:f}.format(mode))
print(“stdev: {:f}”.format(stdev))
Get the current date and time
import datetime
now = datetime.datetime.now()
print(now)
Print the date and the month
aside from this, what other options do you have?
import datetime
now = datetime.datetime.now()
print(now.year)
print(now.month)
day, hour, minute, second, microsecond
Let’s say we want to format datetime in different ways user our “now” variable. How would we do this?
print(now.strftime(“%A, %B, %d, %Y at %I:%M %p”))
This looks a bit more complicated than it is, but you can find what the codes represent on page 215
Finding differences in time can be a bit overwhelming when you try to subtract days and hours and years or whatever you want while taking into account leap years and things of that sort.
Let’s say we want to subtract 18 hours and 49 minutes from the current time. How would we accomplish this?
import datetime
now = datetime.datetime.now()
delta = datetime.timedelta(hours, minutes = 49)
previous_time = now - delta
print(now)
print(previous_time)
Show how many days until your birthday, tee-hee
import timedate
now = timedate.timedate.now()
birthday = timedate.timedate(2024, 7, 16, 0, 0)
print(birthday - now)
Remember to do coffee game for chapters 11, 12, 13 when you’re ready
ok
Create a file, and then read it
string to write
data = “The lazy red fox slept instead of jumping over the dog”
write the date
with open(“fox.txt”, mode = “w”, encoding = “utf-8”) as f:
f.write(data)
Read the file
with open(“fox.txt”, mode = “r”, encoding = “utf-8”) as f:
read_data = f.read()
display results
print(“Original : “ + data)
print(“From disk : “ + read_data)
How would you set it to where you only read from a files first 16 characters
with open(“fox.txt”, mode = “r”, encoding = “utf-8”) as f:
read_data = f.read(16)
If we wanted to do something every 32 bits of a file, how would we do that?
do something here
with open(“fox.txt”, mode = “rb”) as f:
while (c := f.read(32)):
:= <- the walrus operator reports back True or False depending on if it can read what you specify
Read the file line by line and then have it do something to each line
with open(“fox.txt”, mode = “r”) as f:
while (l := f.readline()):
do something
Read the file line by line inside of a list
string to write
data = “The lazy red fox slept instead of jumping over the dog”
write the date
with open(“fox.txt”, mode = “w”, encoding = “utf-8”) as f:
f.write(data)
read
with open(“fox.txt”, mode=”r”, encoding=”utf-8”) as f:
read_data = f.readlines()
print(read_data)
Create a program that takes your inputs and prints them on screen
How would you use this same program to take you input and print to a file?
import sys module
import sys
Read stdin to data_in
data_in = sys.stdin.read()
Write to sdout
bytes_written = sys.stdout.write(data_in)
display stats
print(“Wrote {} bytes to stdout.”.format(bytes_written))
puy ctrl-z then “enter” after your keyboard input
To send this to a file:
python3 names.py(or whatever your program is called) > this
type here and ctrl-z + enter
Why use pickle?
If you’re storing simple data into a file and retrieving it in a simple order it’s not that difficult. You can just pull what you need under [0], [1], [2], etc. This is for like, integers, floats, and that sort of thing.
If you store it in a file, you’re just storing the number though. With pickle, you’re literally storing the object itself. Which is useful for more complicate programs.
As an example, if you have a person class and create an object out of it, you can save that object you made into a binary file, load it, and summon it the same way you normally would with pickle.
Converting back and forth between bytes is known as serialization
Make a list, serialize it with pickle and then read it from pickle
import pickle
customer_names = [“Jim Smith”, “Amber Dobson”, “Al James”]
with open(“customer.dat”, mode = “wb”) as f:
pickle.dump(customer_names, f)
with open (“customer.dat”, mode = “rb”) as f:
loaded_data = pickle.load(f)
print(customer_names)
print(loaded_data)
Get the data from python.org and put it in a variable to later search through or gather info from
import urllib.request
url = “https://www.python.org”
req = urllib.request.Request(url)
with urllib.request.urlopen(req) as response:
page_content = response.read
You’ll see in the next example/question that we don’t add request so I’ll explain what is actually happening.
Request is letting you get specific about what you want, it will let you change headers and stuff. If you just use urlopen you’re saying you don’t care about any additional options, you just want a basic GET request.
Use the Wikipedia API to get some data about Mount Tabora url for api provided below
https://en.wikipedia.org/w/api.php?action=parse&prop=wikitext&format=json&page=Mount_Tambora
from urllib.request import urlopen
import re
from html import unescape
url =”https://en.wikipedia.org/w/api.php?action=parse&prop=wikitext&format=json&page=Mount_Tambora”
response = urlopen(url)
page_content = str(response.read())
stop special characters from interfering with search
page_content = unescape(page_content)
regex = r”elevation_m\s=\s(\d*)”
result = re.search(regex, page_content)
elevation = result[1]
print(“The elevation of Mt. Tambora is “ + str(elevation) + “.”)
print(result)
Unescape interprits the html into plain english. So instead of <div\> will be decoded to <div>
If you run into issues, especially with ssl certs when trying to get info from the web what should you do?
uninstall and then reinstall python
Save python.org to a file
import urllib.request
url = “https://www.python.org”
req = urllib.request.Request(url)
with urllib.request.urlopen(req) as response:
page_content = response.read()
save in binary mode to preserve encoding defined by web server
with open(“python.html”, mode = “wb”) as f:
f.write(page_content)
What to remember when sending mail via python
You need to consult the email provider’s SMTP settings to get the values for it’s port and SMTP server.
You might also need an SMTP password (google calls this an application password)
Most mail servers use SMTPS which is SSL with SMTP.
Send mail via python
import smtplib, ssl
from_email = “your@email.com”
to_email = “their@email.com”
subject = “Test email from Python”
message = “This is a test email from Python”
message = “Subject : “ + subject + “\n\n” + message
smtp_server = “your.mail.server”
smtp_port = 465
smtp_pass = input(“Enter you SMTP password: “)
create an SSL context
context = ssl.create_default_context()
send the mail
try:
with smtplib.SMTP_SSL(smtp_server, smtp_port, context = context) as smtp_srv:
smtp_srv.login(from_email, smtp_pass)
smtp_srv.sendmail(from_email, to_email, message)
except Exception as e:
print(e)