W0 Flashcards

1
Q

How do you display something?

A

print()

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

What is the code comment?

A

”#”
- Anything to the right of the # will be ignored
- Can use code comments is adding a general description

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

What are the symbols for the different mathematical operations?

A

+ Addition
- Subtraction
* Multiplication
/ Division
** Exponential (to the Power of…)

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

How do you assign a value to a variable and return it?

A
  • First define the variable name and variable (i.e. the variable name IS tree; the variable is 20):

tree = 20

  • You can then return the variable via the variable name:

print(result)

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

What type of Variable Names are invalid?

A
  • Starts with a number (1_data)
  • Has a gap/white space (new data)
  • Has an apostrophe (john’s_salary)
  • Has a hyphen (old-data)
  • Has the $ symbol (price_in_$)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

How can you update the value stored for a variable?

A
  • You can update the code sequentially:
    x = 30
    print(x)

x = 70
print(x)

  • You can use arithmetic operations:
    x = 30
    print(x)
    print(x + 70)

x = x + 70
print(x)

  • You can use a shortcut of +=:
    x = 30
    x += 70
    print(x)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What are the different syntax shortcuts to update the value stored for a variable?

A

For a defined variable x, you can update the value stored with:

+= Adds
-= Subtracts
*= Multiplies
/= Divides
**= Exponents

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

How can you determine the type of data used?

A

You can use the command:

type()

  • By coding print(type(x)), you are able to confirm the variable type
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What are the different data types?

A

int (Integer values)

float (Decimal numbers)

str (Strings/words)

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

How do you convert a float to an integer and vice versa?

A
  • To convert an integer to a float:

float()

EXAMPLE: print(float(10))

  • To convert a float to an integer:

int()

EXAMPLE: print(int(4.3))
- NOTE: This will always round down the decimal, even if the number after the decimal point is greater than 5

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

How do you round a number?

A

Use the command:

round()

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

How do you return text?

A

Using strings, you can use double quotation marks (“ “) or single quotation marks (‘ ‘)

  • Can define variables that are words:

fb_1 = “Facebook”

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

Why would you alternate between single quotation marks and double quotation marks?

A

If you want to have quotation marks/apostrophes contained within a string

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

What does the \ character perform in a string?

A

The \ character has a special function within a string it escapes (cancels) the special function of characters. You need to also include the apostrophe/speech marks after the character: i.e. ' and "

EXAMPLE:

motto = ‘Facebook's old motto was “move fast and break things”.’
print(motto)

RESULT: Facebook’s old motto was “move fast and break things”.

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

What is concatenation?

A

You can link two or more distinct strings using the + operator or the * operator.

EXAMPLE: + operator
print(‘a’ + ‘b’)
print(‘a’ + ‘ ‘ + ‘b’)
print(‘This’ + ‘is’ + ‘a’ + ‘sentence.’)

Output
ab
a b
Thisisasentence.

EXAMPLE: * operator
print(‘a’ * 1)
print(‘a’ * 4)
print(‘a ‘ * 5)

Output
a
aaaa
a a a a a

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

How can you concatenate between integers and floats?

A

We can use the int() or float() command to convert a string of type str to a number of type int or float.

print(int(‘4’) + 1)
print(float(‘3.3’) + 1)

Output
5
4.3

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

What do triple quotation marks allow you to do?

A

Using triple quotation marks also allows us to use both single and double quotation marks without needing to escape them.

EXAMPLE:
motto = ‘'’Facebook’s old motto was ‘move fast and break things’.’’’
print(motto)

Output
Facebook’s old motto was ‘move fast and break things’.

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

How are data points and datasets connected?

A

Each value in a table is a ‘data point’.

A collection of data points makes up a ‘dataset’.

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

How do you create a list?

A

To create a list, we do the following:

  • Separate the data points with a comma

*Surround the sequence with square brackets

EXAMPLE:

row_1 = [‘Facebook’, 0.0, ‘USD’, 2974676, 3.5]
print(row_1)

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

What command can be used to determine the length of a list?

A

len()

EXAMPLE:

list_1 = [1, 6, 0]
print(len(list_1))

list_2 = []
print(len(list_2))

Output
3
0

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

What is the index number of a list?

A

The specific number associated with each element (data point) in a list.

The indexing always starts at 0, so the first element will have the index number 0

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

What is the command to find the index number of a list?

A

variable[x]

where x is the index number.

EXAMPLE. We can retrieve the first element (the string ‘Facebook’) with the index number 0 by running the code print(row_1[0])

row_1 = [‘Facebook’, 0.0, ‘USD’, 2974676, 3.5]

print(row_1[0])

Output
Facebook

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

What are the two different types of indexing?

A
  • Positive indexing: the first element has the index number 0, the second element has the index number 1, and so on.
  • Negative indexing: the last element has the index number -1, the second to last element has the index number -2, and so on.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

What is list slicing?

A

When we select the first n elements (n stands for a number) from a list named a_list, we can use the syntax shortcut a_list[0:n]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How do you list slice?
To retrieve any list slice we want, we do the following: * We identify the first and the last element of the slice. * We identify the index numbers of the first and the last element of the slice. * We retrieve the list slice we want by using the syntax a_list[m:n], where the following are true: - m represents the index number of the first element of the slice - n represents the index number of the last element of the slice plus one (if the last element has the index number 2, then n will be 3, if the last element has the index number 4, then n will be 5, and so on).
26
How can you list slice when selecting the first or last elements?
When we need to select the first or last x elements (x stands for a number), we can use even simpler syntax shortcuts: a_list[:x] when we want to select the first x elements. a_list[-x:] when we want to select the last x elements.
27
How do you derive a list of lists?
A list that contains other lists is called a list of lists. EXAMPLE: row_1 = ['Facebook', 0.0, 'USD', 2974676, 3.5] row_2 = ['Instagram', 0.0, 'USD', 2161558, 4.5] row_3 = ['Clash of Clans', 0.0, 'USD', 2130805, 4.5] row_4 = ['Temple Run', 0.0, 'USD', 1724546, 4.5] row_5 = ['Pandora - Music & Radio', 0.0, 'USD', 1126879, 4.0] data_set = [row_1, row_2, row_3, row_4, row_5] print(data_set) OUTPUT: [['Facebook', 0.0, 'USD', 2974676, 3.5], ['Instagram', 0.0, 'USD', 2161558, 4.5], # Notice the commas ['Clash of Clans', 0.0, 'USD', 2130805, 4.5], ['Temple Run', 0.0, 'USD', 1724546, 4.5], ['Pandora - Music & Radio', 0.0, 'USD', 1126879, 4.0]]
28
How do you retrieve an element from a list of lists?
By chaining the two indices ([0] and [-1]) — the code data_set[0][-1] will retrieve the first row and the last element of that first row.
29
What is the command to open a file?
Open a file using the open() command. EXAMPLE: opened_file = open('AppleStore.csv') print(opened_file) The output is an object. For now, all we have to keep in mind is that the AppleStore.csv file will open once open('AppleStore.csv') has finished running.
30
What is a module and how do you import commands from it?
We import the reader() command from the csv module using the code from csv import reader (a module is a collection of commands and variables) EXAMPLE: opened_file = open('AppleStore.csv') from csv import reader read_file = reader(opened_file) print(read_file)
31
How can we command to return for each element in a list (in a loop)?
EXAMPLE: app_data_set = [row_1, row_2, row_3, row_4, row_5] for each_list in app_data_set: rating = each_list[-1] print(rating) NOTE: Ensure you have indented the code we want to repeat
32
What is the structure of a for loop?
* A for loop always start with for (like in for some_variable in some_list:), we call this technique). Make sure to include a colon (:) * The indented code in the body gets executed the same number of times as elements in the iterable variable. EXAMPLE: a_list = [1, 3, 5] for value in a_list: print(value) print(value - 1) OUTPUT: 1 0 3 2 5 4
33
Can the code outside the loop body interact with the code inside the loop body?
* Initialize a variable a_sum with a value of zero outside the loop body. * We loop (or iterate) over a_list. For every iteration of the loop, we do the following: - Perform an addition (inside the loop body) between the current value of the iteration variable value and the current value stored in a_sum. - Assign the result of the addition back to a_sum (inside the loop body). - Print the value of the a_sum variable (inside the loop body). EXAMPLE: a_list = [1, 3, 5] a_sum = 0 for value in a_list: a_sum = a_sum + value print(a_sum)
34
What is the command to convert data into a list?
list() EXAMPLE: apps_data = list(read_file)
35
Once we have created a list, which command can we use to add values to it?
After creating a list, we can add (or append) values to it using the append() command. append() has a special syntactical usage, following the pattern list_name.append() rather than simply append(). EXAMPLE 1: a_list = [1, 2] a_list.append(3) print(a_list) OUTPUT: [1, 2, 3] EXAMPLE 2: empty_list = [] empty_list.append(12) print(empty_list) OUTPUT: [12]
36
How can you use a command to sum up all the values in a list?
sum() NOTE. Remember that they should all be of the same data type (i.e. floats or integers)
37
How can append a list of an apps ratings if its price is equal to 0.0 and not whenever price doesn't equal 0.0?
ratings = [] for row in apps_data [1:]: rating = float(row[7]) price = float(row[4]) if price == 0.0: ratings.append(rating)
38
What are features of the if statement?
* The if statement starts with if, it continues with price == 0.0, and it ends with :. * We use the == operator to check whether price is equal to 0.0. Don't confuse == with = (= is a variable assignment operator in Python; we use it to assign values to variables — it doesn't tell us anything about equality). * We indent ratings.append(rating) four spaces to the right relative to the if statement.
39
What are Boolean commands?
* We call True and False Boolean values or Booleans. * When we use the == operator to determine if two values are equal, the output we get will always be True or False * Boolean values (True and False) are necessary parts of any if statement. EXAMPLE 1: if 1== 1: print(100) EXAMPLE 2: if True: print('1 - Output') if False: print('2 - Output') if True: print('3 - Output')
40
What are the different comparison operators with Booleans for A and B?
A == B: A is EQUAL TO B A != B: A is NOT EQUAL TO B A > B: A is GREATER THAN B A >= B: A is GREATER THAN or EQUAL TO B A < B: A is LESS THAN B A <= B: A is LESS THAN or EQUAL TO B NOTE. You can use this on integers, floats, strings and lists
41
How do you include multiple if conditions?
Include 'and' as perhaps 'or' - these are the logical operators? EXAMPLE 1: if appl_price == 0 and appl_genre == 'Games': print('This is a free game') EXAMPLE 2: if genre == 'Social Networking' or genre == 'Games': games_social_ratings.append(rating)
42
How do you combine logical operators?
Use brackets EXAMPLE: if (genre == 'Social Networking' or genre == 'Games') and price == 0: free_games_social_ratings.append(rating)
43
How can you use comparison operators with conditional statements?
if rating >= 4.0: apps_4_or_greater.append(rating)
44
How can you use an else clause?
The code within the body of an else clause executes only if the if statement that precedes it resolves to False. This forms a compund statement. EXAMPLE: for app in apps_data: price = app[1] if price = 0.0: app. append (' free') else: app. append ('non-free')
45
How can you effectively add a new column to each row?
By using the append command to the element in the for loop (i.e. end of each row), we create a new column. If you have added a new value to each row, make sure to add a new column to the first row. EXAMPLE: for app in apps_data[1:]: price = float(app[4]) if price == 0.0: app.append('free') else: app.append('non-free') apps_data[0].append('free_or_not') NOTE. The latter command adds a new column to the dataset.
46
What is the purpose of an elif command?
*To stop the computer from doing redundant operations, we can use elif clauses. * The code within the body of an elif clause executes only under the following circumstances: - The preceding if statement (or the other preceding elif clauses) resolves to False; and - The condition specified after the elif keyword evaluates to True. EXAMPLE: for app in apps_data: price = app[1] if price == 0.0: app. append (' free') elif price> 0.0 and price ‹ 20: app.append ('affordable') elif price >= 20 and price ‹ 50: app. append ('expensive') elif price >= 50: app.append (' very expensive') NOTE. You can also use an ELSE statement at the end to exhaust the dataset.
47
How do we build a dictionary?
To create the dictionary above, we do the following: * Map each content rating to its corresponding number by following an index:value pattern. - For instance, to map a rating of '4+' to the number 4,433, we type '4+': 4433 (notice the colon between '4+' and 4433). To map '9+' to 987, we type '9+': 987, and so on. * Type the entire sequence of index:value pairs, and separated each with a comma: '4+': 4433, '9+': 987, '12+': 1155, '17+': 622. * Surround the sequence with curly braces: {'4+': 4433, '9+': 987, '12+': 1155, '17+': 622} EXAMPLE: content_ratings = {'4+': 4433, '9+': 987, '12+': 1155, '17+': 622} print(content_ratings)
48
How can you make a list of lists?
content_rating_numbers = [['4+', '9+', '12+', '17+'], [4433, 987, 1155, 622]] OUTPUT: [['4+', '9+', '12+', '17+'], [4433, 987, 1155, 622]]
49
How can we return indexes from dictionaries?
To retrieve the individual values of the content_ratings dictionary, we can use the new indices. We retrieve individual dictionary values the same way we retrieve individual list elements — we follow a variable_name[index] pattern: EXAMPLE: content_ratings = {'4+': 4433, '9+': 987, '12+': 1155, '17+': 622} print(content_ratings['4+']) print(content_ratings['12+']) Output 4433 1155
50
What is an alternative way to make a dictionary?
* We can create a dictionary and populate it with values by following these steps: * Create an empty dictionary. Add values one by one to that empty dictionary. EXAMPLE. content_ratings = {} content_ratings['4+'] = 4433 content_ratings['9+'] = 987 content_ratings['12+'] = 1155 content_ratings['17+'] = 622 print(content_ratings) OUTPUT: {'4+': 4433, '9+': 987, '12+': 1155, '17+': 622} NOTE: This approach is the same as populating an empty list by using the list_name.append()
51
What are the names of the parts of the dictionary?
The index of a dictionary value is called a key. In '4+': 4433, the dictionary key is '4+', and the dictionary value is 4433. As a whole, '4+': 4433 is a key-value pair.
52
What is important with the uniqueness of dictionaries?
When we populate a dictionary, we also need to make sure each key in that dictionary is unique. If we use an identical key for two or more different values, Python keeps only the first key and the last value and removes the others — this means that we'll lose data.
53
How can we check for membership of a dictionary KEYS?
An expression of the form a_value in a_dictionary always returns a Boolean value: * We get True if a_value exists in a_dictionary as a dictionary key. * We get False if a_value doesn't exist in a_dictionary as a dictionary key. EXAMPLE: content_ratings = {'4+': 4433, '9+': 987, '12+': 1155, '17+': 622} print('10+' in content_ratings) print('12+' in content_ratings) OUTPUT: False True
54
How do you update dictionary values?
content_ratings = {'4+': 4433, '9+': 987, '12+'; 1155, '17+': 622} content_ratings['4+'] = 0 content_ratings['9+'] += 13 content_ratings['12+'] -= 1155 content_ratings['17+'] = '622" OR via loops content_ratings = {'4+': 0, '9+': 0, '12+': 0, '17+': 0} ratings = ['4+', '4+', '4+', '9+', '9+', '12+', '17+'] for c_rating in ratings: if c_rating in content_ratings: content_ratings[c_rating]+= 1 OUTPUT: {'4+': 3, '9+': 2, '12+': 1, '17+': 1}
55
How can you count the number of times each unique content rating occurs in the data set while finding the unique values automatically?
content_ratings = {} for row in apps_data[1:]: c_rating = row[10] if c_rating in content_ratings: content_ratings[c_rating] += 1 else: content_ratings[c_rating] = 1 print(content_ratings) OUTPUT: {'4+': 4433, '12+': 1155, '9+': 987, '17+': 622}
56
What is important to remember with running loops?
Don't include the header row. EXAMPLE: for row in apps_data[1:]:
57
How can you transform frequencies into proportions or percentage?
content_ratings = {'4+': 4433, '9+': 987, '12+': 1155, '17+': 622} total_number_of_apps = 7197 content_ratings['4+'] /= total_number_of_apps content_ratings['9+'] /= total_number_of_apps content_ratings['12+'] /= total_number_of_apps content_ratings['17+'] /= total_number_of_apps
58
How can you build a frequency table?
size_freq = {} for row in apps_data[1:]: size = row[2] if size in size_freq: size_freq[size] +=1 else: size_freq[size] = 1 OUTPUT: 7107 {'389879808': 1, '113954816': 1, '116476928': 1, '65921024': 1, '130242560': 1, '74778624': 1, ...}
59
How do you determine the minimum and the maximum values of a column?
* We can use the min() and the max() commands. * These two commands will find out the minimum and the maximum values for any list of integers or floats.
60
How can you build intervals with frequency?
data_sizes = {'0 - 10 MB': 0, '10 - 50 MB': 0, '50 - 100 MB': 0, '100 - 500 MB': 0, '500 MB +': 0} for row in apps_data[1:]: data_size = float(row[2]) if data_size <= 10000000: data_sizes['0 - 10 MB'] += 1 elif 10000000 < data_size <= 50000000: data_sizes['10 - 50 MB'] += 1 elif 50000000 < data_size <= 100000000: data_sizes['50 - 100 MB'] += 1 elif 100000000 < data_size <= 500000000: data_sizes['100 - 500 MB'] += 1 elif data_size > 500000000: data_sizes['500 MB +'] += 1
61
How can you create a function?
To create a function, we do the following: * Started with the def statement, where we did the following: - Specified the name of the function - Specified the name of the variable that will serve as input - Surrounded the input variable a_number with parentheses - Ended the line of code with a colon (:) * Specified what we want to do with the input (in the code below the def statement) - Then we assigned the result to a variable named squared_number * Ended with the return statement, where we specified what we want returned as the output. EXAMPLE. def square(a_number): squared_number = a_number * a_number return squared_number
62
What is an EXAMPLE of how to extract values from any column?
def extract(x): column = [] for index in apps_data[1:]: columns = index[x] column.append(columns) return column genres = extract(11)
63
What is an EXAMPLE of building a frequency table?
def freq_table(a_list): table = {} for value in a_list: if value in table: table[value] += 1 else: table[value] = 1 return table genres_ft = freq_table(genres)
64
How can you have multiple parameters for a function?
You can use multiple parameters for the functions we create. EXAMPLE. For instance, consider the add() function below, which has two parameters, a and b, and returns their sum. def add(a, b): a_sum = a + b return a_sum print(add(a=9, b=11))
65
What are key word arguments?
* When we use the syntax subtract (a=10, b=7) or subtract (b=7, a=10), we pass in the arguments 10 and 7 using the variable names a and b. * For this reason, we call them named arguments, or more commonly, keyword arguments. EXAMPLE: ratings_ft = freq_table(data_set=apps_data, index=7) genres_ft = freq_table(index=11, data_set=apps_data)
66
What are positional arguments?
We call arguments that we pass by position positional arguments. EXAMPLE: When we use subtract(10, 7) or subtract(7, 10): the first argument will map to the first parameter, and the second argument will map to the second parameter. EXAMPLE: content_ratings_ft = freq_table(apps_data, 10)
67
If you define a function with the same name as an inbuilt function, what happens?
It will overrule inbuilt functions. So using the names of built-in functions to name our functions isn't a good idea because it may lead to abnormal function behaviour
68
How do you remove defined functions overruling inbuilt functions?
del **** EXAMPLE. For the max function, run the code del max to delete the max() function you wrote. This will allow you to use the built-in max() function again.
69
How do make a default argument?
In the function below, for instance, we initiate the constant parameter with a default argument of 10. def add_value(x, constant=10): return x + constant print(add_value(3)) OUTPUT: 13
70
What is the round function?
round(number, ndigits) Return the number rounded to n-digits precision after the decimal point.
71
Can you have multiple return statements in a definition?
def sum_or_difference(a, b, do_sum=True): if do_sum: return a + b else: return a - b print(sum_or_difference (10, 5, do_sum=True)) print(sum_or_difference(10, 5, do_sum=False)) OUTPUT: 15 5 NOTE: You can achieve the same result by removing the 'else' and retaining the indention
72
What is a tuple?
(20, 10). (20, 10) is a tuple, which is a data type that is very similar to a list (examples of data types include integers, strings, lists, dictionaries, etc.). * Just like a list, we usually use a tuple to store multiple values. Creating a tuple is similar to creating a list, except we need to use parentheses instead of brackets. *The main difference between tuples and lists is whether we can modify the existing values or not. In the case of tuples, we can't modify the existing values, while in the case of lists, we can. EXAMPLE: a_list = [1, 'a', 10.5] a_tuple = (1, 'a', 10.5)
73
What is the difference between Immutable and Mutable data types?
Immutable Data Types - (Such as tuples, integers, floats, strings, and booleans) because we can't change their state after we've created them. - The only way we could modify tuples, and immutable data types in general, is by recreating them. Mutable Data Types - (Such as lists and dictionaries), because we can change their state after we've created them.