Q001-150 Flashcards

(150 cards)

1
Q

What are the 2 rules for naming a variable?

A
  1. It can be only letters, numbers and underscores
  2. It can’t start with a number
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What are the 2 ways of assigning multiple variables?

A
**a = b = c = 10**
# all of them equal to 10
**a, b, c = 1, 2, 3**
# each of them equals the respective number
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What are the built-in data types? (15 types in 8 categories)

A

text type: str
numeric types: int, float, complex
sequence types: list, tuple, range
mapping type: dict
set types: set, frozen set
Boolean type: bool
binary types: byte, bytearray, memoryview
None type: NoneType

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

What are three features of an object in Python and which of them can be changed?

A
  1. ID - never changes
  2. type - never changes
  3. value - can change (mutable objects) or not (immutable objects)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Which data types are mutable and which immutable?

A

mutable: lists, byte arrays, sets and dictionaries

immutable: numeric data types, strings, bytes, frozen sets and tuples

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

How do we insert multi-line strings?

A

In between triple quotes with Enter after each line except of the last one:

my_string = ‘’’one

two

three’’‘

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

What’s the new line character and how to escape it?

A

\n

It’s a control character used to signify the end of a line of a text and start of a new one.

my_string = ‘’’one

two

three’’’

my_string = ‘one\ntwo\nthree’

****

A backslash has to be inserted at the end of a line (except from the last one)

my_string = ‘’’one\

two\

three’’’

my_string = ‘onetwothree’

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

What are the 2 ways of using indexes and slicing strings and their syntax?

A
  1. Going from the left - the first character has index 0, second 1 and so on
  2. Going from the right - the first character -1, second -2 and so on

syntax: string [start index : end index : step]

The end index is not included!

examples:

my_string = ‘unicode’

print (my_string[0])
print (my_string[-2])
print (my_string[1:3])
print (my_string[:3])
print (my_string[2:-2])
print (my_string[::2])
print (my_string[::-2])

u
d
ni
uni
ico
uioe
eoiu

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

How to find out the length of a string?

A

Using the len() function.

my_string = ‘unicode’

len(my_string)

7

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

What are the 3 basic operations with strings and what do they return?

A

x = ‘new’

y = ‘ order’

  1. Concatenation: x + y (returns string)

‘new order’

  1. Repetition: 3 * x (returns string)

‘newnewnew’

  1. Checking whether a character is part of it: ‘a’ in x or ‘a’ not in x (returns boolean)

False

True

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

What’s the syntax of formatting strings with % and {} operator and limiting decimal points of a float variable?

A

setting up the format structure:

x = ‘model: %s, %d slots, IOS %f’ % (2600XT, 2, 12.4)

print(x)

model: 2600XT, 2 slots, IOS 12.400000

or

x = ‘model: {}, {} slots, IOS {}’ .format (2600XT, 2, 12.4)

print(x)

model: 2600XT, 2 slots, IOS 12.4

changing values and limiting floating decimal points to 1:

y = ‘model: %s, %d slots, IOS %.1f’ % (2800XT, 4, 12.5)

print(x)

model: 2800XT, 4 slots, IOS 12.5

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

What is indexing in formatting strings with {} for and how to use it?

A

It’s useful when we want to switch the order of the values or repeat some of them:

x = ‘model: {1}, {2} slots, IOS {0}’ .format (2600XT, 2, 12.4)

print(x)

model: 2, 12.4 slots, IOS 2600XT

or

x = ‘model: {1}, {2} slots, IOS {1}’ .format (2600XT, 2, 12.4)

print(x)

model: 2, 12.4 slots, IOS 2

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

What is f-string formatting and what’s the syntax?

A

A way to embed variables, expressions and methods inside strings using a minimal syntax.

model = '2600XM'
slots = 4
ios = 12.3

using variables, expressions and methods

f”Cisco model: {model.lower()}, {slots * 2} WAN slots, IOS {ios}”

‘Cisco model: 2600xm, 8 WAN slots, IOS 12.3’

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

What are the 2 important features of strings?

A
  1. They are immutable
  2. Upper and lower case matter
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What are the 2 methods for finding a character within a string, their syntax, 2 important rules and what does it return?

A

Finding the first or the last occurence of a character or a substring of characters in a string or a substring starting and ending with given indexes:

x. find - the first occurence
x. rfind - the last occurence

syntax:

  • *x.find(str, beg = 0, end = len(string))**
  • *x.rfind(str, beg = 0, end = len(string))**

2 rules:

  1. when no indexes given, it searches in the whole string
  2. when given, the ending index is not include

Returns:

an integer if found, integer -1 if not found

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

What does string index method do, what’s the syntax and what does it return?

A

It is indexing the first or the last occurence of a character or a substring of characters in a string or a substring starting and ending with given indexes

x. index - the first occurence
x. rindex - the last occurence

syntax:

  • *x.index(str, beg = 0, end = len(string))**
  • *x.rindex(str, beg = 0, end = len(string))**

Returns:

an integer if found, raises an exception if not found

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

What’s the method for counting characters in a string, its syntax and return?

A

count()

Counting the number of occurences of a character or a substring of characters in a string or a substring starting and ending with given indexes

syntax:

x.count(str, beg = 0, end = len(string))

Returns:

an integer, integer 0 if not found

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

What are the methods for returning min and max character from a string and their syntax?

A

min() and max()

Returns:

a string (a lowercase character first, if there is none, then uppercase)

syntax:

min(str)

max(str)

example:

x = “The temptation of the internet”

min(x)
‘ ‘

max(x)
‘t’

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

What are the 5 methods for converting the case of a string and their syntax?

A

x.lower(), x.upper(), x.swapcase(), x.title() and x.capitalize

important! :

It’s not changing the original string, strings are immutable!

examples:

x = “The temptation of the internet”

x.lower()

‘the temptation of the internet’

x.upper()

‘THE TEMPTATION OF THE INTERNET’

x.swapcase()

‘tHE TEMPTATION OF THE INTERNET’

x.title()

‘The Temptation Of The Internet’

x = ‘tool’

x.capitalize()

‘Tool’

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

Which method can be used to replace or remove a character in a string?

A

x.replace(old, new, max number of occurences)

examples:

x = ‘ Remove the spaces ‘

x.replace(“ “, “”)

replaces spaces with no character:

‘Removethespaces’

x = ‘hahaha’

x.replace(‘a’,’e’)

‘hehehe’

x.replace(‘a’,’e’,2)

‘heheha’

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

Which method can be used to split a string and what’s the syntax and return?

A

x.split(delimiter, max number of delimiters)

= splitting a string by specifying a delimiter (space if not provided) with given maximum of delimiters (optional)

= returns a list

examples:

x = ‘one two three’
x.split(‘ ‘)
[‘one’, ‘two’, ‘three’]

x = ‘one two three’
x.split()
[‘one’, ‘two’, ‘three’]

x = ‘0111022203330’
x.split(‘0’)

creates an empty item of a list if the delimiter is at the beginning or the end:
[’’, ‘111’, ‘222’, ‘333’, ‘’]

x.split(‘ ‘,2)
[‘one’, ‘two’, ‘three’]

x.split(‘ ‘,1)
[‘one’, ‘two three’]

x.split(‘ ‘,0)
[‘one two three’]

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

Which method is used to split a string at new lines?

A

x.splitlines(keepends)

= splitting a string at all or given max of newlines (\n)

= when keepends set as True, line breaks are also included in items of the list
= returns a list
= if there are not line break characters, it returns a list with a single item

examples:

x = ‘One\nTwo\nThree\nFour’

x.splitlines()
[‘One’, ‘Two’, ‘Three’, ‘Four’]

x.splitlines(True)
[‘One\n’, ‘Two\n’, ‘Three\n’, ‘Four’]

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

Which method can be used to insert a character or a substring in between characters of a string?

A

join(str)

= inserting a character or a substring of characters in between every two characters

x = ‘Nova Dedina’
‘ ‘.join(x)
‘N o v a D e d i n a’

‘123’.join(x)
‘N123o123v123a123 123D123e123d123i123n123a’

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

024 What are the 3 methods for removing a character or a substring from the beginning and / or the end of a string?

A

str.strip(), str.lstrip() and str.rstrip()

= removing a character or a substring of characters from the beginning or/and the end of the string

= removes whitespaces if not specified (spaces, tabs, returns…)

examples:

x = ‘ Dude ‘

’ Dude\t\t\t’

x.strip()

‘Dude’

x = ‘aDudea’
x.strip(‘a’)
‘Dude’

x = ‘aaaDudeaaa’
x.strip(‘a’)
‘Dude’

x = ‘aaaDudea’
x.strip(‘a’)
‘Dude’

x = ‘abcDudeabc’
x.strip(‘abc’)
‘Dude’

x = ‘111Dude222’

only from the beginning of the string

x.lstrip(‘1’)

‘Dude222’

only from the end of the string

x.rstrip(‘2’)

‘111Dude’

leaves unchanged if not found

x.lstrip(‘2’)

‘111Dude222’

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
What are the **2** **methods for checking whether a string starts or ends with a character or string**?
**x.startswith( )** and **x.endswith()** syntax: **x.startswith(string, beg, end)** returns: **Boolean** examples: x = "Tool" x.startswith("T") True x.startswith("t") False x.endswith("l") True x.endswith("T") False
26
What are the **3 methods for checking whether a string is numeric,** their syntax and their differences?
**isdecimal()**, **isdigit()** and **isnumeric()** = all return Boolean string type: return per method **0-9 digits** ( '0123') : True True True **fractions and superscripts** ('⅔', '2²') : False True True **Roman numerals** (examples) : False False True = so basically: isdecimal() \< isdigit() \< isnumeric() examples: ``` x = '123' y1 = '⅔' y2 = '2²' ``` x.isdecimal() True x.isdigit() True x.isnumeric() True y1.isdecimal() False y1.isdigit() True y1.isnumeric() True y2.isdecimal() False y2.isdigit() True y2.isnumeric() True z2 = '\u2160' unicocde version of a Roman numeral (U+2160 - U+2188) z2.isdecimal() False z2.isdigit() False z2.isnumeric() True
27
What are the **2 methods for** **checking whether the characters of a string are alphabetic or alphanumeric?**
**x.isalpha()** and **x.isalnum()** = isalpha() - only alphabetic = isalnum() - alphabetic or numeric ``` a = 'abc' b = '123' c = 'abc123' d = 'a b c' e = '?' f = '' # an empty string ``` a.isalpha() True a.isalnum() True b.isalpha() False b.isalnum() True c.isalpha() False c.isalnum() True d.isalpha() False d.isalnum() False e.isalpha() False e.isalnum() False f.isalpha() False f.isalnum() False
28
What is the **method for checking whether a string contains only whitespaces**?
**x.isspace()** ``` x = 'abc' y = 'a b c' z = ' ' ``` x.isspace() False y.isspace() False z.isspace() True
29
What are the **3 methods for checking the letter case of a string**?
**x.isupper()**, **x.islower()** and **x.istitle()** ``` x = 'the new tool album' y = 'THE NEW TOOL ALBUM' z = 'The New Tool Album' ``` x.isupper() False x.islower() True x.istitle() False y.isupper() True y.islower() False y.istitle() False z.isupper() False z.islower() False z.istitle() True
30
What are the **7** **basic math operations with numbers** and their **order of evaluation** (priority)?
1. addition: **1 + 2 = 3** 2. substraction: **5 - 1 = 4** 3. multiplication: **2 \* 3 = 6** 4. float division: **3 / 2 = 1.5** 5. integer division: **3 // 2 = 1** 6. remainder after division (modulo): **5 % 2 = 1** 7. raising to a power: **4 \*\* 2 = 16** Highest priority: raising to a power Medium priority: division, multiplication and modulo Low priority: addition and subtraction
31
How to **convert between numeric types**?
**int(1.5)** #result is 1 **float(2)** #result is 2.0
32
What are the **4 useful functions for working with numbers**?
**abs**(5) = 5, **abs**(-5) = 5 **min**(1, 2, 7, 8) = 1 **max**(1, 2, 5) = 5 **pow**(3, 2) = 9
33
What are the **3 main Boolean (logical) operators**?
**AND** means that both operands should be True in order to get the expression evaluated as True (1 == 1) and (2 == 2) # result is True; When using **OR**, it is enough if only one expression is True, in order to have True as the final result (1 == 1) or (2 == 2) # result is True; using the **NOT** operator means denying an expression not(1 == 1) #result is False; not(1 == 2) #result is True; **# these values always evaluate to False:** None, ‘’, 0, 0.0, 0L, 0j, empty string, empty list, empty tuple, empty dictionary examples: bool(None) #returns False bool(0) #returns False bool(2) #returns True bool("router") #returns True
34
**What is a list** and what are 2 main rules for creating it?
= a list is an indexed sequence of elements separated by comma and enclosed in square brackets 1. can have any data types as elements 2. may have any number of elements
35
What is the **difference between a list and a string** and what do they have in common?
Lists are mutable whereas strings are immutable. We can use the len() function, indexing and slicing for both.
36
Can min() and max() functions be used with lists?
Yes, under the condition that all elements are the same data type.
37
037 How to find out whether an element is part of a list?
Using the **x in list** or **x not in list** method list = [1,2,3] 3 in list True 4 in list False
38
038 What are the 2 basic operations with lists?
Concatenation and multiplication. ``` list1 = [1,2,3] list2 = [4,5,6] ``` list1 + list2 [1, 2, 3, 4, 5, 6] list2 + list1 [4, 5, 6, 1, 2, 3] list1 \* 3 [1, 2, 3, 1, 2, 3, 1, 2, 3]
39
039 How to add an item to the end of the list?
Using the **list.append()** method. list = [1,2,3] list.append(4) [1, 2, 3, 4]
40
040 How to delete a list or remove an item with specific index?
Using the **del** method. list = [1,2,3] **del list[1]** removes the item with specified index list [1,3] **del list** deletes the whole list list
41
041 What are the **2 methods of removing an element of a list** and the difference between them?
**list.pop()** and **list.remove()** list = [1,2,3] **list.pop()** removes and returns the last element 3 list [1,2] **list.pop(1)** removes and returns character with the index in brackets 2 list [1] list = [1,2,1,3] removes the first item of the specified value **list.remove(1)** list [2,1,3] The difference is that pop removes and returns and remove only removes and needs an index.
42
042 Which method inserts an element at particular index in a list and what's its syntax?
* *list.insert()** syntax: list.insert(index, value) list = [1,2,3] **list.insert(2,4)** # inserts number 4 at the index 2 list [1,2,4,3] **list.insert(1, 'word')** list [1, 'word', 2, 4, 3]
43
043 Which method appends a list to the end of another list?
**list1.extend(list2)** ``` list1 = [1,2,3] list2 = ['a','b','c'] ``` list1.extend(list2) # appends list2 at the end of the list1 list1 [1, 2, 3, 'a', 'b', 'c']
44
044 How to find index of an item in a list?
**list.index()** list = [1, 2, 3, 'a', 'b', 'c'] list.index('a') 3
45
045 How to count how many times an element is in a list?
**list.count()** list = [1,2,1,3] list.count(1) 2
46
046 What are the 3 methods to sort a list in ascending or descending order?
``` **list.sort()**, **list reverse()** # sorting in ascending / descending order, works only for the same data types # modifies an existing list ``` list = [1,2,1,3] list.sort() list [1, 1, 2, 3] list.reverse() list [3, 2, 1, 1] ``` or **sorted()** # returns a new list with sorted elements ``` list = [3,1,4,5,2] sorted(list) [1, 2, 3, 4, 5] sorted(list, reverse = True) [5, 4, 3, 2, 1]
47
047 Which 4 built-in data types are subscriptable (can be indexed)?
**string**"tool"[3] == "l" **list** [1, 2, 3, 4][3] == 4 **tuple** (1, 2, 3, 4)[3] == 4 **dictionary** {"a":1, "b":2, "c":3}["c"] == 3
48
048 What is a set and what are its 3 main characteristics?
= **an unordered collection of unique elements enclosed in curly brackets** it does not allow duplicates a set itself may be modified, but the elements contained in the set must be of an immutable type sets are not subscriptable =\> cannot be indexed
49
049 What are the **3 ways of creating a set**?
1. **creating set from a list** list = [1, 2, 3, 1, 2, 4] set(list) {1, 2, 3, 4} 2. **creating set from a string** set('tool') {'t', 'o', 'l'} 3. **creating using the curly braces {}** set = {11, 12, 13, 13, 14, 14} set {11, 12, 13, 14}
50
050 How to find out the length of a set and whether it contains an element or not?
Using the **len()** function: set = {1, 2, 3, 4, 5} len(set) 5 Using the **X in set** and **X not in set** functions set = {1, 2, 3} 2 in set True 4 in set False 4 not in set True
51
051 How to **add or remove element of a set**?
Using the **set.add()** and **set.remove()** methods set = {1, 2, 3} **set.add(****4****)** set {1, 2, 3, 4} **set.remove(****3****)** set {1, 2, 4}
52
052 What are **3 basic operations with sets**?
**set.intersection()**, **set.difference()** and **set.union()** ``` set1 = {1, 2, 3, 4} set2 = {3, 5, 8} ``` set1.intersection(set2) # identifying common elements of two sets {3} set2.intersection(set1) # works both ways {3} set1.difference(set2) # element that set1 has but set2 doesn't have {1, 2, 4} set2.difference(set1) # the opposite {8, 5} set1.union(set2) # includes each element just once {1, 2, 3, 4, 5, 8}
53
053 What does **set.pop() method** do?
Removes and returns a random element. set = {1,2,3} **set.pop()** 1 set {2, 3}
54
054 Which method can be used to empty a set?
**set.clear ()** set = {1,2,3} set.clear() set set() # empty set
55
055 What are **frozen sets** and which methods and operations are allowed with them and which not?
= **immutable sets =\> therefore can be elements of sets** ``` list1 = [1, 2, 3, 4] list2 = [3, 4, 7] ``` ``` fs1 = frozenset(list1) fs2 = frozenset(list2) ``` fs1 frozenset({1, 2, 3, 4}) fs2 frozenset({3, 4, 7}) type(fs1) **fs.add(), fs.remove(), fs.pop() or fs.clear() don't work** **intersection, difference and union are available as they don't modify** fs1.intersection(fs2) frozenset({3, 4}) fs1.difference(fs2) frozenset({1, 2}) fs1.union(fs2) frozenset({1, 2, 3, 4, 7})
56
056 What is **tuple**?
Tuples are **ordered collections of non-unique elements enclosed in parenthesis** =\> immutable lists with indexes and duplicates allowed.
57
057 How do we create **a tuple with single element**?
It has to be created **with comma**, otherwise it will be an integer or string. my\_tuple = (9) type (my\_tuple) my\_tuple = ('f') type(my\_tuple) **my\_tuple = (9,)** type(my\_tuple)
58
058 What is **tuple packing and unpacking**?
**Packing:** Wherever python expects a single value, if multiple expressions are provided, separated by commas, they are automatically **packed** into a tuple. Parentheses can be omitted when assigning a tuple of values to a single variable. ``` julia = ("Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia") # or equivalently julia = "Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia" ``` print(julia[4]) 2009 **Unpacking:** Python also has a very powerful **tuple assignment** feature that allows a tuple of variable names on the left of an assignment statement to be assigned values from a tuple on the right of the assignment. Another way to think of this is that the tuple of values is **unpacked** into the variable names. Naturally, _the number of variables on the left and the number of values on the right have to be the same_. julia = "Julia", "Roberts", 1967, "Duplicity", 2009, "Actress", "Atlanta, Georgia" name, surname, birth\_year, movie, movie\_year, profession, birth\_place = julia
59
059 Can unpacking be done if the number of values in the tuple doesn't equal the number of variables on the left?
**Yes, using an asterisk to collect the remaining values as a list:** fruits = ("apple", "banana", "cherry", "strawberry", "raspberry") (green, yellow, \*red) = fruits green 'apple' red ['cherry', 'strawberry', 'raspberry'] (green, \*yellow, red) = fruits yellow ['banana', 'cherry', 'strawberry'] red 'raspberry'
60
060 What is **direct assignment** using tuples?
= assigning multiple values to multiple variables using one statement (a, b, c) = (10, 20, 30) a 10
61
061 What are the 2 basic operations, 3 functions and 2 methods to use with tuples?
operations: **concatenation** and **multiplication** functions: **len()**, **min()**, **max()** methods: **del** tuple and x **in / not in** tuple
62
062 What is the **difference between compiler and interpreter**?
An **interpreter** reads a high-level program and executes it, meaning that it does what the program says. It processes the program a little at a time, alternately reading lines and performing computations. ![]() A **compiler** reads the program and translates it completely before the program starts running. In this case, the high-level program is called the **source code**, and the translated program is called the **object code** or the **executable**. Once a program is compiled, you can execute it repeatedly without further translation. ![]() Many modern languages use both processes. They are first compiled into a lower level language, called **byte code**, and then interpreted by a program called a **virtual machine**. Python uses both processes, but because of the way programmers interact with it, it is usually considered an interpreted language.
63
063 What are **iterables**?
Iterables are containers that can store multiple values and are capable of returning them one by one. Iterables can store any number of values. In Python, the values can either be the same type or different types. Python has several types of iterables: strings, lists, tuples and sets.
64
064 Is it possible to **create an empty list**?
Yes, simply by empty brackets: list = []
65
065 How to check whether a number is divisible by another?
Using the modulus operator. If it equals zero, it is divisible: x % y = 0
66
066 What value is printed when the following statement executes? ## Footnote **print(18.0 // 4)**
**4.0** even though it truncates, it produces a floating point result because 18.0 is a float
67
067 Can both single quote and double quotes be part of one string?
Yes, enclosed in triple quotes: print('''"Oh no", she exclaimed, "Ben's bike is broken!"''')
68
068 What will be the result of the following operation: ## Footnote **print(2 \*\* 3 \*\* 2)**
The right-most \*\* operator gets done first! print(2 \*\* 3 \*\* 2) 512 Parenthesis has to be used for the correct result: print((2 \*\* 3) \*\* 2) 64
69
069 What's the other way of incrementing and decrementing variable? ## Footnote **x = x + 1** **x = x - 1**
**x += 1** **x -= 1**
70
070 What are the results of: ## Footnote **12 / 15 = ?** **12 // 15 = ?** **12 % 15 = ?**
**0.8** **0** **12**
71
071 How to find and replace text in bulk in Pycharm?
1. Ctrl + F 2. type the text 3. Ctrl + Alt + Shift + J 4. type the new text 5. click somewhere
72
072 What are the **3 kinds of errors** that can occur in a program?
1. **syntax error** **syntax** of a [computer language](https://en.wikipedia.org/wiki/Computer_language) is the set of rules that defines the combinations of symbols that are considered to be correctly structured [statements](https://en.wikipedia.org/wiki/Statement_(computer_science)) or [expressions](https://en.wikipedia.org/wiki/Expression_(computer_science)) in that language 2. **runtime error** **runtime**, **run time**, or **execution time** is the final phase of a [computer program](https://en.wikipedia.org/wiki/Computer_program)'s [life cycle](https://en.wikipedia.org/wiki/Program_lifecycle_phase), in which the code is being [executed](https://en.wikipedia.org/wiki/Execution_(computing)) on the computer's [central processing unit](https://en.wikipedia.org/wiki/Central_processing_unit) (CPU) as [machine code](https://en.wikipedia.org/wiki/Machine_code). In other words, "runtime" is the running phase of a program. A [runtime error](https://en.wikipedia.org/wiki/Runtime_error_detection) is detected after or during the execution (running state) of a program, whereas a [compile-time](https://en.wikipedia.org/wiki/Compile_time) error is detected by the [compiler](https://en.wikipedia.org/wiki/Compiler) before the program is ever executed. [Type checking](https://en.wikipedia.org/wiki/Type_checking), [register allocation](https://en.wikipedia.org/wiki/Register_allocation), [code generation](https://en.wikipedia.org/wiki/Code_generation_(compiler)), and code optimization are typically done at compile time, but may be done at runtime depending on the particular language and compiler. Many other runtime errors exist and are handled differently by different [programming languages](https://en.wikipedia.org/wiki/Programming_language), such as [division by zero](https://en.wikipedia.org/wiki/Division_by_zero) errors, domain errors, [array subscript out of bounds](https://en.wikipedia.org/wiki/Bounds_checking) errors, [arithmetic underflow](https://en.wikipedia.org/wiki/Arithmetic_underflow) errors, several types of underflow and [overflow](https://en.wikipedia.org/wiki/Overflow_(disambiguation)) errors, and many other runtime errors generally considered as software bugs which may or may not be caught and handled by any particular computer language. 3. **semantic error** In [computer programming](https://en.wikipedia.org/wiki/Computer_programming), a **semantic** or **logic error** is a [bug](https://en.wikipedia.org/wiki/Software_bug) in a program that causes it to operate incorrectly, but not to terminate abnormally (or [crash](https://en.wikipedia.org/wiki/Crash_(computing))). A logic error produces unintended or undesired output or other behaviour, although it may not immediately be recognized as such. Logic errors occur in both [compiled](https://en.wikipedia.org/wiki/Compiler) and [interpreted](https://en.wikipedia.org/wiki/Interpreter_(computing)) languages. Unlike a program with a [syntax error](https://en.wikipedia.org/wiki/Syntax_error), a program with a logic error is a valid program in the language, though it does not behave as intended. Often the only clue to the existence of logic errors is the production of wrong solutions, though [static analysis](https://en.wikipedia.org/wiki/Static_program_analysis) may sometimes spot them.
73
073 What are the **2 main differences between a syntax error and a runtime error**?
1. If the error message mentions SyntaxError, the problem has to do with syntax: the structure of the code, the punctuation, etc. 2. If the program runs partway and then crashes, you know the problem is a runtime error. Programs with syntax errors don’t execute even one line.
74
074 What is a test case?
A **test case** is a set of input values for the program, together with the output that you expect the program should produce when it is run with those particular inputs. example: Test Case: Input: 2, 3 Expected Output: 5
75
075 Can **int() function** be used to convert more values at the same time?
No, it can take only one parameter at a time.
76
076 What is a **module**?
**= a file containing Python definitions and statements intended for use in other Python programs** There are many Python modules that come with Python as part of the **standard library**. Providing additional functionality through modules allows us to only use the functionality we need when we need it, and it keeps our code cleaner.
77
077 What are the **3 ways of importing a module or part of it**?
1. **import morecode** = imports everything in morecode.py. To invoke a function f1 that is defined in morecode.py, we would write morecode.f1() 2. **import morecode as mc** = giving the imported module an alias (a different name. To invoke a function f1 we would write mc.f1() 3. **from morecode import f1** = importing SOME of the functionality from a module, and making those objects be part of the current module’s namespace. Function f1 can be then invoke without referencing morecode again, simply by f1()
78
078 How do we create **a random dice throw**?
By importing the random module and invoking its randrange() function: **import random** **dice\_throw = random.randrange(****1****,****7****)** **print(dice\_throw)**
79
079 What does the **randrange() function** do and what's its syntax?
It generates an integer between its lower and upper argument where the lower bound is included, but the _upper bound is excluded_. Third argument can be used to limit the results to multiplications of it. import random random.randrange(0,20,5) this will be randomly generating numbers 0, 5, 10 and 15
80
080 What does **random() function** do and what's the syntax?
It **returns a floating point number in the range [0.0, 1.0)** — the square bracket means “closed interval on the left” and the round parenthesis means “open interval on the right”. In other words, 0.0 is possible, but all returned numbers will be strictly less than 1.0. It is usual to *scale* the results after calling this method, to get them into a range suitable for our application. import random random.random()
81
081 What is the **difference between atomic and collection data types**?
**Atomic data types** because their values are not composed of any smaller parts. They cannot be broken down. Types that are comprised of smaller pieces are called **collection data types**. Depending on what we are doing, we may want to treat a collection data type as a single entity (the whole), or we may want to access its parts. This ambiguity is useful.
82
082 What is printed by the following statement? L = [0.34, '6', 'SI106', 'Python', -2] print(len(L[1:-1]))
3
83
083 What's the **inverse method for string split** and its syntax?
It's the join() method for lists and it's syntax is following: **‘x’.join(list)** where _x is the desired separator_ and list is the name of the source list wds = ["red", "blue", "green"] ``` glue = ';' s = glue.join(wds) ``` print(s) print(wds) print("\*\*\*".join(wds)) print("".join(wds)) red;blue;green ['red', 'blue', 'green'] red\*\*\*blue\*\*\*green redbluegreen
84
084 What is the basic statement working with iteration and its syntax?
For loop: for in : loop body # indented
85
085 If you have a pixel whose RGB value is (50, 0, 0), what color will this pixel appear to be?
**dark red** The closer the values are to 0, the darker the color will appear.
86
086 What are **iterator and iterable**?
The **iterable** is the object that is iterated over. Generally, this object does not change while the for loop is being executed. The **iterator** (loop) variable is the variable which stores a portion of the iterable when the for loop is being executed. Each time the loop iterates, the value of the iterator variable will change to a different portion of the iterable.
87
087 What is **traversing** a string or a list?
**Traversing a string or a list** means accessing each character in the string or item in the list, one at a time.
88
088 What is **short-circuit boolean evaluation?**
**For some cases of OR and AND operands, only the first operand can be evaluated:** OR If it is True, Python doesn't check the second operand and evaluates the whole expression as True. AND If it is False, Python doesn't check the second operand and evaluates the whole expression as False.
89
089 In the following program, **which version of the condition can end up with runtime error** and why? ``` total\_weight = int(input('Enter total weight of luggage:')) num\_pieces = int(input('Number of pieces of luggage?')) ``` **a) if num\_pieces != 0 and total\_weight / num\_pieces \> 50:** print('Average weight is greater than 50 pounds -\> $100 surcharge.') **b) if total\_weight / num\_pieces \> 50 and num\_pieces != 0:** print('Average weight is greater than 50 pounds -\> $100 surcharge.') print('Luggage check complete.')
It's **b)**, because the left part of the statement is evaluated first and in case user's input equals zero, it causes runtime error division by zero. In a), if user inputs zero, the second part of the statement is not evaluated.
90
090 What will happen with this program if user presses Enter without typing a response? yesno = input('Enter Yes or No:') if yesno[0] == 'Y' and len(yesno) \> 0: print('Yes!')
It will result in a runtime crash with the following exception: **IndexError: string index out of range** = this error occurs when a character is retrieved by an index that is outside the range of string value
91
091 What are the outputs of the following operators: print(**'a' in 'a'**) print(**'apple' in 'apple**') print(**'' in 'a'**) print(**'' in 'apple'**)
A string is a substring of itself, and the empty string is a substring of any other string, therefore: True True True True
92
092 What's the output of the following statement: ## Footnote **print("a" in ["apple", "absolutely", "application", "nope"])**
**False** Python is checking whether or not an element of the list is the string “a” - nothing more or less than that.
93
093 What are the 3 kinds of operators and what's the correct precedence (order of priority) of them?
LevelCategoryOperators7(high)exponent\*\*6multiplication\*,/,//,%5addition+,-4relational==,!=,\<=,\>=,\>,\<3logicalnot2logicaland1(low)logicalor
94
094 What are **binary, unary and chained conditionals**?
**Binary** = classic if / else statement **Unary** = if statement without else **Chained** = if statement with any number of elif statements and one (optional) final else
95
095 **What is the best set of conditonal statements** in case you want to keep track of all the words that have the letter ‘t’ in one variable and in a separate variable you want to keep track of all the words that have the letter ‘z’ in them? a) **if + else** b) **if + elif** c) **if + if** d) **if + elif + else**
**It's c) if + if** If it was b) if + elif, the words with both letters in them wouldn't be properly counted by both variables, only by one of them.
96
096 Can multiple items of a list be updated at once?
Yes, by combining assignment with the slice operator: list = [1,2,3,4,5,6,7,8,9,0] **list[****1****::****2****] =** **len****(list[::****2****]) \* [****'b'****]** print(list) [1, 'b', 3, 'b', 5, 'b', 7, 'b', 9, 'b'] **list2 = [****'a'****,****'b'****,****'c'****,****'d'****,****'e'****]** list[::2] = list2 print(list) ['a', 'b', 'b', 'b', 'c', 'b', 'd', 'b', 'e', 'b']
97
097 What does assigning empty list to a part of another list do?
It removes the respective elements: alist = ['a', 'b', 'c', 'd', 'e', 'f'] alist [1:3] = [] print (alist) ['a', 'd', 'e', 'f']
98
098 How can we insert elements into a certain part of a list without removing or updating other elements?
By using slicing with the same number for beginning and end index: alist = ['a', 'd', 'f'] **alist[1:1] = ['b', 'c']** print(alist) ['a', 'b', 'c', 'd', 'f'] **alist[4:4] = ['e']** print(alist) ['a', 'b', 'c', 'd', 'e', 'f']
99
099 How to test whether two variables point to the same object?
The ***is*** **operator** will return true if the two references are to the same object: ``` a = 'banana' b = 'banana' ``` **print****(a****is****b)** print(id(a)) print(id(b)) True 1884027991920 1884027991920
100
100 Can two different lists have the same ID?
**No.** They need to have different ids so that mutations of list a do not affect list b. ``` X = [1,2,3] Y = [1,2,3] ``` print(X is Y) print(X == Y) print(id(X)) print(id(Y)) False True 1419424289280 1419424526336
101
101 What is **alias** used for?
If we assign one variable to another, both variables refer to the same object. For example: because the same list has two different names, a and b, we say that it is **aliased**. Changes made with one alias affect the other: a = [81,82,83] b = [81,82,83] **print(a is b)** b = a * *print(a == b)** * *print(a is b)** b[0] = 5 **print(a)** False True True [5, 82, 83]
102
102 How do we **clone lists**?
By using the slice operator: a = [81,82,83] **b = a[:]** print(a == b) print(a is b) b[0] = 5 print(a) print(b) True False [81, 82, 83] [5, 82, 83]
103
103 What is a **raw string** and how do we create it?
Unlike a regular string, **a raw string treats the backslashes (****\****) as literal characters**. When we prefix a string with the letter r or R such as r'...' and R'...', that string becomes a raw string. Raw strings are useful when you deal with strings that have many backslashes, for example, [regular expressions](https://www.pythontutorial.net/python-regex/python-regular-expressions/) or directory paths on Windows.
104
103 What is a **raw string** and how do we create it?
Unlike a regular string, **a raw string treats the backslashes (****\****) as literal characters**. When we prefix a string with the letter r or R such as r'...' and R'...', that string becomes a raw string. Raw strings are useful when you deal with strings that have many backslashes, for example, [regular expressions](https://www.pythontutorial.net/python-regex/python-regular-expressions/) or directory paths on Windows.
105
105 What is **with statemen**t in Python?
The **with statement** in Python is **used for resource management and exception handling**. For example, the statement ensures that the file stream process doesn't block other processes if an exception is raised, but terminates properly. Syntax: **with open('mydata.txt', 'r') as md:** for line in md: print(line) continue on with other code
106
106 What is **CSV format**?
CSV stands for **Comma Separated Values**. If weprint out tabular data in CSV format, it can be easily imported into other programs like Excel, Google spreadsheets, or a statistics package (R, stata, SPSS, etc.).
107
107 How can we _easily_ create a list with 10 zeros in it?
zero\_list = [0] \* 10
108
108 What is a **dictionary**?
A mapping type of mutable data collection stored in key : value pairs, where keys have to be unique.
109
109 What is the syntax of **adding an item to a dictionary**?
**dictionary [key] = value**
110
110 How do we **delete an item from a dictionary**?
By using the del function: ## Footnote **del dictionary [key]**
111
111 Can we use len() function with dictionaries?
Yes, it counts the number of key : value pairs: inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} **print****(****len****(inventory))** 4
112
112 What's the **difference between using dict[key] and get() method** to access the items in dictionary?
If key is not found, dict[key] raises the KeyError exception, whereas get() method returns None.
113
113 What are the **4 basic built-in methods that can be used with dictionaries,** what is their syntax and what do they return?
It's keys(), values(), items() and get(). Syntax: **dict.keys()** **dict.values()** **dict.items()** **dict.get(key)** or (for non-existing key): **dict.get(key,value)** The first three return special class type and get returns either None (for non-existing key with no value specified) or a type based on the type of the value (for non-existing key with a value specified). inventory = {'apples': 430, 'bananas': 312, 'oranges': 525, 'pears': 217} inventory['pears'] = inventory['pears'] + 200 print(inventory.keys()) dict\_keys(['apples', 'bananas', 'oranges', 'pears']) print(inventory.values()) dict\_values([430, 312, 525, 417]) print(inventory.items()) dict\_items([('apples', 430), ('bananas', 312), ('oranges', 525), ('pears', 417)]) print(inventory.get('kiwis',123)) 123
114
114 What is a **docstring** and how can we retrieve it?
**= a string used to document a Python module, class, function or method**, so programmers can understand what it does without having to read the details of the implementation. It is right under the header and it is enclosed in tripple brackets. Also, it is a common practice to generate online (html) documentation automatically from docstrings. Syntax for retrieval: **object\_name.\_\_doc\_\_** with double underscores for example: ``` def hello(): **"""This function says hello and greets you"""** print("Hello") print("Glad to meet you") ```
115
115 What's the syntax for a function's parameters or results **type annotation**?
def function\_name (parameter: type, parameter : type..) → type of result: example: ``` def add**(x: int, y: int) -\> int:** """Returns the sum of ‘x’ and ‘y’""" ```
116
116 How does Python treat type annotations in functions?
**Python ignores them.** The interpreter does not check that the values passed to a function are the expected types and does not cause the returned value to be converted to the expected type.
117
117 What happens when the following is executed? **def display(msg: str):** **"""Displays ‘msg’ on the screen"""** **print(msg + 2)** **display(2.5)** a) The value 4.5 is displayed on the screen. b) The value 2.52 is displayed on the screen. c) A crash occurs because 2.5 is not a string. d) A crash occurs because the expression 'msg + 2' illegally attempts to concatenate a str and an int
a) Python ignores the ': str' annotation and returns the sum of msg (the float 2.5) + 2.
118
118 What are the **4 rules of variable scope**?
1. Python is divided into **object space** and **name space**. 2. **All objects** live in object space. 3. The name space is divided into **nested spaces: built-in, global and local**. 4. When looking for a variable we **start at the name space that contains the expression** we are evaluating and **then go outward**.
119
119 What is **a function's side effect** and what are the 3 ways to have it?
It's **a lasting effect that occurs in a function**, but not through its return value. 1. **Printing out a value**. This doesn’t change any objects or variable bindings, but it does have a potential lasting effect outside the function execution, because a person might see the output and be influenced by it. 2. **Changing the value of a mutable object**. 3. **Changing the binding of a global variable**.
120
120 What is **a stack frame**?
A frame that keeps track of the values of local variables during a function execution, and where to return control when the function execution completes. When one function call returns its data to its caller, then its stack frame is removed from the stack. New stack frames are added and removed (along with their associated data) until the bottommost stack frame, sometimes called the **module frame**, gets the data it needs.
121
121 Floating point arithmetic is not always exactly accurate. What's **the safe way to test floating point numbers for equality**?
**if abs(x - y) \< 0.0001:** if x is approximately equal to y (the number of zeros determines the tolerance)
122
122 What is **a neat way to swap values between variables**?
Using tuple assignment: a = 1 b = 2 **(a, b) = (b, a)** print(a, b) 2 1
123
123 How does **tuple unpacking into iterator variables** work?
Multiple assignment with unpacking is particularly useful when iterating through a list of tuples. We can unpack each tuple into several loop variables. For example: * *authors = [('Paul', 'Resnick'), ('Brad', 'Miller'), ('Lauren', 'Murphy')]** * *for first\_name, last\_name in authors:** * *print("first name:", first\_name, "last name:", last\_name)** first name: Paul last name: Resnick first name: Brad last name: Miller first name: Lauren last name: Murphy
124
124 What is **enumerate function** for and what's its syntax?
It takes a sequence as input and returns a sequence of tuples. In each tuple, the first element is an integer representing the index and the second is an item with that index original sequence: fruits = ['apple', 'pear', 'apricot', 'cherry', 'peach'] * *for idx, fruit in enumerate(fruits):** * *print(idx, fruit)** 0 apple 1 pear 2 apricot 3 cherry 4 peach
125
125 If we want a function to return two values, contained in variables x and y, which 3 methods will work?
**return [x, y]** **return (x, y)** **return x, y**
126
126 How does **unpacking tuples as arguments to function** work?
**We can do it by using the \* notation inside a parameter list:** ``` def add(x, y): return x + y ``` print(add(3, 4)) z = (5, 4) **print(add(\*z))** this line will cause the values to be unpacked
127
127 What is wrong with the following function definition (it's not about the indentation): ## Footnote **def addEm(x, y, z):** **return x+y+z** **print('the answer is', x+y+z)**
**We should not have any statements in a function after the return statement.** Once the function gets to the return statement it will immediately stop executing the function.
128
128 What will the following function return? ## Footnote **def addEm(x, y, z):** **print(x+y+z)**
The value **None**.
129
129 What is the **general syntax to iterate over a list using while loop**?
**index = 0** **while index \< len(myList):** **element = myList[index]** **# statement(s)** **• element** contains value of the this element in the list. For each iteration, next element in the list is loaded into this variable with the changing index. **• myList** is the Python List over which we would like to traverse through **• statement(s)** are block are set of statement(s) which execute for each of the element in the list
130
130 What is **a listener loop**?
It's a pattern inside the while loop where there is a function call to get user input. The loop repeats indefinitely, until a particular input is received.
131
131 What is **a sentinel value**?
= **a value used to signal the end of the loop**
132
132 What do the keywords “**break**” and “**continue**” do with the flow of iteration?
**Break** allows the program to immediately ‘break out’ of the loop, regardless of the loop’s conditional structure. This means that the program will then skip the rest of the iteration, without rechecking the condition, and just goes on to the next code that exists after the whole while loop. **Continue** allows the program to immediately “continue” with the next iteration. The program will skip the rest of the iteration, recheck the condition, and maybe does another iteration depending on the condition set for the while loop.
133
133 What is an **optional parameter** and **default value** and how do we create them?
Sometimes it is convenient to have **optional parameters** that can be specified or omitted. When an optional parameter is omitted from a function invocation, the formal parameter is bound to a **default value**. When the optional parameter is included, then the formal parameter is bound to the value provided. Optional parameters are convenient when a function is almost always used in a simple way, but it’s nice to allow it to be used in a more complex way, with non-default values specified for the optional parameters. **When defining a function, you can specify a default value for a parameter. That parameter then becomes an optional parameter when the function is called. The way to specify a default value is with an assignment statement inside the parameter list.** Consider the following code, for example: initial = 7 def f(x, **y = 3**, **z = initial**): print(x,y,z) f(2) 2 3 7
134
134 What are **2 tricky things about default values** of optional parameters?
1. The default value is **determined at the time that the function is defined**, not at the time that it is invoked. So in the example below, the value of initial at the time of invocation is 7, not 10! initial = 7 def f(x, **y = 3**, **z = initial**): print(x,y,z) initial = 10 f(2) 2 3 7 2. **If the default value is set to a mutable object**, such as a list or a dictionary, that object will be shared in all invocations of the function. **It can get very confusing**, for example: ``` def f(a, L=[]): L.append(a) return L ``` print(f(1)) print(f(2)) print(f(3)) print(f(4, ["Hello"])) print(f(5, ["Hello"])) [1] [1, 2] [1, 2, 3] ['Hello', 4] ['Hello', 5] In the first three cases, the list L is changed with every invocation and it's always the same list. However on the last two lines two different copies of a list with ‘Hello’ in it are provided as optional parameter, so the function returns a different list each time. **It is therefore recommended not to use mutable objects as default values.**
135
135 What is **keyword-based parameter passing**?
When there are several optional parameters, it is a way to provide a value for one of the later parameters while not providing a value for the earlier ones. The following rules must be followed: 1. **In a function call, keyword arguments must follow positional arguments.** 2. **All the keyword arguments passed must match one of the arguments accepted by the function and their order is not important.** This also includes non-optional arguments (like in “parrot(voltage = 1000)” in the valid examples below). 3. **No argument may receive a value more than once.** (like in “parrot(110, voltage = 220)” in the invalid examples below) For example this function: **def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):** can be called in any of the following ways: **parrot(1000)** # 1 positional argument **parrot(voltage=1000)** # 1 keyword argument **parrot(voltage=1000000, action='VOOOOOM')** # 2 keyword arguments **parrot(action='VOOOOOM', voltage=1000000)** # 2 keyword arguments **parrot('a million', 'bereft of life', 'jump')** # 3 positional arguments **parrot('a thousand', state='pushing up the daisies')** # 1 positional, 1 keyword but all the following calls would be invalid: **parrot()** # required argument missing **parrot(voltage=5.0, 'dead')** # non-keyword argument after a keyword argument **parrot(110, voltage=220)** # duplicate value for the same argument **parrot(actor='John Cleese')** # unknown keyword argument
136
136 What is a **lambda expression** and what is its syntax?
It's **an alternative notation for creating a function**. The syntax of a lambda expression is the word “lambda” followed by parameter names, separated by commas but not inside (parentheses), followed by a colon and then an expression: **func = lambda arguments: expression**
137
137 How does **lambda function return values**?
In the typical function, we have to use the keyword return to send back the value. **In a lambda function**, that is not necessary - **whatever is placed after the colon is what will be returned**.
138
138 Knowing the syntax of the replace method for strings, **how can we remove two different characters at once**?
By passing the result of one removal as argument to another removal: **‘string’.replace('x', '').replace('y', '')** The thing to the left of the period can be any expression, not just a variable name or value. It can even be a return value from some other function call or another method invocation. It can actually go on like that as a nested method invocation: **print****(****"This is a sentence"****.replace(****"s"****,****""****).replace(****"t"****,** **""****).replace(****"n"****,****""****))** **Thi i a eece**
139
139 What are the **parameters of sorted() function**?
sorted **(iterable, reverse = True, key = function)** It takes three parameters from which two are optional. ***Iterable:*** sequence (list, tuple, string) or collection (dictionary, set, frozenset) or any other iterator that needs to be sorted. ***Reverse*** **(optional):** If True, then the iterable would be sorted in reverse (descending) order, by default it is set as False. ***Key*** **(optional):** A function that would serve as a key or a basis of sort comparison.
140
140 What happens when sorted() method is given a key function with 2 parameters?
Syntax error: **The key function passed to sorted** **must always take just one parameter**.
141
141 What happens when two items are “tied” in the sort order? For example, suppose we sort a list of words by their lengths. Which five letter word will appear first?
The python interpreter will sort the tied items **in the same order they were in before the sorting**.
142
142 What is **JSON**?
**JavaScript Object Notation** JSON is an open standard file format and data interchange format that uses human-readable text to store and transmit data objects consisting of attribute–value pairs and arrays. It is a common data format with diverse uses in electronic data interchange, including that of web applications with servers.
143
143 How do we convert **JSON-formatted string** to a Python object and vice versa?
Using the json module and its 2 functions json.loads() and json.dumps(). **json.loads()** takes a string as input and produces a python object (a dictionary or a list) as output **json.dumps()** takes a python object, typically a dictionary or a list, and returns a string, in JSON format. It has a few other parameters. Two useful parameters are sort\_keys and indent. When the value True is passed for the sort\_keys parameter, the keys of dictionaries are output in alphabetic order with their values. The indent parameter expects an integer. When it is provided, dumps generates a string suitable for displaying to people, with newlines and indentation for nested lists or dictionaries.
144
144 What are **deep and shallow copies**?
Simply cloning a list using [:] is making **shallow copies** (copying a list at the highest level). When we copy a nested list, we do not also get copies of the internal lists. When performing a mutation operation on one of the original sublists, the copied version will also change, which means we need to make **deep copies**. Either using nested iteration or slicing or better with **module** **copy** and its **method deepcopy**.
145
145 What do **try, except, else and finally** do in handling exceptions?
The **try block** lets us test a block of code for errors. The **except block** lets us handle the errors. The **else block** lets us execute code when there is no error. The **finally block** lets us execute code, regardless of the result of the try- and except blocks.
146
146 What is a **class** and what is an **object**?
A **class** is a user-defined blueprint or prototype from which objects are created. Classes provide a means of bundling data and functionality together. Creating a new class creates a new type of object, allowing new instances of that type to be made. Each class instance can have attributes attached to it for maintaining its state. Class instances can also have methods (defined by their class) for modifying their state. Class creates a user-defined data structure, which holds its own data members and member functions, which can be accessed and used by creating an instance of that class. A class is like a blueprint for an object. **Some points on Python class:** * Classes are created by keyword class. * Attributes are the variables that belong to a class. * Attributes are always public and can be accessed using the dot (.) operator. Eg.: Myclass.Myattribute An **Object** is an instance of a Class. A class is like a blueprint while an instance is a copy of the class with *actual values*. It’s not an idea anymore, it’s an actual object (with class Dogs, it's like a dog of breed pug who’s seven years old). We can have many different instances (many dogs), but without the class as a guide, we would be lost, not knowing what information is required. An object consists of : * **State:** It is represented by the attributes of an object. It also reflects the properties of an object. * **Behavior:** It is represented by the methods of an object. It also reflects the response of an object to other objects. * **Identity:** It gives a unique name to an object and enables one object to interact with other objects.
147
147 What is an **object declaration** and **class instantiation**?
The same thing. **When an object of a class is created, the class is said to be instantiated.** All the instances share the attributes and the behavior of the class. But the values of those attributes, i.e. the state are unique for each object. A single class may have any number of instances.
148
148 What is the **self parameter**?
In object oriented programming, the object whose method is being called is often called "self", because the method is referring to the object itself. It can be called anything else but it's not considered good for readability. Class methods must have an extra first parameter in the method definition. We do not give a value for this parameter when we call the method, Python provides it. If we have a method that takes no arguments, then we still have to have one argument. When we call a method of this object as myobject.method(arg1, arg2), this is automatically converted by Python into MyClass.method(myobject, arg1, arg2) – this is all the special self is about.
149
149 What is the difference between **constructor**, “**\_\_init\_\_()**” method and “**\_\_new\_\_()**” method?
A **constructor** is a method which creates the object itself. In Python, this method is **\_\_new\_\_()**. A common signature of this method is: \_\_new\_\_(cls, \*args, \*\*kwargs) The function “**\_\_init\_\_()**” is called immediately **after** the object is created and is used to initialize it (to initialize attributes of an object). Generally "\_\_new\_\_()" is used to control the way an object is created. We can also use \_\_new\_\_() to initialize attributes of an object, but logically it should be inside \_\_init\_\_(). One practical use of \_\_new\_\_(), however, could be to restrict the number of objects created from a class. We see \_\_init\_\_() very often but the use of \_\_new\_\_() is rare. This is because most of the time there is no need to override it.
150
150 What does **map() function** do and what is its syntax?
**map()** function returns a map object (an iterator, not a list!) of the results after applying the given function to each item of a given iterable (list, tuple etc.) syntax: **map (function, iterable)** example: ``` def double(x): return 2\*x ``` L = [1,2,3,3,5,4,7,8,9] L2 = list(map(double,L)) print(L2)