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
How can we slice a list up/until the end?
"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]"
26
How do we repeat a character M times in Python?
"When used with a sequence, the multiplication operator repeats the sequence—in this case, the string ""—value times."
27
Code to iterate using appropiate technique.\t\>...
"for index, value in enumeratecolors:\t ...: printf'{index}: {value}'"
28
How do we iterate through a list?
"The preferred mechanism for accessing an element’s index and value is the built-in function enumerate."
29
Can tuples be modified?
"As with lists, the += augmented assignment statement can be used with strings and tuples, even though they’re immutable."
30
Code of an element addition to a list in Python.\t\>...
"for number in range1, 6:\t ...: a\_list += [number]"
31
What happens to a reference when its variable is modified?
"modifying the variable creates a new object"
32
Explain how Python handles the storage of:\t\> x = 7
"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."
33
How does Python handle references?
"When a function call provides an argument, Python copies the argument object’s reference—not the object itself—into the corresponding parameter."
34
What is the approach of passing parameters in Python?
"Python arguments are always passed by reference. Some people call this pass-by-object-reference, because “everything in Python is an object.”"
35
Define a function with an arbitrary number of parameters.\t\>...
"def averageargs:\t ...: return sumargs / lenargs"
36
Does the order of function parameters matter in Python?
"When calling functions, you can use keyword arguments to pass arguments in any order."
37
Define a function with default parameters.\t\>...
"def rectangle\_arealength=2, width=3:"
38
Do Python support constant variables?
"True/False Python does not have constants.\tAnswer: True."
39
Given a module you can use it...\timport module\tmodule.function
"math.sqrt900"
40
Answer: module
"Fill-In Every Python source code .py file you create is an ."
41
Code to build a really random sequence.\t\>...
"random.seed32"
42
How do we generate random numbers? \t[random.randrangemin max+1]
"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
How can we see the source code for a function if available?
"you can use ?? to display the function’s full source-code definition"
44
How can we see an info doc of a function in Python?
"to view a function’s docstring to learn how to use the function, type the function’s name followed by a question mark ?"
45
Example of call to regular expression in Python
"'Match' if re.fullmatchpattern, '02215' else 'No match'"
46
Example of split
"letters = 'A, B, C, D'\t \tIn [2]: letters.split', '\tOut[2]: ['A', 'B', 'C', 'D']"
47
Substitute a substring from another
"values.replace'\t', ','"
48
Get the last index of an occurrence in a string
"sentence.rindex'be'"
49
Get the first index of an occurrence in a string
"sentence.index'be'"
50
Get the number of occurrences of a substring in a string
"sentence.count'to'"
51
Make every word starts with an Uppercase
"'strings: a deeper look'.title\tOut[2]: 'Strings: A Deeper Look'"
52
Delete the spaces of the right in a string
"sentence.rstrip\tOut[4]: '\t \n This is a test string.'"
53
Delete the spaces of the left in a string
"sentence.lstrip\tOut[3]: 'This is a test string. \t\t \n'"
54
Delete spaces from string on both sides
"sentence.strip\tOut[2]: 'This is a test string.'"
55
Capitalize only first character
"'happy birthday'.capitalize\tOut[1]: 'Happy birthday'"
56
Show a string in the middle of the space
"f'[{3.5:7.1f}]'\tOut[8]: '[3.5]'"
57
Show a value at the right of a predefined space string
"f'[{"hello":\>15}]'\tOut[6]: '[hello]'"
58
Show a value at the left of a predefined space string
"f'[{3.5:\<15f}]'\tOut[5]: '[3.500000]'"
59
Show a two-decimal float number
"f'{17.489:.2f}'"
60
Intersection two sets in Python
"{1, 3, 5} {2, 3, 4}\tOut[3]: {3}\t\tIn [4]: {1, 3, 5}.intersection[1, 2, 2, 3, 3, 4, 4]"
61
Merge two sets in Python
"{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
Create an empty set
"set"
63
Create a set from existing data in Python
"setnumbers"
64
Create a set in Python.\t\>...
"colors = {'red', 'orange', 'yellow', 'green', 'red', 'blue'}"
65
Example of dictionary comprehension
"months2 = {number: name for name, number in months.items}"
66
Methods to insert an item in a dictionary in Python.\t\>...
"country\_codes.updateAustralia='ar'"
67
Obtain an element from a dictionary with caution.\t\>...
"roman\_numerals.get'III', 'III not in dictionary'\tOut[14]: 'III not in dictionary'"
68
How we add a new element to a dictionary in Python?
"Assigning a value to a nonexistent key inserts the key–value pair in the dictionary:\tIn [6]: roman\_numerals['L'] = 50"
69
Dictionary method ____ returns each key–value pair as a tuple.
Answer: items()
70
Iterate through a dictionary.\t\>...
"for month, days in days\_per\_month.items:\t ...: printf'{month} has {days} days'"
71
Create a dictionary in Python.\t\>...
"country\_codes = {'Finland': 'fi', 'South Africa': 'za',\t ...: 'Nepal': 'np'}"
72
"Fill-In An defines related functions, data and classes. An groups related modules. \tAnswer: module, package."
?
73
"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"
?
74
"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."
?
75
"country\_codes.update{'South Africa': 'za'}"
?
76
"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"
?
77
How do we indicate that a class is a dataclass?
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
Card = namedtuple('Card', ['face', 'suit'])
card = Card(face='Ace', suit='Spades') In [4]: card.face Out[4]: 'Ace' In [5]: card.suit Out[5]: 'Spades'
79
Advantage of a namedTuple from the Python library.
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
Overloading of += operator.
def \_\_iadd\_\_(self, right):
81
Overloading of + operator
def \_\_add\_\_(self, right):
82
Definition of duck-duck typing.
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
What is duck-duck typing in Python?
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
INTERNAL KNOWLEDGE
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
Calculate a value using the base class data.
return super().earnings() + self.base\_salary
86
Format number with milliard characters
print(f'{s.earnings():,.2f}')
87
Call to a constructor of the base class.
super().\_\_init\_\_(first\_name, last\_name, ssn, 14 gross\_sales, commission\_rate)
88
Inheritance of a class to another in Python.
class SalariedCommissionEmployee(CommissionEmployee):
89
How to create a path from your location.
from pathlib import Path In [5]: path = Path('.').joinpath('card\_images')
90
Implement a toString method.
def \_\_str\_\_(self): 34 |||Return string representation for str().||| 35 return f'{self.face} of {self.suit}'
91
Explanation of private attributes in Python
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
Advantages of Properties in Python
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
What properties are?
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
Let’s change the hour value to 6:
wake\_up.hour = 6
95
import class Time from timewithproperties.py
from timewithproperties import Time
96
(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.
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
Explanation of class private attributes
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
Answer: False. A class’s \_\_init\_\_ method initializes an object of the class and implicitly returns None.
(True/False) A class’s \_\_init\_\_ method returns an object of the class.
99
Answer: \_\_init\_\_
A class’s _________ method is called by a constructor expression to initialize a new object of the class.
100
Explanation of self attribute
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
Code a class constructor.
def \_\_init\_\_(self, name, balance): |||Initialize an Account object.|||