Python Part Flashcards

1
Q

What does a condition evaluate to?

A

Boolean. True or False

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

What does a break statement do?

A

Immediately exits whatever loop it is in, and skips the remaining expressions in the code block.

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

In a for loop, there is an unbounded number of iterations that you don’t know. True or false?

A

False. You know the number of iterations in a for loop. In a while loop there is an unbounded number of iterations

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

Which of the following are mutable:

a. Strings
b. Lists
c. Tuples

A

b. lists

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

What can you use to slice a string?

A

string[start:stop:step]

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

What is a docstring?

A

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)

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

Inside a function, you can access a variable defined outside. True or false?

A

True

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

Inside a function, you can modify a variable defined outside (without global variables). True or false?

A

False

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

What is a higher order function?

A

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

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

Define the scope of a variable.

A

The scope is mapping of names to objects

I don’t know why I put this in

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

A return statement ends the execution of the function call and returns the result. True or false?

A

True

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

What does “lists are mutable” mean?

A

It means that list elements can be changed.

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

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

A

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 ().

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

To combine lists together you can use the + operator. True or false?

A

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)

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

What does the method .pop on a list do?

A

It removes the element at the end of the list and returns the removed element.

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

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?

A

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.

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

What can you use to delete an element at a specific index in a list?

A

del(L[index])

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

Assume s is a string. What do you use to convert it to a list containing every character from s?

A

list(s)

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

What does s.split(“,”) do? s is a string

A

It is splitting a string on a character parameter. It splits on spaces if called without a parameter.

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

Think of a list. What is the difference between sort() and sorted()

A

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]

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

What do you use to get the absolute value of something?

A

abs()

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

Tuples are immutable. True or false?

A

True.

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

What is a tuple?

A

An ordered sequence of elements, in which you can mix the element types:
(2, “plant”, 3)

24
Q

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?

A

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!!!

25
Q

What is recursion?

A

A programming technique where a function calls itself.

26
Q

What is the first step in the process of writing a recursion?

A
  1. You must have 1 or more base cases that are easy to solve
  2. 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)

27
Q

What does a dictionary store?

A

It stores pairs of data. it has keys and values

28
Q

What methods can you use on dictionaries to iterate through the keys and values?

A

.keys() separately
.values() separately

.items() together

29
Q

A dictionary automatically stores keys in order. True or false?

A

False

30
Q

Values and keys can be duplicates in a dictionary. True or false?

A

False. Only values can be duplicates. Keys are always unique.

31
Q

A list is indexed by a range of numbers, while dictionaries are indexed by a set of unique keys. True or false?

A

True

32
Q

The order matters in the dictionary, but does not matter in a list. True or false?

A

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

33
Q

What is the difference between classes and objects?

A

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.

34
Q

What is the difference between a method and an attribute?

A

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.

35
Q

What does every object have? (3 characteristics)

A
  1. A type
  2. An internal data representation (primitive or composite)
  3. A set of procedures for interaction with the object
36
Q

What is the difference between primitive data types and composite data types?

A

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…

37
Q

What are objects?

A

Objects are data abstractions that capture:

  1. an internal representation - through data attributes
  2. an interface for interacting with the objects - through methods
38
Q

What are some advantages of OOP (object-oriented programming)?

A

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

39
Q

What are attributes of a class?

A

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

40
Q

What is __init__?

A

A special method to initialize some data attributes. It allows us to kickstart the object with some specific attributes

41
Q

Getter and setter method. Click

A

No idea. write more when you arrive here

42
Q

When do the following errors appear?

a. IndexError
b. TypeError
c. NameError
d. SyntaxError

A

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

43
Q

How does try & except handling work?

A

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.

44
Q

How does “raise” exception handing work?

A

The program can raise an exception when it is unable to produce a result consistent with the function’s specifications

45
Q

How do assertions work in Python?

A

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"
46
Q

What is the goal of assertions?

A

To spot bugs as soon as they are introduced and make clear where they happened.

47
Q

NumPy arrays comprise elements of a single data type. True or false?

A

True

48
Q

What is an array?

A

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.

49
Q

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)

A

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.

50
Q

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?

A

Yes, the arrays work the same way. Simple assignments do not make copies of arrays.

51
Q

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?

A

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.

52
Q

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)

A

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

53
Q

What do you find out from array.shape method?

A

The number of elements in the array

dimensions

54
Q

What is pandas?

A

Pandas is a rich relational data tool built on top of NumPy

55
Q

What is a data frame?

A

some characteristics:
NumPy array-like

Each column can have a different type

Row and column indexes

Size mutable: insert and delete columns

56
Q

How can you access a column/s through square brackets in a data frame?

A

e.g.,

brics[[“country”, “capital”]]

dataframe_name[[column_1, column_2]]

57
Q

What is the difference between the methods .loc and .iloc when locating some stuff in a pandas data frame?

A

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).