Python Flashcards

1
Q

What are the different types of errors?

A

 SyntaxErrors - Detected by the interpreter
 RuntimeErrors – Causes the program to abort
 LogicErrors – Produces an incorrect result

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

what is the eval function?

A

eval()

The computer evaluates, and guesses what the user may be trying to input.

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

how to extract a substring from a variable

A

s[2:4]

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

substring from index 3 to the end

A

s[3:]

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

What is the method to get the character length?

A

len()

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

how to replace characters within a string

A

STRINGVARIABLENAME.replace(‘FIRSTLETTER’,’REPLACINGLETTER’)

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

what method removes leading/trailing whitespaces

A

variable.strip()

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

what is the python method how to make substrings

A

split()

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

what method provides the type for a variable?

A

type()

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

how to slice an index from a certain part of s string, to another, via a interval step

A

s.[3:8:2]

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

How to summon the notepad from the command line in windows command prompt

A

notepad filename.extension

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

What are the programming naming conventions (e.g. what “case” would you name a variable as? etc.)

A

 Both Functions and Variable names, and Package and Module names - snake case
 Class names – CapitalizedWords (or CamelCase)

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

What are the three types of operators?

A

1) Unary — works on one operator (e.g. a negative sign)
2) Binary — works with two operands
3) Ternary — works with three (i.e. known as conditions statements)

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

How does the range() work?

is the stop number inclusive or exclusive?

A

range(stop)
 generates an arithmetic progression of integers starting from
0 to stop-1 with the step of 1 ❑ range(start, stop)
start to stop-1 with the step of 1 ❑ range(start, stop, step)
 generates an arithmetic progression of integers starting from start to stop-1 with the step of step

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

list.append(elm)

A

adds the element to the end of the list

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

Adds all elements of the sequence to the list

A

list.extend(seq)

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

Linear Search

A

The linear search approach compares the key element, key, sequentially with each element in the list. The method continues to do so until the key matches an element in the list or the list is exhausted without a match being found. If a match is found, the linear search returns the index of the element in the list that matches the key. If no match is found, it returns -1.

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

What is the python code for binary search?

A
def binary_search(lst, key): lo = 0
     hi = len(lst)-1
     while lo <= hi:
         mid = (lo+hi)//2
if lst[mid] < key: lo = mid+1
         elif lst[mid] > key:
             hi = mid-1
else:
return mid
return -1
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

Selection sort implementation syntax

A
def selection_sort(lst):
for i in range(len(lst)):
lo = i
         for j in range(i+1, len(lst)):
             if lst[j] < lst[lo]:
lo = j
my_list = [5, 4, -3, 2, -53, 16, 0] selection_sort(my_list) print(my_list)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

what are compiled error also called?

A

check error

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

what is the keyword used to the throw an exceptions

A
1) raise
this is used for a custom exception
doesn't need to be in a conditional 
2) assert #this is more commonly used
assertion  error is less customize-able
3) try...except..else block
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

What normally goes into the body of the try…except..else..finally clause

A

log

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

what is the difference between finally and writing outside of the block

A

In the event of an unhandled error, the ‘finally’ of the try block will run. But if that same clause is written after the try clause, it will not run.

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

how to check the type of a variable

A

isinstance(dvd, float)

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

for a try statements if you were to put a definition within the body of the try block

A

It will not run.

You cannot put a function/method definition within the try block

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

What syntax is usually accompanied with a ‘except’ statement within the try and except phrase?

A

a type of error

e.g:
except Indexerror:

27
Q

what is the default mode when opening a file?

A

opening a file (e.g. “open(‘my_file.txt’)”) opens in read mode / text file

28
Q

Python syntax to Open a file for reading. (default)

A
f = open('my_file.txt')
# equivalent to 'r' or , 'rt')
29
Q

Python syntax to open a file for writing.

A
f = open('my_file.csv', 'w')
# write in text mode
'''
**Creates a new file if it does not exist or truncates the file if it exists.
'''
30
Q

Python syntax to open a file for exclusive creation. If the file already exists, the operation fails.

A

f = open(‘my_file.txt’, ‘w’)

31
Q

Python syntax to open a file for exclusive creation. If the file already exists, the operation fails.

A

f = open(‘my_file.csv’, ‘x’)

32
Q

Python syntax to open a file for appending at the end of the file without truncating it. Creates a new file if it does not

A

open(‘my_file.csv’, ‘a’)

33
Q

Python syntax to open a file in text mode

A

f = open(‘my_file.txt’, ‘t’)

34
Q

Python syntax to open a file for updating (reading and writing)

A

the + flag, can be written with ‘w’, ‘r’, or ‘a’

f = open(‘my_file.txt’, ‘+’)

35
Q

what does tell() do?

A

Returns the current position of the cursor with in the file.

36
Q

what does seek(n) do?

A

Moves the current position of the cursor to n.

37
Q

what does read(n) do?

A

Reads and returns at most n bytes/characters from the file. Reads till the end of the file if it is negative or not provided.

38
Q

What is the python syntax to reads and returns a list of lines from the file

A

readlines()

39
Q

What type string does a .splitlines() and .split() and return?

A

a “list’ of strings

40
Q

What is an array?

A

An array in Python is a compact way of collecting basic data types, all the entries in an array must be of the same data type. However, arrays are not popular in Python, unlike other programming languages such as C# or Java.

Arrays are not built into Python. We can implement arrays using array or numpy modules. (e.g. import array as alias name)

import array as arr
a = arr.array(‘I’, [3, 6, 9]) for i in a:
print(i)

41
Q

what does .shape do?

A

it gives you the dimensions of a multi-dimensional array

number_of_rows, number_of_columns

42
Q

what is the linear structure?

A

The data structures where data items are organized sequentially or linearly where data elements attached one after another is called linear data structure. Data elements in a linear data structure are traversed one after the other and only one element can be directly reached while traversing. All the elements in linear data structure can be traversed in a single run.

the examples of linear data structures we will discuss are stack, queue, and linked list.

43
Q

What is deque?

A

data structure called deque(double-ended queue) that generalizes a queue, for which elements can be added to or removed from either the front or back.

module supports thread-safe, memory efficient appends and pops from either side of the deque with approximately the same performance in either direction.

44
Q

What is a tuple?

A

Tuples function like a list but are immutable, and are ‘lighter’ weight

powerpoint definition: A tuple is another standard sequence data type. It is immutable sequences, typically used to store collections of heterogeneous data. Since tuples are immutable, unlike lists, once they are defined, the values cannot be removed, added, or edited. This might be useful in situations where we want to implement “read- only” data structure. Also, a tuple is much simpler structure than a list, and therefore much faster in terms of performance. Tuples are built into Python: they need not be imported.

45
Q

what does the ^ operator do for set?

set1 ^ set2

A

set1 ^ set2

Returns a new set with elements in either set1 and set2, but not both.

46
Q

what does the <= operator do for set?

set1 <= set2

A

set1 <= set2

Tests whether set1 is a subset of set2.

47
Q

what does the >= operator do for set?

set1 >= set2

A

set1 >= set2

Tests whether set1 is a superset of set2.

48
Q

what does the | operator do for set?

set1 | set2

A

set1 | set2

Returns a union of set1 and set2 as a set.

49
Q

what does the & operator do for set?

set1 & set2

A

set1 & set2

Returns an intersection of set1 and set2 as a set.

50
Q

what does the ‘-‘ operator do for set?

set1 - set2

A

Returns a new set with elements in set1 that are not in set2.

51
Q

what does the ^ operator do for set?

set1 ^ set2

A

Returns a new set with elements in either set1 and set2, but not both.

52
Q

In Python, what is a Class attribute?

A

Class attributes are defined in the body of a class, at the same indentation level as method definitions. Class attributes are often used to define constants which are closely associated with a particular class. They are accessible from both class instances and the class object itself

53
Q

what is an instance?

A

An instance, more commonly known as an object, a “living/breathing” life example of a class (with values and functions.

Powerpoint definition: While the class is the blueprint, an instance is a copy of the class with actual values, literally an object belonging to a specific class. From the previous example, an instance of a Student class is not an idea anymore; it is an actual student, like a student named Young whose id is 1328 and who lives in New York, NY.

54
Q

What is an Attribute or Method?

A

The “properties” or data values which we store inside an object are called attributes, and the “behaviors” or functions which are associated with the object are called methods. We have already used the methods of some built-in objects, like strings and lists.

When designing user-defined classes and objects, we have to decide how things are grouped together, and what to represent with the objects.

55
Q

What is the syntax to a class called student

A
class Student:
def \_\_init\_\_(self, student_id, name, address):
self.student_id = student_id 
self.name = name 
self.address = address

s = Student(1328, ‘Young Wook Baek’, ‘New York, NY’)
print(‘id:{}, name:{}, address:{}’
.format(s.student_id, s.name, s.address))

56
Q

What is the __init__ method?

A

The initialization method of an object, which is called when the object is created

57
Q

What is the __str___ method?

A

The “informal” representation method of an object, which is called when using str function to convert the object to a string

58
Q

What are built-in functions with a class?

A

➢ getattr(obj, attr) – accesses the attribute of the object.
➢ hasattr(obj, attr) – checks if the attribute exists.
➢ setattr(obj, attr, value) – sets the attribute. If the attribute does not exist, then it is created.
➢ delattr(obj, attr) – deletes the attribute.

59
Q

What is an instance method?

A

Instance methods are defined inside a class body and are used to get the contents of an instance. They can also be used to perform operations with the attributes of the objects. Like the __init__ method, the first argument is always self:

class Student:
            def \_\_init\_\_(self, f_name, l_name):
            self.f_name = f_name 
            self.l_name = l_name
# instance method
def fullname(self):
             return "{} {}".format(self.f_name, self.l_name)
s = Student('Young Wook', 'Baek') 
print(s.fullname())
# output: "Young Wook Baek"
60
Q

What is a decorator?

A

Decorators are functions used to transform some original function into another form. A decorator creates a kind of composite function.

61
Q

How do you create a 2D array or list using numpy?

A

numpy. empty((3,3), dtype=’str’)

grid. fill(‘ ‘)

62
Q

When do you use yield statements?

A

If a function contains at least one yield statement, it becomes a generator function.
You use yield statements when you want to return an iterable statement (see slides)

63
Q

What is the higher order function

A

A function that takes in another function

64
Q

What is the python syntax used with the mysql.connector module to create a connection?

A

connect(host =’localhost’, user=’root’,database=’test_db’)

host defaults to ‘localhost’