CCChapter 8 and maybe more Flashcards

1
Q

Use a dataclass to automatically create your __init__ and your instance variables
Give one default argument

A

from dataclasses import dataclass

@dataclass
class Customer:
name: str
city: str
age: int = 33

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

What are things like @dataclass and @property called?

A

decorators

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

Add all arguments to the dataclass decorator and describe their functionality

A

@dataclass(init=True, repr=True, eq=True, order=False, frozen=False)

init - defaults to true and auto creates __init__ method

repr - defaults to True and allows class to represent itself as a string, used to compare object usually. repr() will call this method on the class to obtain the string.

eq - defaults to true and the __eq__ method will compare two object of the same class.

order - defaults to false and does comparisons like equals, except with __lt__ __le__ __gt__ __ge__

frozen - defaults to false, if true it makes everything in class immutable which would allow it to be stored in a set or dictionary

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

Use the repr argument

A

from dataclasses import dataclass

@dataclass
class Customer:
name = str
age = int

c1 = Customer(“Nathan”, 33)
print(repr(c1))

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

Use the eq argument

A

from dataclasses import dataclass

@dataclass
class Customer:
name = str
age = int

c1 = Customer(“Nathan”, 33)
c2 = Customer(“Jeremy”, 28)
print(c1 == c2)

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

Module

A

Group of code that can be classes, variables, or functions all working together, a module works in it’s own namespace separate from the Main Program (global namespace)

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

Namespaces and importing

A

Importing grabs a module and makes it accessible to you. The module exists in it’s own namespace, like the module “locale”.

If we import locale:
import locale we can’t access locale_alias because it exists in the module’s namespace. You access it like this
locale.locale_alias

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

Give the locale module a new name

A

import locale as robert
robert.locale_alias

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

Lets say we want to use the parser code from the email module and that’s it, how would we do that?

A

from email import parser

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

Show all variables, then show all methods, then finally show helpful info for the email module

A

vars(email)
dir(email)
help(email)

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

How would you create a module

A

Save a file that you have made for a class that can actually do something.

Open a new file.
import distance (name of the file minus the .py bit)

dist = distance.Distance(3)
making an object in the new file that denotes the module “distance” then adds the class, followed by the argument Distance(3)
now use it like you would from the module itself.

print(dist.miles)

FILES MUST BE IN THE SAME DIRECTORY

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

What is a package?
Create one. Remember, we have everything we need except one file to make it easier.

A

In the directory with your current project add the files you want as a part of your package into a folder called “calculations”.
Add all your python files to this.
Next, add a file called __init__.py
import everything using this file:
from .distance import *
from .area import *
from .timecalc import *

On your current project:
import calculations
object = calculations.Distance(3)
print(object.km)

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

Create a variable with the string “Hello, World”

Create an if statement that says if World isn’t in the equal to -1 then to do something. (Also, what number would pop up for world?)

inside the if statement replace “World” with “Reader”

A

create a string
a = “Hello, World”

search for world in the string
if a.find(“World”) != -1:

# Replace "World with Reader"
b = a.replace("World", "Reader")

# Display the results
print(a)
print("... was replaced with ...")
print(b)

You could also just do print(a.replace(“World”, “Reader”))

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

Create the variable “title” with comprised of the string “Python Quick Start Guide”

Show it in all uppercase and then all lower case.

A

title = “Python Quick Start Guide”

print(title.upper())

print(title.lower())

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

create a variable and string combination:
tongue_twister = “She sells sea shells by the seashore.”

Show the count of every time an “s” was displayed.

A

print(tongue_twister.count(s))

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

Take each character from a string and put it into a list

Put it back together again

A

fox = quick fox
list = fox.split()
print(list)

list = ““.join(fox)

17
Q

Create a string that contains the following:
123-45-6789
print this as if every “-“ is a space to add them as their own item in a list.
Use “-“ as your delimiter basically

A

id = “123-45-6789
id_s = id.split(“-“)
print(id_s)

you can also make a split calling multiple delimiters:
glossary = “This, and, that”
gl = glossary.split(“, “)
print(gl)

18
Q

Create a variable with the below string:
“delimiter, module, package, class, object”
Put each item individually in a list
Now return them to the way they were.

A

glossary = “delimiter, module, package, class, object”

print (glossary)

glossary_list = glossary.split(“, “)

print(glossary_list)

glossary_list = “, “.join(glossary_list)

print(glossary_list)

19
Q

Create an input variable
Have python return whether it is:
numeric
alphabetic
alphanumeric
Explain what works here

A

Firstly, this only works if there are no spaces.
Secondly Alphanumeric will pop up if it’s either one or the other

value = input(“Please enter a vlaue: “)

if value.isnumeric():
print(“It’s a number!”)

Check if every character is a letter”
if value.isalpha():
print(“It is filled with alphabet characters only!”)

if value.isalnum():
print(“It is alphanumeric!”)

20
Q

What are regular expressions?

A

String of characters and special codes that are designed to match certain patterns in strings.

21
Q

Import regular expressions
create a string “Hello, World!”
Search for “hello” within the string
using regular expressions, remember to add a flag in

A

import re

text = “Hello, World!”

if re.search(“Hello”, text, re.IGNORECASE):
print(“Hello is in the string”)
else:
print(“Hello isn’t in the string”)

You can also use re.I to do the same thing

22
Q

Create the string:
“the quick gray fox jumped over the lazy dog”
Search if gray or grey is used in the sentence with regex.
print the match
print where the word is located in the sentence

A

import re
text = “The quick gray fox jumped over the lazy dog”

match = re.search(“(gray|grey)”, text, re.IGNORECASE)

print(match.group(0))

23
Q

create a variable with “The quick gray fox jumped over the lazy dog”

Search for whether “grey” or “gray” was used.

store the position of the beginning of the word grey in the sentence into a variable
store the position of the end of the word grey in the sentence into a variable

Using the numbered positions. swap the word grey out for gray

A

text = “The quick gray fox jumped over the lazy dog”

match = re.search(“(gray|grey)”, text, re.IGNORECASE)

match_start = match.span()[0]
match_end = match.span()[1]
replace_text = “grey”

new_text = text[:match_start] + replace_text + text[match_end:]
print(“old text: “ + text)
print(“new text: “ + new_text)

[:this] and [this:] tell python:
[:this] < - give me everything up until before this point
[this:] give me everything after and including this point this point

24
Q

Using a regex anchor print if the string starts with “h” or not

A

import re

text = “Hello, World”

if re.search(“^H”, text):
print(“String starts with H”)

25
Q

Using a regex anchor, print if a string ends with and exclamation point

A

import re

text = “Hello, World!”

if re.search(“!$”, text):
print(“String ends with exclamation”)

When we use the \ this means we want to use the literal character rather than a regex symbol.

26
Q

How would regex check if the first or last word in every line of a multiline string is a certain word. (This doesn’t mean they all need to start with the word, just that one of them has it.)

How would you change this slightly to make sure it would only search the beginning or the end of the string?

A

import re

text = “"”This is a multiline string.
It has multiple lines to it.
So, fittingly, it’s called a multiline string.
When you type a string and hit ENTER,
a special character is inserted in the string.
That special character is a backslash followed by n.”””

if re.search(“^It”, text, re.MULTILINE):
print(“yes”)
else:
print(“no”)

re.MULTILINE flag tells to check everyline for this, not just the beginning of the string.

For just beginning of the string
if re.search(“\AIt”, text, re.MULTILINE):

For just the end of the string
if re.search(“It\Z”, text, re.MULTILINE):

27
Q

What’s the faster way of searching for words at the beginning of a string?

Use that and compare it to re.search doing the same thing looking for a character in the middle of a sentence

A

import re

test = “Hello, World!”

if re.match(“e”, test):
print(“e in it”)

if re.search(“e”, test):
print(“e in it also”)

28
Q

Split an string using regex into a list, use space as a delimiter in two different ways

A

import re

test = “The quick brown fox is fast!”

space = re.split(“\s+”, test)
print(space)

spacer = re.split(“\W+”, test)
print(spacer)

\s <- white space
\W <- non word character
+ <- match one or more

29
Q

Create a string
replace spaces with +’s

A

import re

test = “The quick brown fox is fast!”

plus_test = re.sub(“\s+”, “+”, test)
print(plus_test)

remember:
\s < - white space
+ < - one or more

30
Q

Using string formatting, print the string:
“Hello !”
place a name variable inside that you’ve defined earlier

Next create a greeting variable that will let you add information to it via print using string formatting

A

name = “Frank”
print(“Hello {}!”.format(name))

greeting = “Hello, {name}! I hear you’re {age} years old”
print(greeting.format(name = “Nathan”, age = 33))

31
Q

Convert a number to a float using string formatting

You can do this via two variables and then print at the end

A

number = 6.99
message = “Your total is {:.2f}”

print(message.format(number))

: <- This tells the format formatting code is coming
.2 <- I need two decimal places
f <- make my boy here a float

32
Q

Create a multiline string
compress it
compare amount of characters in original to compressed data

Don’t forget UTF-8!

A

UTF-8 has a bit more in it then just english numbers and letters

import zlib

data = “"”This is a multiline string.
We are using this as a test to compare
the before and after affects of compression.
Let this serve as a warning to any woman who dares
disrespect my virginity by attempting to have sex with me.
Away, wench! I will cry ha ha! Away with thee! I must study!!”””

We have to convert from ASCII to UTF-8 in order to compress
compressed = zlib.compress(data.encode())

print(len(data))
print(len(compressed))