Python Part Flashcards
What does a condition evaluate to?
Boolean. True or False
What does a break statement do?
Immediately exits whatever loop it is in, and skips the remaining expressions in the code block.
In a for loop, there is an unbounded number of iterations that you don’t know. True or false?
False. You know the number of iterations in a for loop. In a while loop there is an unbounded number of iterations
Which of the following are mutable:
a. Strings
b. Lists
c. Tuples
b. lists
What can you use to slice a string?
string[start:stop:step]
What is a docstring?
A docstring is a string literal specified in source code that is used, like a comment, to document a specific segment of code; so, basically just an explanation of what the outputs should be and what to expect from a function, just to make your code easier to read and understand in case you wanna use it somewhere else
You can access the docstring with help(functionname)
Inside a function, you can access a variable defined outside. True or false?
True
Inside a function, you can modify a variable defined outside (without global variables). True or false?
False
What is a higher order function?
A higher-order function is a function that does at least one of the following:
takes one or more functions as arguments
returns a function as its result
Define the scope of a variable.
The scope is mapping of names to objects
I don’t know why I put this in
A return statement ends the execution of the function call and returns the result. True or false?
True
What does “lists are mutable” mean?
It means that list elements can be changed.
L.append(5). What does the dot do? (L is a list)
Not necessary append, but what does the dot between L and append mean
Lists are Python objects, everything in Python is an object. Objects have data. Objects have methods and functions. One can access this information by object_name.do_something ().
To combine lists together you can use the + operator. True or false?
True. L1 = [1,2,3] and L2 = [4,5,6]. L1+L2 = [1,2,3,4,5,6]
You can also use L1.extend(L2)
What does the method .pop on a list do?
It removes the element at the end of the list and returns the removed element.
When you use L.remove(element), what happens? What if you have the same element two times? What if the element is not in the list?
It looks for the element and removes it. If the element occurs multiple times, it only removes the first occurrence. If the element is not in the list, it gives an error.
What can you use to delete an element at a specific index in a list?
del(L[index])
Assume s is a string. What do you use to convert it to a list containing every character from s?
list(s)
What does s.split(“,”) do? s is a string
It is splitting a string on a character parameter. It splits on spaces if called without a parameter.
Think of a list. What is the difference between sort() and sorted()
L = [1,4,3,1]
sorted(L) - returns the sorted list, does not mutate L
L.sort() - mutates L = [1,2,3,4]
L.reverse() - mutates L = [4,3,2,1]
What do you use to get the absolute value of something?
abs()
Tuples are immutable. True or false?
True.
What is a tuple?
An ordered sequence of elements, in which you can mix the element types:
(2, “plant”, 3)
When you set an alias to a list (i.e. you have a list called hot and you have some elements in it, and then you write warm = hot) and you append one element to one of the lists, does it append to the other one as well?
Yes. append() has a side effect, both lists warm and hot have the same object in memory.
You can solve this issue by cloning a list as follows:
warm = hot[:]
which means that you take all the elements from the hot list and you put them in warm, these two lists will have different objects in memory
The same thing happens with nested list!!!
What is recursion?
A programming technique where a function calls itself.
What is the first step in the process of writing a recursion?
- You must have 1 or more base cases that are easy to solve
- You must solve the same problem on some other input with the goal of simplifying the larger problem input
(sorry i put this question in, i dont know what i was thinking)
What does a dictionary store?
It stores pairs of data. it has keys and values
What methods can you use on dictionaries to iterate through the keys and values?
.keys() separately
.values() separately
.items() together
A dictionary automatically stores keys in order. True or false?
False
Values and keys can be duplicates in a dictionary. True or false?
False. Only values can be duplicates. Keys are always unique.
A list is indexed by a range of numbers, while dictionaries are indexed by a set of unique keys. True or false?
True
The order matters in the dictionary, but does not matter in a list. True or false?
False, the order does not matter in a dictionary because you have the unique keys to use as a lookup table, while for lists, the order matters
What is the difference between classes and objects?
Classes and objects both have attributes and methods, but the difference is that a class is an abstract template, while an object is a concrete representation of a class.
What is the difference between a method and an attribute?
A method is an attribute, but not all attributes are methods. For example, if we have the class
class MyClass(object):
class_name = 'My Class'
def my_method(self): print('Hello World!')
This class has two attributes, class_name and my_method. But only my_method is a method. Methods are functions that belong to your object. There are additional hidden attributes present on all classes.
What does every object have? (3 characteristics)
- A type
- An internal data representation (primitive or composite)
- A set of procedures for interaction with the object
What is the difference between primitive data types and composite data types?
Primitive data types are byte, short, int, bool, long, float, double, char…
Composite data types are the data types that can be constructed using the primitive data types and other composite types. Examples include lists, arrays, dictionaries…
What are objects?
Objects are data abstractions that capture:
- an internal representation - through data attributes
- an interface for interacting with the objects - through methods
What are some advantages of OOP (object-oriented programming)?
One can bundle data into packages together with procedures that work on them through well-defined interfaces
“Divide-and-conquer” development = implement and test behavior of each class separately; increases modularity and reduces complexity
Classes make it easy to reuse code or for subclasses to inherit some behavior
What are attributes of a class?
Attributes are data and procedures that belong to the class.
Data attributes - think of data as other objects that make up the class (e.g., a coordinate is made up of two numbers)
Methods (procedural attributes) - think of methods as functions that only work with this class
What is __init__?
A special method to initialize some data attributes. It allows us to kickstart the object with some specific attributes
Getter and setter method. Click
No idea. write more when you arrive here
When do the following errors appear?
a. IndexError
b. TypeError
c. NameError
d. SyntaxError
a. IndexError appears when trying to access beyond list limits
b. TypeError appears when trying to convert to an inappropriate type, or mixing types without coercion
c. NameError appears when referencing a non-existing variable
d. SyntaxError appears when Python can’t parse the program because of some syntax mistake in the code
How does try & except handling work?
Exceptions raised by any statement in the body of “try” are handled by the “except” statement and the execution continues with the body of the “except” statement.
How does “raise” exception handing work?
The program can raise an exception when it is unable to produce a result consistent with the function’s specifications
How do assertions work in Python?
When you want to be sure that the assumptions on the state of computations are as expected, use an “assert” statement to raise an AssertionError exception if assumptions are not met.
This is a good practice of defensive programming.
e.g., assert len(grades) != 0, "not good"
What is the goal of assertions?
To spot bugs as soon as they are introduced and make clear where they happened.
NumPy arrays comprise elements of a single data type. True or false?
True
What is an array?
An array is a data structure consisting of a collection of elements, each identified by at least one array or index key. An array is stored such that the position of each element can be computed from its index tuple.
What do these different methods do?
a. np.arrange(10)
b. np.zeros((2,2))
c. np.ones((2,2))
d. np.empty((1,3)
e. np.eye(3)
f. np.diag([1,2,3,4])
g. np.linspace(0, 1, 5)
They create different arrays, other than explicitly stating a list of values (np.array([1,2,3]))
If unsure about what one does, Google it, or check Lecture 5.
Remember that you have to make a copy of a list to be able to apply some methods on one of them without affecting the other one? Good. Do you know if that is the case with arrays as well?
Yes, the arrays work the same way. Simple assignments do not make copies of arrays.
When you have two arrays, a & b, and you compute a + b, the arrays are appended to each other, just like lists. True or false?
False, unlike lists c = a + b will compute the sum of the corresponding entries in the arrays. This is an example of a universal function (or ufunc) of NumPy.
If we want to transfer a numpy array into another dimension, we can refer to their axis.
In an array like the following:
0 1 2 3 4
5 6 7 8 9
10 11 12 13 14
What does the following code return?
a. array.sum(axis = 0)
b. array.sum(axis = 1)
axis = 1 reduces into the first dimension; which means that the program does something with the rows
array.sum(axis = 1) returns
[10 , 35 , 60], which is the sum row-wise
axis = 0 reduces into the zero dimension; which means that the program does something with the columns
array.sum(axis = 0) returns
[15 , 18 , 21 , 24 , 27], which is the sum column-wise
What do you find out from array.shape method?
The number of elements in the array
dimensions
What is pandas?
Pandas is a rich relational data tool built on top of NumPy
What is a data frame?
some characteristics:
NumPy array-like
Each column can have a different type
Row and column indexes
Size mutable: insert and delete columns
How can you access a column/s through square brackets in a data frame?
e.g.,
brics[[“country”, “capital”]]
dataframe_name[[column_1, column_2]]
What is the difference between the methods .loc and .iloc when locating some stuff in a pandas data frame?
loc gets rows (or columns) with particular labels from the index
iloc gets rows (or columns) at particular positions in the index (so it only takes integers).