Chapter 11 and more Flashcards

1
Q

What’s the only thing that will spit out a float from two intergers despite there being no remainder

A

Division

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

How do you perform an exponent equation (n to the 3rd power)

A

3 ** 3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

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

A

integers - :n

floating point numbers :f

To use comma separators :,

Percentage format :%

Exponent(scientific) notion :e

Exponent (scientific) notion with capital E :E

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Find the square root of a number using the math import.
Remember to use formatting

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

round numbers to the nearest whole number

A

a = 4.2

print(round(a))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

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?

A

from decimal import decimal

a = decimal(“2.3”)
b = decimal(“1.9”)
c = decimal(“8.4”)

result = a + b + c

print(str(result))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Python doesn’t have a dedicated function or module for percentages, what should you do?

A

multiply by 100 and add a percent sign at the end

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is mean, median, mode, and standard deviation?

A

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?

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Calculate mean, median, mode, and standard deviation

print these out as floats using formatting

A

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))

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Get the current date and time

A

import datetime

now = datetime.datetime.now()

print(now)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

Print the date and the month

aside from this, what other options do you have?

A

import datetime

now = datetime.datetime.now()

print(now.year)
print(now.month)

day, hour, minute, second, microsecond

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

Let’s say we want to format datetime in different ways user our “now” variable. How would we do this?

A

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

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

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?

A

import datetime

now = datetime.datetime.now()

delta = datetime.timedelta(hours, minutes = 49)

previous_time = now - delta

print(now)
print(previous_time)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Show how many days until your birthday, tee-hee

A

import timedate

now = timedate.timedate.now()

birthday = timedate.timedate(2024, 7, 16, 0, 0)

print(birthday - now)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

Remember to do coffee game for chapters 11, 12, 13 when you’re ready

A

ok

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Create a file, and then read it

A

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)

17
Q

How would you set it to where you only read from a files first 16 characters

A

with open(“fox.txt”, mode = “r”, encoding = “utf-8”) as f:
read_data = f.read(16)

18
Q

If we wanted to do something every 32 bits of a file, how would we do that?

A

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

19
Q

Read the file line by line and then have it do something to each line

A

with open(“fox.txt”, mode = “r”) as f:
while (l := f.readline()):
do something

20
Q

Read the file line by line inside of a list

A

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)

21
Q

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?

A

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

22
Q

Why use pickle?

A

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

23
Q

Make a list, serialize it with pickle and then read it from pickle

A

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)

24
Q

Get the data from python.org and put it in a variable to later search through or gather info from

A

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.

25
Q

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

A

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>

26
Q

If you run into issues, especially with ssl certs when trying to get info from the web what should you do?

A

uninstall and then reinstall python

27
Q

Save python.org to a file

A

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)

28
Q

What to remember when sending mail via python

A

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.

29
Q

Send mail via python

A

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)

30
Q
A