Python Fundamentals Flashcards

1
Q

GENERAL

A

GENERAL

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

How does logical operators work?

A

There are two main logical operators ‘and’ & ‘or’ which operate
on boolean values. The ‘and’ operator needs both values to be
True to return a True result. The ‘or’ operator only needs
one value to be True to return a True result.

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

What is boolean logic?

A

Boolean logic is the name given to comparison operations whose
result is True or False.
==
!=
>
<
>=
<=
are all comparison operations that result in True or False

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

Is it possible to assign a maximum or minimum value to a variable in python.

A

Yes, python has the concept of positive and negative infinity which is a float.

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

What is a bitwise operation?

A

A bitwise operation is a logical operation performed on individual bits where 0 represents false and 1 represents true.

A bitwise ‘&’ operation tends to drop bits

A bitwise ‘|’ operation tends to add the bit together

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

What is binary? how does it work?

A

The binary number system is the base two representation of numbers using only two symbols 0 and 1.
When writing a number in binary, the prefix 0b is used to indicate that what follows is a binary number.

0b0101 is 5

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

What is floor division and what is the result of performing this operation?

A

floor division is just like regular division except the result is always an integer i.e. the decimal portion of the result is dropped NOT rounded.

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

What are the main types in python?

A

string, integer, float, boolean and None

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

How do we assign a multi-line string?

A

By using “”” (triple quotes)

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

Is there an increment and decrement operator in python?

A

Yes it is the ‘+= ‘ and ‘-=’.
‘++’ and ‘- -‘ do not exist in python like many C-style programming languages.

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

Is type hinting enforced by python?

A

The python interepter does not enforce types. Python is dynamically typed therefore type hinting only allows the user of the code to see the expected types.

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

Is python statically or dynamically typed?
What does this mean?

A

python is dynamically typed, which means you can assign any type to a variable, more IMPORTANT this also means that you can change the type of the variable after its assignment.
This in NOT recommended however.

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

DATE
<===>

A

DATE
<===>

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

syntax for creating a date object?

A

Use single integer inputs when creating the date object.

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

CONTROL FLOW
<===========>

A

CONTROL FLOW
<===========>

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

Short hand syntax for if-statement?

A

(do something) if (condition) else (do something else)

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

for-else….?

A

The else statement can be used with a loop as folows:

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

FUNCTONS
<===========>

A

FUNCTONS
<===========>

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

what is a function and what keyword is used to create one?

A

A function is a reusable block of code, that returns a result or performs an action. The ‘def’ keyword is used to declair a function.

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

Function parameters vs arguments

A

The function parameters are the inputs to the function at its definition, the arguments on the other hand are the inputs used when calling the function.

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

Can you call a function before it ‘s declaration?

A

You cannot call a function before you declare it. A common convention in many languages is to use a single main function which is then called at the end as the entry point for the program, this ensures all subsequent functions are called in the correct order.

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

What value is returned by a function without a return keyword or the return keyword without a value?

A

None

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

Can a Python function return multiple values?

A

Yes. A return statement followed by a list of comma seperated values will return each value. When the function is called an equal number of variables must be used in the order they were returned.

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

What are the three types of arguments we can pass to a function?

A

Positional arguments, Keyword arguments, and Default arguments

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

What are positional arguments?

A

A positional arguments is an arguments that can be called by their position in the function definition.

positional call to function:

calculate_taxi_price(100, 10, 5)

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

What are Keyword arguments?

A

Arguments that can be called by their name.

keyword argument call to function:

calculate_taxi_price(rate=0.5, discount=10, miles_to_travel=100)

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

What are default arguments?

A

Arguments that are given default values in the function definition.

def calculate_taxi_price(miles_to_travel, rate, discount = 10):
  print(miles_to_travel * rate - discount )

When using a default argument, we can either choose to call the function without providing a value for a discount (and thus our function will use the default value assigned) or overwrite the default argument by providing our own.

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

How would you create a function that accepts unlimited arguments?

A

Note that to assing a value to the age argument you must use key-word assignment syntax (age=10) or position age as the first argument in the sequence.

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

Accept unlimited keyword arguments?

A

Note kwargs is just a convention and not a keyword.

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

Unlimited args and kwargs

A

args:tuple kwargs:dict

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

Positional args only?

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

Kwargs only?

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

Combination args?

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

LOOPS
<======>

A

LOOPS
<======>

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

What is a loop? how do you construct a for loop?

A

A loop allows us to perform an action multiple times without explicitly writing it each time.

Note: In the sample code 0-9 will be printed.

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

How does the range() function work?

A

The range function takes a single input and returns a range object. The range object can be converted into a list by using the list() function.

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

How does the range() function work in a for loop?

A

The range function when used with a for loop generally uses two parameters a start value and end value which is exclusive. An optional third argument can be used the ‘step’ which determines how much to add to ‘i’ in each iteration of the loop. using a negative value for the step input will cause the iteration to go backwards.

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

What is a While-loop?
What is the syntax?

A

A while loop performs a given set of instructions as long as a given condition is true.

while True:
  do something

Note: The condition must eventully evaluate to false to exit the loop.

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

How does the ‘break’ and ‘continue’ keywords affect the processing of a loop?

A

When the python interpreter hits the ‘break’ statement it will exit the loop.
In the case of the ‘continue’ keyword the interpreter will skip to the next iteration cycle.

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

LIST
<====>

A

LIST
<====>

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

What is a list and how do you create one?

A

A list is a simple data structure that can store items of any data type. Lists also know as an array stores and references items by index. The index start at zero and indicates the items position in the list:

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

How do you find the number of items in a list?

A

Pass the list as an argument to the ‘len()’ function

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

Can items in a list at a specific index be mutated?

A

Yes. simply assign the new value directly to the desired index. Note that this will replace any value currently at that index.

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

What does the ‘append()’ method do when used with a list?

A

The append method adds the given argument to the end of the list.

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

What does the ‘.pop()’ method do when used with a list?

A

The pop method removes the last item in the list and returns it. It can also take an optional argument which is the index of the element you wish to remove.
my_list.pop(2)

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

How does the .insert method work when used on a list?

A

The ‘.insert’ method is called on the list, it expects a minimum of two inputs the index for insertion and the element to be inserted.

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

When accessing a list

alternative to the ‘indexed for-loop’?
when should you use it?

A

If you do not need to update the item(s) in a list i.e. you only need to access the item and not its index you can use the ‘for-in’ syntax

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

Using slice syntax “return a slice of the list from index 1, up to but not including 5, skipping every 2nd value.

A

Note that slicing returns a new list.

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

How do we concatenate lists together?

A

Simply use the ‘+’ operator.

you can also use the += operator or call the extend() method on a list.

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

How to check for an item in a list without using a ‘if-statement’?

A

By using the ‘in’ keyword. This will return a Boolean value.

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

How do we delete specific items from a list?

A

Use the ‘del’ keyword followed by the name of the list square brackets containing the index or slices you wish to delete.
The ‘.pop()’ method with a index as an argument can also be used.

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

How to remove an item from a list by name not index?

A

Use the remove() method with the item as the argument.

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

How does the ‘.count()’ method work?

A

The ‘.count()’ method will count the number of times an element appears in a list.

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

How does the ‘.sort()’ method work?

A

The ‘.sort()’ method will sort a list alphabetically or numerically.
Calling the method on a list with no inputs sorts the list in ascending order.
my_list.sort()

To sort in descending order pass the following argument to the method.
my_list.sort(reverse=true)

Note that the ‘.sort()’ method modifies the original list and does not return any value.

55
Q

What is the difference between the ‘.sort()’ method and ‘sorted()’ function?

A

The main difference is that the sorted() function does not modify the original list like the .sort() method does. Therefore using the sorted() function will return a value that can be stored in a variable for use.

names = [“Xander”, “Buffy”, “Angel”, “Willow”, “Giles”]
sorted_names = sorted(names)
print(sorted_names)

56
Q

How do we easily access the last element in a list

A

use negative indexing
my_list[-1]

57
Q

How do we append multiple items to a list?

A

use ‘+’ to concatenate two lists together: Note that the original list was not modified, only lists can be concatenated this way.

58
Q

What is a list comprehension?

A

A list comprehension is a concise way to create lists in Python. It provides a compact syntax for generating a new list by iterating over an existing iterable (such as a list, tuple, set, or even a string), applying an expression to each element, and optionally including only certain elements based on a condition.

59
Q

Basic list comprehension syntax

A
output: [2, -2, 158, 66, -90]
60
Q

list comprehension with condition and expression syntax

A

The syntax for the list comprehension changes based on conditional statement and it’s complexity.

61
Q

STRING OPERATIONS
<================>

A

STRING OPERATIONS
<================>

62
Q

How does the ‘+’ operator work when used with strings?

A

The ‘+’ operator will concatenate two or more strings into a single string.

63
Q

How does the replace() method work?

A

this method takes two arguments, it then replaces all instances of the first argument with the second argument. Note this is a substring method.

64
Q

How does the find() method work?

A

This method takes a string as an argument it then searches the string it was called on and returns the first index value where that substring is located.

65
Q

How does the .format() method work?

A

This method can be used to interpolate variables into a string. Use a ‘f-string’ instead!

66
Q

How does the basic split() method with no argumets work?

A

The split() method returns a list of substrings that has been split by a delimiter. If no argument is passed to the method the default delimiter is the “ “ space character.

67
Q

How does the split method work with a delimiter as an argument?

A

Note that the delimiter must be passed as a string. The delimiter is not included in the list of substrings, the method returns a empty string if the string ends with the delimiter.

print(greatest_guitarist.split(‘a’))
output: [’s’, ‘nt’, ‘n’, ‘’”]

Note you can also split based on escape characters such as \n “newline” and \t “horizontal tab”

68
Q

How does the join() method work?

A

The join() method is the opposite of the split() method. It uses a delimiter to join a list of strings.

‘delimiter’.join(list_you_want_to_join)

69
Q

How do we create a csv from a list?

A

CSV stands for “Comma-Separated Values.” It is a simple and widely used file format for storing tabular data, such as spreadsheets or databases.

call the join() method on a “ ,” with a list of strings as the argument.

”,”.join(my_list_of_strings)

70
Q

How does the strip() method work?

A

The strip() method with no arguments when called on a string removes white space from the start and end of the string. The method can also be called with a specific character which will be stripped from the start and end of the string.

71
Q

Strings are immutable, what does this mean?

A

This means a string once created cannot be changed. Operations performed on strings such as slicing and concatenation create a new string.

72
Q

What are the three main string methods that can change the case of a string?

A

‘.lower()’
‘.upper()’
‘.title()’
remember that strings are immutable so the result is a new string. The original string does not change.

73
Q

TUPLES
<======>

A

TUPLES
<======>

74
Q

What is a tuple?

A

A tuple is a data structure similar to a list but whos data is immutable.
To create a tuple use the rounded brackets.
To create a single item tuple you must use a trailing comma:
my_tuple =(4,)
You can also unpack a tuple by using multiple variables
name, age, occupation = (“murphy”, 39, “Data Engineer”)

75
Q

How is the ‘zip()’ function used?

A

The ‘zip()’ function is used to combine two or more iterables (such as lists, tuples, or strings) into a list of tuples paired based on their position.
Note that the zip() function will create an iterator you will need a loop to access the items.

76
Q

MODULES
<========>

A

MODULES
<========>

77
Q

What is a python module?

A

A module is a collection of python declarations intended to be used as a tool. The basic syntax is.

from module_name import object_name

> from datetime import datetime

You can also select the whole module for use:
import random

> random.choice(my_list)

78
Q

Explain module namespacing

A

A namespace isolates the function, classes and variables defined in the module from the code in the file doing the callng.
The name of the module is the name given to the namespace by default. This can be changed however using aliasing.

import module_name as name_you_pick_for_the_module

79
Q

if __name__ == ‘__main__’ ?

A

‘__main__’ refers to the current module being executed. so the calls will not be executed unless it was called locally.

80
Q

Virtual Environments
<================>

A

Virtual Environments
<================>

81
Q

Python virtual Environments

A

Python virtual environments allows you to manage the dependencies for a project in separate environments. Packages are installed at the project level not globally. pipenv is one package used to create and manage these environments.

82
Q

How do we create a virtual environment with pipenv?

A

Make sure the pipenv module is installed. navigate to the root of the project directory and execute the command:
$ pipenv –three
this will initialize the virtual enviroment.
Note a ‘pipfile’ will be created in the directory that contains all the info about the virtual environment and the project dependencies.

83
Q

How do we install packages with pipenv?

A

Make sure your in the desired project directory, use the command:
$ pipenv install package_name

to specify a version of a package use:
$ pipenv install package_name ==2.18.1

Note that using the command:
$ pipenv shell
will allow you use the shell within that virtual environment with all it’s specific dependencies.

84
Q

DICTIONARY
<===========>

A

DICTIONARY
<===========>

85
Q

What is a dictionary?

A

A dictionary is a data structure that is used to stores a collection of items using key, value pairs. Unlike lists which are indexed by position, dictionaries are indexed by keys. Keys must be unique, must be ‘hashable’ type so therefore a list or dictionary cannot be used as a key, hashable values are values that will not change such as numbers and strings.

86
Q

How do we access the values in a dictionary?

A

by using the key in square brackets similar to accessing the index of a list.

87
Q

What is the syntax for adding key/value pairs to an existing dictionary?

A

using the square bracket syntax use the assignment operator to give that key a value.

88
Q

What happens in a dictionary when value is assigned to a key that already exists?

A

The value is overwritten. Each key in a dictionary must be unique.

89
Q

How can we check if a key is present in a dictionary?

A

Simply use the ‘in’ keyword, this will return a Boolean value.

90
Q

What is the syntax for iterating over a dictionary?

A

Use a for-in loop. Note that the value held in the loop variable is a ‘key’.

91
Q

What happens when you try to access a key that does not exist?

A

a ‘keyError’ is thrown

92
Q

How does the update() method work?

A

The update() method allows us to add multiple key value pairs to a dictionary at the same time.

93
Q

How do we delete a key from a dictionary?

A

Use the ‘del’ keyword along with the square bracket syntax and the key you wish to delete.

94
Q

How does the .get() method work with a dictionary?

A

The .get() method will return the value if it exists, otherwise it will return none, or the value used as the optional second argument for the method.

You can also use my_dict.setdefault(‘xx’, ‘key does not exist’) method to get similar behaviour as the .get method.

95
Q

How to remove an item from a dictionary with the .pop() method?

A

Note that using the .pop() method on a dictionary requires at least one argument, i.e. the key to be removed, an optional second argument can be used which will be the value to return if the key does not exist in the dictionary. Remeber that the .pop() method removes the item but also returns the value for use.
EXAMPLE:

raffle = {
223842: “Teddy Bear”,
872921: “Concert Tickets”,
320291: “Gift Basket”,
412123: “Necklace”,
298787: “Pasta Maker”
}

96
Q

What is the result of passing a dictionary as an argument to the list function:
list(my_dict) ?

A

This will return a list of all the keys in the dictionary.
EXAMPLE
test_scores = {
“Grace”: [80, 72, 90],
“Jeffrey”: [88, 68, 81],
“Sylvia”: [80, 82, 84],
“Pedro”: [98, 96, 95],
“Martin”: [78, 80, 78],
“Dina”: [64, 60, 75]
}

97
Q

How does the .keys() method work when called on a dictionary?

A

The .keys() method returns a dict_keys object that contains all the keys in the dictionary, the dict_keys object is a view only object items cannot be removed or added however, It can be iterated.

98
Q

How to get all the values in a dictionary?

A

Use the .values() method. It will return a dict_values object that can be iterated.

99
Q

Using a for-loop and the .items() method, how do we get all the keys and values from a dictionary?

A

Using the .items() method returns a dict_list object which is a tuple in a (key, value) format which can be used in a loop as follows:

100
Q

Syntax for creating a dict comprehension?

A
101
Q

Files
<==>

A

Files
<==>

102
Q

What is the syntax for opening a file?

A
with open('welcome.txt') as text_file:
    text_data = text_file.read()
    print(text_data)

Note that read() returns the file as one single string.
Also text_file is a file object that we then use to perform various actions.

103
Q

How does the readlines() function work?

A

It reads the text file line by line.

with open('how_many_lines.txt') as lines_doc:
  print(lines_doc)
  for line in lines_doc.readlines():
   print(line)

Note that readlines() returns a list with each line in the file.

104
Q

How would we access only a single line in a file?

A

By calling the readline() method on the
file object.

with open('millay_sonnet.txt') as sonnet_doc:
  first_line = sonnet_doc.readline()
  second_line = sonnet_doc.readline()
  print(second_line)
105
Q

What is the syntax for writing a file?

A

To write a file we use the open() function with a second argument ‘w’ for write mode.If the file already exists it will be over-written.

Note that the open() function uses ‘r’ by default as the second argument, so it is optional when reading a file.

106
Q

Appending to an existing file?

A

If you do not want to overwrite the file you will need to use append mode.

107
Q

Removing a file

A
import os
if os.path.exists('my_file.txt'):
    os.remove('my_file.txt')

check if the file exists before carrying out an operation on the file.

108
Q

How to remove a folder and all the files in it?

A
import os

folder_name = 'sample_folder/'
for file in os.listdir(folder_name):
    if os.path.exists(folder_name + file):
		    os.remove(folder_name + file)
os.rmdir('sample_folder')
109
Q

what’s with ‘with’?

A

The ‘with’ keyword invokes a context manager for the file we’re calling open() on. The context manager takes care of opening the file when we call open() and closing the file when we leave the indent block. We can use the older method of opening and closing a file however this is not recommended since it will cause performance issues if it is not done correctly.

110
Q

working with csv

A

To work with a csv file the best approach is to use the csv module.

111
Q

CSVs with different delimiters?

A

Although csv means comma seperated values other delimeters are also valid.

112
Q

Writing a csv file programmatically?

A

note that the order of the fileds does not need to match the source data.

113
Q

Reading a JSON file?

A

The json module is used to process json files

note that the result of passing the file object to json.load() is a regular python dictionary and therefore we are able to perform regular dict. operations on the result.

114
Q

Writing a JSON file?

A

note turn_to_json is the data we wish to convert to json which will be written in the file outout.json

115
Q

What are the different modes available to open a file.

A

‘r’ - read the default mode
‘w’ - write mode will overwrite if the file already exist
‘a’ - append mode file alteady exist
‘a+’ - append, read and write mode.
‘x’ - make sure the file does not already exist.

116
Q

What is a glob?

A

The ‘glob’ module is a built-in module used to find all the pathnames matching a spefic pattern according to the rules used by the Unix shell.

Note that the return type is a list.

117
Q

What is pickling?

A

Pickling is the process used by python to serialize and deserialize objects. The pickle module is used to achieve this.

Note that pickling is not secure and should only be used with trusted sources!

118
Q

Serializing objects with the pickle module?

A
119
Q

Deserializing objects with the pickle module?

A
120
Q

Classes
<====>

A

Classes
<====>

121
Q

What is a class?

A

A class is a template for a data type. It describes what kind of information the class will hold and how to interact with the data.
We use the ‘class’ keyword to define a class.

122
Q

Instantiation?

A

For a class to be useful we must create an instance of it.
myinstance = MyClass()

A class instance is also called an object.

123
Q

Class variable?

A

A class variable or attribute allows every instance of the class to have access to the same varible.

124
Q

Methods?

A

A method is a function defined as part of a class. The first argument in a method is always the object calling the method.By convention the is usually called ‘self’.

125
Q

Constructor?

A

There are several special methods that can be defined in classes, they are sometimes referred to as magic or dunnder methods. You can identify them by the double underscore.
A constructor is a special method used to ‘set up an object when it is instantiated.

_ init() _

126
Q

What is a instance variable?

A

Even though a class is the blueprint for an object. When an object is created it can maintain seperate data from another object created from the same class, this in essence is the instance variable, the opposite of a class variable.

127
Q

Attribute function?

A

The attribute function can be used to check if an item has a certain attribute.

128
Q

dir()

A

Passing any object to the dir() method will return all it’s attributes and methods.

dir(my_function)

129
Q

__repr__(self)

A

The __repr__() dunder method when defined in a class will tell python what the string representation of the class should be when we print out an object of that class. The method only takes self as an argument and has to return a string. If __repr__() is not used only the class name and memory address of the object will be printed.

130
Q

What is an enumeration?

A

An enum is a custom defined type that allows multiple constants to be assigned simultaneously.

131
Q

ERROR HANDLING
<==============>

A

ERROR HANDLING
<==============>

132
Q

Syntax for handling errors?

A
133
Q

Raising exceptions?

A