Intermediate Python Flashcards

Advanced level python

1
Q

How do you combine multiple .csv files into a single DataFrame?

A

Loop through each CSV file in the directory

Directory where the individual CSV files are saved
csv_directory = ‘/Users/Documents/Udacity/Political_News_2024/political_news’

Initialize an empty list to hold DataFrames
dataframes = []
for filename in os.listdir(csv_directory):
if filename.endswith(‘.csv’): # Check if the file is a CSV
file_path = os.path.join(csv_directory, filename)
df = pd.read_csv(file_path) # Save the CSV file
dataframes.append(df) # Append the DataFrame to the list
# Concatenate all DataFrames in the list
combined_news_df = pd.concat(dataframes, ignore_index=True)
# Get today’s date in YYYY-MM-DD format
today = datetime.today().strftime(‘%Y-%m-%d’)
# Define the path and name for the combined CSV file
combined_filename = os.path.join(csv_directory, f’combined_political_news_data_{today}.csv’)
# Save the combined DataFrame to CSV
combined_news_df.to_csv(combined_filename, index=False)

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

What are the steps to learning python

A

Learn the python language
Learn the standard library
Learn the ecosystem

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

What three questions are asked to verify if data is a collection?

A

Can I know the size, or length, of this data? If so, the data is Sized.
Can I produce elements from this data set, one at a time? If so, the data is Iterable.
Can I check whether an element is in this data set? If so, the data is a Container.

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

What questions should you ask when thinking about structure, performance, and clarity?

A

Is the data ordered (sequential), or unordered?
Is the data associative, mapping between keys and values?
Is the data unique?

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

Define mutability

A

whether an object in Python can be changed after it has been created.

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

Define hashability

A

If all data in a collection is immutable. An object is hashable if it has a fixed hash value for its lifetime and it implements the __hash__() method.

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

What does false mean in Python

A

Something that is False

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

What means nothingness?

A

None

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

Iterable

A

An object that can produce a stream of elements of data.

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

Mapping

A

An unordered collection associating elements of data (keys) to other elements of data (values).

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

Set

A

An unordered collection of unique data elements

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

Sized

A

An object that has a finite size

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

Structured data

A

Information to which we assign meaning through organizaiton

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

What is a bool

A

Either False or True and encodes binary values

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

What are the numeric values for a number?

A

int (integer) or float (real)

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

What is a string

A

An immutable sequence of text characters

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

What represents nothingness

A

None

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

What are the building blocks of data

A

bool
number
string
None

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

How do you escape special characters in string literals

A

\
print(‘doesn't’)

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

What does r”U\escaped” do?

A

It avoids ecaping, creating a raw string so special sequences U\escaped, \n (newline), or \t (tab) are treated as literal text, not as control characters.

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

name common methods for Strings

A
  • greeting.find(‘lo’) # 3 (-1 if not found)
  • greeting.replace(‘llo’, ‘y’) # => “Hey world!”
  • greeting.startswith(‘Hell’) # => True
  • greeting.isalpha() # => False (due to ‘!’)
  • greeting.lower() # => “hello world! “
  • greeting.title() # => “Hello World! “
  • greeting.upper() # => “HELLO WORLD! “
  • greeting.strip(‘dH !’) # => “ello worl”
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Visualize how to convert the following:
str
int
float
bool

A

str(42) # => “42”
int(“42”) # => 42
float(“2.5”) # => 2.5
bool(None)

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

T or F: converting a value to a bool turns it into a boolean

A

F: it gives the value an essence of truthiness

bool(None) # => False
bool(False) # => False
bool(41) # => True
bool(‘abc’) # => True

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

What is a Python Object

A

A Python object can be thought of as a suitcase that has a type and contains data about its value. Everything in Python is an object.

isinstance(4, object) # => True
isinstance(“Hello”, object) # => True

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Visualize how to evaluate a type function
type(1) # => type("Hello") # => type(int) # => type(type(int)) # =>
25
What are the characteristics of a Python Object?
everything in Python is an object every Python object has a type every Python object has an identity
26
Visualize how to evaluate a Python object identity
id(41) # => 4361704848 (for example) An object's "identity" is unique and fixed during an object's lifetime.* Python objects are tagged with their type at runtime and contain a reference to their blob of data
27
What is a variable
a named reference to an object. x = 5
28
What are namespaces?
A namespace (or symbol table) is an associative mapping from (variable) names to objects.
29
How do you access namespaces
locals() globals()
30
What is abstraction?
Distilling a concept to its core ideas so it can apply to multiple scenarios.
31
Name the four keys to thinking in abstraction
Generalization - dstilling a concept to core idea for widespread application Simplication - removing unncessary details Focus on Why - think about the goal Reusability and scalability - desire is to reuse across multiple scenarios
32
What comes after a dot (.)?
an attribute
33
What is a name?
A reference to an object
34
What are Objects?
Bundles of data associated with actions. Basically everything in Python.
35
Visualize a Class Object
class ClassName: def __init__(self,var): self.var = var
36
What are elements?
A single unit of data that is Boolean, and a number or text.
37
What are ways to represent collections
Sets - unordered, unique data like tags for a blog Sequences - ordered, non-unique or unique data like a list of tasks Mappings -associative data like a product name with an id, country and a country code
38
Container
An object that holds elements of data
39
Mutable
A property of a data collection where the top-level collection can be changed.
40
Schema
A representation or outline of a data model
41
Sequence
An ordered collection of data elements
42
What is 5 ** 2
25. ** acts as square
43
What is 7 // 2?
3. //Gives division with a floor.
44
What are f-strings
a string literal prefixed with f or F, allowing for embedding expressions with {} f"{x}"
45
Visualize how to use the modulo operator for string interpolation
>>>name = "Jane" >>>"Hello, %s!" % name >>>'Hello, Jane!'
46
Visualize how to use a tuple with the modulo operator
>>> name = "Jane" >>> age = 25 >>>" Hello, %s! You're %s years old." % (name, age) 'Hello, Jane! You're 25 years old.'
47
Visualize how to use the str.format() method
>>> name = "Jane" >>> age = 25 >>>"Hello, {}! You're {} years old.".format(name, age) "Hello, Jane! You're 25 years old." or >>> "Hello, {1}! You're {0} years old.".format(age, name) "Hello, Jane! You're 25 years old." ## uses indices to specify placements or >>> "Hello, {name}! You're {age} years old.".format(name="Jane", age=25) "Hello, Jane! You're 25 years old." ## improves readibility
48
Visualize how to use dictionaries to provide values for interpolating strings
>>> person = {"name": "Jane", "age": 25} >>> "Hello, {name}! You're {age} years old.".format(**person) "Hello, Jane! You're 25 years old."
49
Visualize how to access strings by index
x = "string" x[0] = "s" x[-1] = "g"
50
visualize slicing string sequences
x = "string" x[0:2] = "st"
51
what is slicing
Special syntax for accessing or updating elements or subsequences of data from a sequence type.
52
What is str?
An immutable sequence of characters.
53
what would print(r"U\nescaped") print?
U\nescaped appending a r to the "" makes it a raw string, and ignores the escape. `
54
visualize data type conversions
float() int() str() bool(False)
55
What are false values
bool(None) bool(0) bool(0.9) bool("")
56
T or F: bool([False]) is False
False. It's true because it contains something in it.
57
Visualize how to remove a value from a list
list.remove(value)
58
visualize how to return number of occurrences of a value from a list
list.count(value)
59
visualize how to return first index of value
list.index(value, [start, [stop]])
60
visualize how to return item at index without splicing. Starts with p.
list.pop([index])
61
visualize how to sort in place
list.sort(key=None, reverse=False) list.reverse()
62
what is a list
a finite, ordered, mutable sequence of elements. letters = ['a', 'b', 'c', 'd']
63
visualize how to check if a str is an object
isinstance("string", object) Return True if the object argument is an instance of the classinfo argument
64
Visualize how to get an objects identity
id(x) xxxxxxxx
65
Visualize how to get the objects type
type(x)
66
what is a tuple?
an immutable sequence of arbitrary data. v = ([1, 2, 3], ['a', 'b', 'c'])
67
translate s[1:5:2] for s = 'Udacity'
go between positions 2 and 4, taking a step size of 2 s[1:5:2] = 'dc'
68
how do you reverse the elements of x? x = 'string'
x[::-1] 'gnirts'
69
how would you modify the list at index 3? letters = ['a', 'b', 'c', 'd']
letters[2] = 3 letters = ['a', 'b', 3, 'd']
70
visualize how to insert a value into a list
list.insert(x, index)
71
T or F: s is a tuple s = ('value')
False. A ',' has to follow 'value' or s becomes a string. s = ('value',)
72
T or F: the below code would fail. x = ([1,2,3], ['a','b','c']) x[0].append(4) print(x)
False. x = ([1,2,3], ['a','b','c']) x[0].append(4) print(x) Output x = ([1,2,3,4], ['a','b','c']) Tuples aren't immutable all the way down. You can modify what's inside the lists.
73
What does packing and unpacking mean?
Any comma-separated values are packed into a tuple: t = 12345, 54321 print(t) # (12345, 54321) type(t) # => tuple Any comma-separated names unpack a tuple of values (which must be of the same size) x, y = t x # => 12345 y # => 54321
74
Visualize variable-length tuple tuple packing/unpacking *start
Collect elements at the start *start, x, y = (1, 2, 3, 4, 5) print(start) # Output: [1, 2, 3] print(x) # Output: 4 print(y) # Output: 5
75
Visualize variable-length tuple packing/unpacking for *end
Collect elements at the end a, b, *end = (1, 2, 3, 4, 5) print(a) # Output: 1 print(b) # Output: 2 print(end) # Output: [3, 4, 5]
76
Visualize variable-length tuple packing/unpacking using ignore
a, _, b, *rest = (1, 2, 3, 4, 5) print(a) # Output: 1 print(b) # Output: 3 print(rest) # Output: [4, 5]
77
Visualize variable-length tuple packing/unpacking using nesting
data = (1, 2, (3, 4, 5)) a, b, (x, *rest) = data print(a) # Output: 1 print(b) # Output: 2 print(x) # Output: 3 print(rest) # Output: [4, 5]
78
Visualize swapping using tuple packing/unpacking
x=5 y=6 x,y = y,x Output: x=6 y=5
79
for sequence = ['red', 'green', 'blue'] Why is the code: for index, value in enumerate(sequence): print(index, value) better than the code: for i in range(len(sequence)): print(i, sequence[i])
enumerate() directly provides both the index (index) and the corresponding value (value) This is a form of tuple packing/unpacking
80
Visualize how to make a string, list, or tuple
str([3, 4, 5]) # => '[3, 4, 5]' list("ABC") # => ["A", "B", "C"] tuple("XYZ") # => ("X", "Y", "Z")
81
Visualize how to use .split
'ham cheese bacon'.split() # => ['ham', 'cheese', 'bacon'] '03-30-2016'.split(sep='-') # => ['03', '30', '2016']
82
Visualize how to use .join
# => "Eric, John, Michael" join creates a string from an iterable (of strings) ', '.join(['Eric', 'John', 'Michael'])
83
What is mapping?
using hashable values to: -Encoding associative information -Capturing plain data with named fields. -Building more complicated data structures.
84
Visualize the ways to create a dictionary
empty = {'one': '1', 'two': 2, 'three' : 3} dict(one = 1, two = 2, three = 3)
85
Visualize ways to modify the dictionary
d = {"one": 1, "two": 2, "three": 3} Access and modify d['one'] = 22
86
Visualize how to use dict.get
temps = {'CA': [101, 115, 108], 'NY': [98, 102]} temps.get('CA') # => [101, 115, 108] temps.get('KY') # => None (not a KeyError!)
87
What are ways to remove elements in dictionarys?
d = {"one": 1, "two": 2, "three": 3} del d["one"] d.pop("three", default) # => 3 d.popitem() # => ("two", 2) d.clear() #removes everything
88
What is the .get()?
This method allows you to access a dictionary and specify a default value a.get('five', 0) #won't have an error if five doesn't exist.
89
Visualize how to loop over the values in a dictionary
for v in x.values(): print(v)
90
Visualize how to use a for loop to pack and unpack an dictionary
for key, value in x.items(): print(key,value)
91
What methods allow you to view keys, values, or items?
d.keys() d.values() d.items()
92
What is a set?
an unordered collection of distinct hashable elements Can check: the size of, element containment, and loop over it
93
Visualize a set
empty_set = set() set_from_list = set([1, 2, 3, 2, 3, 4, 3, 1, 2]) # => {1, 2, 3, 4} if you want to create a set, you have to use set()
94
T or F: Sets can contain duplicates
False. Sets can only have unique values
95
What are some set operations that you can use?
a = set("mississippi") # {'i', 'm', 'p', 's'} a.add('r') a.remove('m') # Raises a KeyError if 'm' is not present. a.discard('x') # Same as `remove`, except will not raise an error. a.pop() # => 's' (or 'i' or 'p') a.clear() len(a) # => 0
96
Visualize how to use mathematical operations on sets
a = set("abracadabra") # {'a', 'b', 'c', 'd', 'r'} b = set("alacazam") # {'a', 'm', 'c', 'l', 'z'} # Set difference a - b # => {'b', 'd', 'r'} # Union a | b # => {'a', 'b', 'c', 'd', 'l', 'm', 'r', 'z'} # Intersection a & b # => {'a', 'c'} # Symmetric Difference a ^ b # => {'b', 'd', 'l', 'm', 'r', 'z'} # Subset a <= b # => False
97
What are the below named variations for the sets: A. difference B. union C. intersection D. symmetric difference
A. set.difference B. set.union C. set.intersection D. set.symmetric_difference E. set.issubset
98
Comprehensions
A convenient shorthand to build lists, sets, or dictionaries ex. for x in range(6): squares.append(x**2) This is the comprehension [x***2 for x in range(6)] print(squares) [0,1,4,9,16,25,36)
99
Visualize list comprehensions
[a transformation for an element in a collection (that meets criteria)] [ x ** 2 for x in range(10) if x % 2 == 0] # Lowercased versions of words in a sentence. [word.lower() for word in sentence] # Words in a sentence of more than 8 letters long. [word for word in sentence if len(word) > 8]
100
What is the dictionary comprehension syntax
{key_func(vars): value_func(vars) for vars in iterable}
101
Visualize a dictionary comprehension
{student: grades for student, grades in gradebook.items() if sum(grades) / len(grades) > 90 builds a dictionary of student grades for students whose average grade is at least 90.
102
requests.get()
pulls in the information from the website. import requests results = requests.get("http://www.example.com") results.text #obtains the text object passed to BeautifulSoup
103
BeautifulSoup
results = requests.get("http://www.example.com") results.text #prints to a screen import bs4 soup = bs4.BeautifulSoup(results.text,"lxml")
104
Visualize how to select a title from a soup object
title = soup.select('title') title.getText() # returns back the text object
105
What module do you use to import your password?
import getpass email = getpass.getpass("Email: ") password = getpass.getpass("Password: ") smtp_object.login(email,password)
106
What library do you use for email import?
import imaplib