Python Flashcards

1
Q

What is the precedence of comparison operatos?

A

“The operators and >= all have the same level of precedence and evaluate left to right. The operators == and != have the same level of precedence and evaluate left to right. Their precedence is lower than that of and >=.”

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

What is cloud computing?

A

“Cloud computing: You can use software and data stored in the “cloud”—i.e., accessed on remote computers or servers via the Internet and available on demand—rather than having it stored locally on your desktop, notebook computer or mobile device. This allows you to increase or decrease computing resources to meet your needs at any given time, which is more cost effective than purchasing hardware to provide enough storage and processing power to meet occasional peak demands. Cloud computing also saves money by shifting to the service provider the burden of managing these apps such as installing and upgrading the software, security, backups and disaster recovery.”

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

What is an interpreted language?

A

“Compiling a large high-level language program into machine language can take considerable computer time. Interpreter programs, developed to execute high-level language programs directly, avoid the delay of compilation, although they run slower than compiled programs.”

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

What is a list in Python?

A

” One of the most common is a list, which is a comma-separated collection of items enclosed in square brackets [and]. Python only contains basically lists and dicts and sets and tuples a_list = [1, 2, 3]”

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

Example of matrix for in Python

A

“for i, row in enumeratea:\t …: for j, item in enumeraterow:\t …: printf’a[{i}][{j}]={item} ‘, end=’ ‘\t …: print”

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

Example of combination with map and filter

A

“listmaplambda x: x 2,\t …: filterlambda x: x 2 != 0, numbers”

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

Example of filter function

A

“listfilterlambda x: x 2 != 0, numbers”

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

Example of map function

A

“listmaplambda x: x 2, numbers”

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

Define the format of a lambda in Python

A

“lambda parameter_list: expression”

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

Example of a list comprehension

A

“[item for item in range1, 11 if item 2 == 0]”

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

How we can construct a list from a given range?

A

“list2 = listrange1, 6”

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

Put the list upside down.\t>…

A

“color_names.reverse”

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

How do we get the number of ocurrences of an element in a list?

A

“responses.counti”

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

How do we delete an element from a list?

A

“color_names.remove’green’”

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

How do we add more than one item to a list?

A

“color_names.extend[‘indigo’, ‘violet’]”

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

How do we add an item to the list?

A

“color_names.append’blue’”

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

How do we add an element to a specified position of a list?

A

“color_names.insert0, ‘red’”

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

How can we prevent an index error

A

“You can use the operator in to ensure that calls to method index do not result in ValueErrors for search keys that are not in the corresponding sequence:\tIn [11]: key = 1000\t\tIn [12]: if key in numbers:\t …: printf’found {key} at index {numbers.indexsearch_key}’\t …: else:\t …: printf’{key} not found’\t …:\t1000 not found”

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

Order a list without changing its original content.\t>…

A

“ascending_numbers = sortednumbers”

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

Order a list beginning at the end.\t>…

A

“numbers.sortreverse=True”

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

Order a list.\t>…

A

“numbers.sort”

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

Delete a member with a specific index position in a list.

A

“del numbers[-1]”

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

How can you create an empty list from a range?

A

“IPython Session”

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

Assume you have a list called names. The slice expression _____ creates a new list with the elements of names in reverse order.

A

Answer:

names[::-1]

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

How can we slice a list up/until the end?

A

“In [3]: numbers[:6]\tOut[3]: [2, 3, 5, 7, 11, 13]\t\tIn [4]: numbers[0:6]\tOut[4]: [2, 3, 5, 7, 11, 13]”

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

How do we repeat a character M times in Python?

A

“When used with a sequence, the multiplication operator repeats the sequence—in this case, the string ““—value times.”

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

Code to iterate using appropiate technique.\t>…

A

“for index, value in enumeratecolors:\t …: printf’{index}: {value}’”

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

How do we iterate through a list?

A

“The preferred mechanism for accessing an element’s index and value is the built-in function enumerate.”

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

Can tuples be modified?

A

“As with lists, the += augmented assignment statement can be used with strings and tuples, even though they’re immutable.”

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

Code of an element addition to a list in Python.\t>…

A

“for number in range1, 6:\t …: a_list += [number]”

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

What happens to a reference when its variable is modified?

A

“modifying the variable creates a new object”

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

Explain how Python handles the storage of:\t> x = 7

A

“the variable x does not actually contain the value 7. Rather, it contains a reference to an object containing 7 and some other data we’ll discuss in later chapters stored elsewhere in memory.”

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

How does Python handle references?

A

“When a function call provides an argument, Python copies the argument object’s reference—not the object itself—into the corresponding parameter.”

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

What is the approach of passing parameters in Python?

A

“Python arguments are always passed by reference. Some people call this pass-by-object-reference, because “everything in Python is an object.””

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

Define a function with an arbitrary number of parameters.\t>…

A

“def averageargs:\t …: return sumargs / lenargs”

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

Does the order of function parameters matter in Python?

A

“When calling functions, you can use keyword arguments to pass arguments in any order.”

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

Define a function with default parameters.\t>…

A

“def rectangle_arealength=2, width=3:”

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

Do Python support constant variables?

A

“True/False Python does not have constants.\tAnswer: True.”

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

Given a module you can use it…\timport module\tmodule.function

A

“math.sqrt900”

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

Answer: module

A

“Fill-In Every Python source code .py file you create is an .”

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

Code to build a really random sequence.\t>…

A

“random.seed32”

42
Q

How do we generate random numbers? \t[random.randrangemin max+1]

A

“First, we import random so we can use the module’s capabilities. The \trandrange function generates an integer from the first argument value up to, but not including, the second argument value.”

43
Q

How can we see the source code for a function if available?

A

“you can use ?? to display the function’s full source-code definition”

44
Q

How can we see an info doc of a function in Python?

A

“to view a function’s docstring to learn how to use the function, type the function’s name followed by a question mark ?”

45
Q

Example of call to regular expression in Python

A

“‘Match’ if re.fullmatchpattern, ‘02215’ else ‘No match’”

46
Q

Example of split

A

“letters = ‘A, B, C, D’\t \tIn [2]: letters.split’, ‘\tOut[2]: [‘A’, ‘B’, ‘C’, ‘D’]”

47
Q

Substitute a substring from another

A

“values.replace’\t’, ‘,’”

48
Q

Get the last index of an occurrence in a string

A

“sentence.rindex’be’”

49
Q

Get the first index of an occurrence in a string

A

“sentence.index’be’”

50
Q

Get the number of occurrences of a substring in a string

A

“sentence.count’to’”

51
Q

Make every word starts with an Uppercase

A

“‘strings: a deeper look’.title\tOut[2]: ‘Strings: A Deeper Look’”

52
Q

Delete the spaces of the right in a string

A

“sentence.rstrip\tOut[4]: ‘\t \n This is a test string.’”

53
Q

Delete the spaces of the left in a string

A

“sentence.lstrip\tOut[3]: ‘This is a test string. \t\t \n’”

54
Q

Delete spaces from string on both sides

A

“sentence.strip\tOut[2]: ‘This is a test string.’”

55
Q

Capitalize only first character

A

“‘happy birthday’.capitalize\tOut[1]: ‘Happy birthday’”

56
Q

Show a string in the middle of the space

A

“f’[{3.5:7.1f}]’\tOut[8]: ‘[3.5]’”

57
Q

Show a value at the right of a predefined space string

A

“f’[{“hello”:>15}]’\tOut[6]: ‘[hello]’”

58
Q

Show a value at the left of a predefined space string

A

“f’[{3.5:<15f}]’\tOut[5]: ‘[3.500000]’”

59
Q

Show a two-decimal float number

A

“f’{17.489:.2f}’”

60
Q

Intersection two sets in Python

A

“{1, 3, 5} {2, 3, 4}\tOut[3]: {3}\t\tIn [4]: {1, 3, 5}.intersection[1, 2, 2, 3, 3, 4, 4]”

61
Q

Merge two sets in Python

A

“{1, 3, 5} | {2, 3, 4}\tOut[1]: {1, 2, 3, 4, 5}\t\tIn [2]: {1, 3, 5}.union[20, 20, 3, 40, 40]”

62
Q

Create an empty set

A

“set”

63
Q

Create a set from existing data in Python

A

“setnumbers”

64
Q

Create a set in Python.\t>…

A

“colors = {‘red’, ‘orange’, ‘yellow’, ‘green’, ‘red’, ‘blue’}”

65
Q

Example of dictionary comprehension

A

“months2 = {number: name for name, number in months.items}”

66
Q

Methods to insert an item in a dictionary in Python.\t>…

A

“country_codes.updateAustralia=’ar’”

67
Q

Obtain an element from a dictionary with caution.\t>…

A

“roman_numerals.get’III’, ‘III not in dictionary’\tOut[14]: ‘III not in dictionary’”

68
Q

How we add a new element to a dictionary in Python?

A

“Assigning a value to a nonexistent key inserts the key–value pair in the dictionary:\tIn [6]: roman_numerals[‘L’] = 50”

69
Q

Dictionary method ____ returns each key–value pair as a tuple.

A

Answer:

items()

70
Q

Iterate through a dictionary.\t>…

A

“for month, days in days_per_month.items:\t …: printf’{month} has {days} days’”

71
Q

Create a dictionary in Python.\t>…

A

“country_codes = {‘Finland’: ‘fi’, ‘South Africa’: ‘za’,\t …: ‘Nepal’: ‘np’}”

72
Q

“Fill-In An defines related functions, data and classes. An groups related modules. \tAnswer: module, package.”

A

?

73
Q

“If you need to create an empty set, you must use the set function with empty parentheses, rather than empty braces, {}, which represent an empty dictionary”

A

?

74
Q

“Curly braces delimit a dictionary comprehension, and the expression to the left of the for clause specifies a key–value pair of the form key: value. The comprehension iterates through months.items, unpacking each key–value pair tuple into the variables name and number. The expression number: name reverses the key and value, so the new dictionary maps the month numbers to the month names.”

A

?

75
Q

“country_codes.update{‘South Africa’: ‘za’}”

A

?

76
Q

“months = {‘January’: 1, ‘February’: 2, ‘March’: 3}\t\tIn [2]: for month_name in months.keys:\t …: print month_name, end=’ ‘\t …:\tJanuary February March\t\tIn [3]: for month_number in months.values:\t …: printmonth_number, end=’ ‘\t …:\t1 2 3”

A

?

77
Q

How do we indicate that a class is a dataclass?

A

To specify that a class is a data class, precede its definition with the @dataclass decorator: Use of a namedTuple PART OF ANSWER: from collections import namedtuple

78
Q

Card = namedtuple(‘Card’, [‘face’, ‘suit’])

A

card = Card(face=’Ace’, suit=’Spades’) In [4]: card.face Out[4]: ‘Ace’ In [5]: card.suit Out[5]: ‘Spades’

79
Q

Advantage of a namedTuple from the Python library.

A

The Python Standard Library’s collections module also provides named tuples that enable you to reference a tuple’s members by name rather than by index number.

80
Q

Overloading of += operator.

A

def __iadd__(self, right):

81
Q

Overloading of + operator

A

def __add__(self, right):

82
Q

Definition of duck-duck typing.

A

A programming style which does not look at an object’s type to determine if it has the right interface, instead, the method or attribute is simply called or used (If it looks like a duck and quacks like a duck, it must be a duck.).

83
Q

What is duck-duck typing in Python?

A

for employee in employees: print(employee) print(f’{employee.earnings():,.2f}\n’) In Python, this loop works properly as long as employees contains only objects that: can be displayed with print (that is, they have a string representation) and have an earnings method which can be called with no arguments.

84
Q

INTERNAL KNOWLEDGE

A

In the Python open-source world, there are a huge number of well-developed class libraries for which your programming style is: know what libraries are available, know what classes are available, make objects of existing classes, and send them messages (that is, call their methods). This style of programming called object-based programming (OBP). When you do composition with objects of known classes, you’re still doing object-based programming. Adding inheritance with overriding to customize methods to the unique needs of your applications and possibly process objects polymorphically is called object-oriented programming (OOP). If you do composition with objects of inherited classes, that’s also object-oriented programming.

85
Q

Calculate a value using the base class data.

A

return super().earnings() + self.base_salary

86
Q

Format number with milliard characters

A

print(f’{s.earnings():,.2f}’)

87
Q

Call to a constructor of the base class.

A

super().__init__(first_name, last_name, ssn, 14 gross_sales, commission_rate)

88
Q

Inheritance of a class to another in Python.

A

class SalariedCommissionEmployee(CommissionEmployee):

89
Q

How to create a path from your location.

A

from pathlib import Path In [5]: path = Path(‘.’).joinpath(‘card_images’)

90
Q

Implement a toString method.

A

def __str__(self): 34 |||Return string representation for str().||| 35 return f’{self.face} of {self.suit}’

91
Q

Explanation of private attributes in Python

A

Even with double-underscore (__) naming, we can still access and modify __private_data, because we know that python renames attributes simply by prefixing their names with ‘_ClassName’.

92
Q

Advantages of Properties in Python

A

It may seem that providing properties with both setters and getters has no benefit over accessing the data attributes directly, but there are subtle differences. A getter seems to allow clients to read the data at will, but the getter can control the formatting of the data. A setter can scrutinize attempts to modify the value of a data attribute to prevent the data from being set to an invalid value.

93
Q

What properties are?

A

properties, which look like data attributes to client-code programmers, but control the manner in which they get and modify an object’s data. This assumes that other programmers follow Python conventions to correctly use objects of your class. Setting an Attribute via a Property Class Time also supports setting the hour, minute and second values individually via its properties.

94
Q

Let’s change the hour value to 6:

A

wake_up.hour = 6

95
Q

import class Time from timewithproperties.py

A

from timewithproperties import Time

96
Q

(True/False) Like most object-oriented programming languages, Python provides capabilities for encapsulating an object’s data attributes so client code cannot access the data directly.

A

Answer: False. In Python, all data attributes are accessible. You use attribute naming conventions to indicate that attributes should not be accessed directly from client code.

97
Q

Explanation of class private attributes

A

Python does not have private data. Instead, you use naming conventions to design classes that encourage correct use. By convention, Python programmers know that any attribute name beginning with an underscore (_) is for a class’s internal use only. Client code should use the class’s methods and—as you’ll see in the next section—the class’s properties to interact with each object’s internal-use data attributes. Attributes whose identifiers do not begin with an underscore (_) are considered publicly accessible for use in client code. In the next section, we’ll define a Time class and use these naming conventions. However, even when we use these conventions, attributes are always accessible.

98
Q

Answer: False. A class’s __init__ method initializes an object of the class and implicitly returns None.

A

(True/False) A class’s __init__ method returns an object of the class.

99
Q

Answer: __init__

A

A class’s _________ method is called by a constructor expression to initialize a new object of the class.

100
Q

Explanation of self attribute

A

When you call a method for a specific object, Python implicitly passes a reference to that object as the method’s first argument. For this reason, all methods of a class must specify at least one parameter. By convention most Python programmers call a method’s first parameter self. A class’s methods must use that reference (self) to access the object’s attributes and other methods.

101
Q

Code a class constructor.

A

def __init__(self, name, balance): |||Initialize an Account object.|||