cs workbook content Flashcards

1
Q

**If the first index is greater than or equal to the second the result is an **

Such:
»> fruit = ‘banana’
»> fruit[3:3]
What is output?

A

what string indexing does this: the result is an empty string, represented by two quotation marks:

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

when changing strings, what should you know?

A

(ig)strings are immutable in Python, it means that once a string is created, it cannot be changed or modified.

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

Python has a function called “what?” which lists all the methods available for an object.

A

function dir does what?

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

the method “what” takes a string and returns a new string with all uppercase letters.

How would I write this and know about it?

A

(ig) instead of the function syntax, upper(word), it uses the method syntax, word.upper().
The empty parentheses indicate that this method takes no argument.

word = ‘banana’
2
new_word = word.upper()
3
print(new_word)
4

BANANA

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

explain the syntax of find() and explain its paramters

A

(ig)Syntax
string.find(value, start, end)

Parameter Values
Parameter Description
value Required. The value to search for
start Optional. Where to start the search. Default is 0
end Optional. Where to end the search. Default is to the end of the string

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

The find() method returns what? if the value is not found.

A

(ig) -1

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

The method finds the first occurrence of the specified value.

A

(ig) The find() method finds the first occurrence of the specified value.

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

You will note that** startswith** requires what, so what

A

You will note that startswith requires case to match, so sometimes we’ll convert a line to lowercase using the lower method before we do any checking:
line = ‘Have a nice day’
line.startswith(‘h’)

print(line.lower())

print(line.lower().startswith(‘h’))
have a nice day
True

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

Method that makes all the letters lowercased

A

(ig) string.lower()

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

the string method **what? ** to count the number of times a string appears in a another string. How would I write this

A

(ig) string.count(‘aa’)

def countSS(word):
counter = word.count(‘ss’)
return counter

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

What is used to format an integer, floating-point number, and string

A

(anw follows the statement)What does the following: %d, %g , and %s.

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

What list method adds a new element to the end of a list, also a way to add to an empty list:

A

string.append does what and should know(don’t look on the bottom)
&raquo_space;> t = [‘a’, ‘b’, ‘c’]
»> t.append(‘d’)
»> t
[‘a’, ‘b’, ‘c’, ‘d’]

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

What list method adds the specified list elements (or any iterable) to the end of the current list.

Parameter Description
iterable Required. Any iterable (list, set, tuple, etc.)

A

What does string.extend() do? What do you use on this?

fruits = [‘apple’, ‘banana’, ‘cherry’]

points = (1, 4, 5, 9)

fruits.extend(points)

print(fruits)
[‘apple’, ‘banana’, ‘cherry’, 1, 4, 5, 9]

> > > t1 = [‘a’, ‘b’, ‘c’]
t2 = [‘d’, ‘e’]
t1.extend(t2)
t1
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

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

What list method arranges the elements of the list from low to high:

A

What does string.sort do?() do(don’t look below)

> > > t = [‘d’, ‘c’, ‘e’, ‘b’, ‘a’]
t.sort()
t
[‘a’, ‘b’, ‘c’, ‘d’, ‘e’]

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

Adding up the elements of a list is such a common operation that Python provides it as a built-in function

A

Explain and give me the connotation of using sum()

_
»> t = [1, 2, 3]
»> sum(t)
6

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

If you know the index of the element you want to delete, you can use what: modifies the list and returns the element that was removed. If you don’t provide an index, it deletes and returns the last element.

A

What does string.pop() do?

-

> > > t = [‘a’, ‘b’, ‘c’]
x = t.pop(1)
t
[‘a’, ‘c’]
x
‘b’

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

If you don’t provide an index for pop(), what happens?

A

(ig)If provide an index, it deletes and returns the last element, basically deletes the last item.

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

If you don’t need the removed value like from pop(), you can use what?

A

What does del string[] do?

-
»> t = [‘a’, ‘b’, ‘c’]
»> del t[1]
»> t
[‘a’, ‘c’]

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

If you know the element you want to remove (but not the index), you can use what?

The return value from this is None.

A

What does string.remove() do/return explanation?

> > > t = [‘a’, ‘b’, ‘c’]
t.remove(‘b’)
t
[‘a’, ‘c’]

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

NT

To remove more than one element, you can use

A

(ig) you can use del with a slice index:

> > > t = [‘a’, ‘b’, ‘c’, ‘d’, ‘e’, ‘f’]
del t[1:5]
t
[‘a’, ‘f’]

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

To convert from a string to a list of characters, you can use?

A

What does list(string) do?

> > > s = ‘spam’
t = list(s)
t
[’s’, ‘p’, ‘a’, ‘m’]

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

The list function breaks a string into individual letters. If you want to break a string into words, you can use what?

A

What does string.split() do? What uses this?

-

> > > s = ‘pining for the fjords’
t = s.split()
t
[‘pining’, ‘for’, ‘the’, ‘fjords’]

s = ‘pining for the fjords’
t = s.split()
print(t)

print(t[2])
[‘pining’, ‘for’, ‘the’, ‘fjords’]
the

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

An optional argument called a what? specifies which characters to use as word boundaries.

A

What does delimiter do?

-
The following example uses a hyphen as a delimiter:

> > > s = ‘spam-spam-spam’
delimiter = ‘-‘
t = s.split(delimiter)
t
[‘spam’, ‘spam’, ‘spam’]

> > > t = [‘pining’, ‘for’, ‘the’, ‘fjords’]
delimiter = ‘ ‘
s = delimiter.join(t)
s
‘pining for the fjords’

24
Q

A method that is the inverse of split. It takes a list of strings and concatenates the elements. This method is a string method, so you have to invoke it on the delimiter or anything else like” “ and pass the list as a parameter.

A

What does delimiter.join(string) do?

> > > t = [‘pining’, ‘for’, ‘the’, ‘fjords’]
delimiter = ‘ ‘
s = delimiter.join(t)
s
‘pining for the fjords’

25
Q

To concatenate strings without spaces, you can what as a delimiter.

A

(ig) To concatenate strings without spaces, you can use the empty string, ‘’, as a delimiter.

26
Q

In this example, Python only created one string object, and both a and b refer to it.
&raquo_space;> a = ‘banana’
»> b = ‘banana’
»> a is b
True
But when you create two lists, you get **how many objects: **
»> a = [1, 2, 3]
»> b = [1, 2, 3]
»> a is b
True or False

A

(ig) two objects, False

27
Q

An object with more than one reference has more than one name, so we say that the object is what? What should you about changing this “what”

A

(ig)An object with more than one reference has more than one name, so we say that the object is aliased.

If the aliased object is mutable, changes made with one alias affect the other:

> > > b[0] = 42
a
[42, 2, 3]

28
Q

difference between append and + operator

A

(ig) the append method modifies a list, but the + operator creates a new list:

29
Q

The method takes all items in an iterable and joins them into one string.

A string must be specified as the separator.

A

string.join(iterable)

describe and explain its parameter

Join all items in a tuple into a string, using a hash character as separator:
myTuple = (“John”, “Peter”, “Vicky”)

x = “#”.join(myTuple)

print(x)

John#Peter#Vicky

30
Q

The method adds an element to the set.

If the element already exists, the method does not add the element.

A

describe add() method, what do you use on for

-
thisset = {“apple”, “banana”, “cherry”}

thisset.add(“orange”)

print(thisset)
{‘orange’, ‘cherry’, ‘banana’, ‘apple’}

31
Q

The method removes the specified item from the set.

This method is different from the remove() method, because the remove() method will raise an error if the specified item does not exist, and the method will not.

A

Describe what uses the discard() method and the what’s special about it?

32
Q

The function returns a sorted list of the specified iterable object.

You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.

Note: You cannot sort a list that contains BOTH string values AND numeric values.

A

describe sorted()

a = (“h”, “b”, “a”, “c”, “f”, “d”, “e”, “g”)

x = sorted(a, reverse=True)

print(x)

[‘h’, ‘g’, ‘f’, ‘e’, ‘d’, ‘c’, ‘b’, ‘a’]

a = (“Jenifer”, “Sally”, “Jane”)
x = sorted(a, key=len)
print(x)

[‘Jane’, ‘Sally’, ‘Jenifer’]

33
Q

describe sorted() parameters

A

(ig)Parameter Description
iterable Required. The sequence to sort, list, dictionary, tuple etc.
key Optional. A Function to execute to decide the order. Default is None
reverse Optional. A Boolean. False will sort ascending, True will sort descending. Default is False

a = (“h”, “b”, “a”, “c”, “f”, “d”, “e”, “g”)

x = sorted(a, reverse=True)

print(x)

[‘h’, ‘g’, ‘f’, ‘e’, ‘d’, ‘c’, ‘b’, ‘a’]

a = (“Jenifer”, “Sally”, “Jane”)
x = sorted(a, key=len)
print(x)

[‘Jane’, ‘Sally’, ‘Jenifer’]

34
Q

.sort() vs sorted()

A

(ig) The sorted() function creates a new sorted list and leaves the original list unmodified.
The .sort() method sorts the original list, mutating it.

35
Q

The method sorts the list ascending by default.

You can also make a function to decide the sorting criteria(s).

A

what uses sort() method, and describe it

36
Q

What is the parameter Values of .sort()

A

(ig) Parameter Description

Syntax
list.sort(reverse=True|False, key=myFunc)

reverse Optional. reverse=True will sort the list descending. Default is reverse=False
key Optional. A function to specify the sorting criteria(s)

A function that returns the length of the value:
def myFunc(e):
return len(e)

cars = [‘Ford’, ‘Mitsubishi’, ‘BMW’, ‘VW’]

cars.sort(key=myFunc)

print(cars)

[‘VW’, ‘BMW’, ‘Ford’, ‘Mitsubishi’]

37
Q

What method returns a string where the first character is upper case, and the rest is lower case.

It uses a string

A

describe capitalize() method, and what do you use for it

38
Q

extra

It is also possible to use what when creating a new list.

A

what does/ how to use the list() constructor

thislist = list((“apple”, “banana”, “cherry”)) # note the double round-brackets
print(thislist)

39
Q

Describe set? List?

A

(ig) List is a collection which is ordered and changeable. Allows duplicate members.

Set is a collection which is unordered, unchangeable*, and unindexed. No duplicate members.
Set items are unchangeable, but you can remove and/or add items whenever you like.

40
Q

How do (+ operator) work on lists

A

(ig)Addition (+): List Concatenation
The + operator is used to concatenate two lists, meaning it joins them together.
It does not add the elements in the lists mathematically.

list1 = [1, 2, 3]
list2 = [4, 5, 6]
result = list1 + list2
print(result) # Output: [1, 2, 3, 4, 5, 6]

41
Q

How do (* operator) work on lists

A

(ig) Multiplication (*): List Repetition
The * operator repeats the list a specified number of times.
It does not multiply the elements in the list.

list1 = [1, 2, 3]
result = list1 * 3
print(result) # Output: [1, 2, 3, 1, 2, 3, 1, 2, 3]

42
Q

What function returns True if the specified object is of the specified type, otherwise False.

Parameter Description(object, type)
object Required. An object.
type A type or a class, or a tuple of types and/or classes

A

how does isinstance() works and explain it

What parameters are used?

x = isinstance(“Hello”, (str, float, int, str, list, dict, tuple))

print(x)
True

43
Q

What’s the range() syntax parameters

A

(ig) Parameter Description
start Optional. An integer number specifying at which position to start. Default is 0
stop Required. An integer number specifying at which position to stop (not included).
step Optional. An integer number specifying the incrementation. Default is 1

x = range(3, 20, 2)
for n in x:
print(n)

x = range(3, 6) for n in x:   print(n)
44
Q

The method that formats the specified value(s) and insert them inside the string’s placeholder.

The placeholder is defined using curly brackets: {}. Read more about the placeholders in the Placeholder section below.

This method returns the formatted string.

parameters:
value1, value2… Required. One or more values that should be formatted and inserted in the string.

The values are either a list of values separated by commas, a key=value list, or a combination of both.

The values can be of any data type.

What is used for this?

A

named indexes:

Describe and explain string.format(), what are use for the parameters

txt1 = “My name is {fname}, I’m {age}”.format(fname = “John”, age = 36)
#numbered indexes:
txt2 = “My name is {0}, I’m {1}”.format(“John”,36)
#empty placeholders:
txt3 = “My name is {}, I’m {}”.format(“John”,36)

print(txt1)
print(txt2)
print(txt3)

My name is John, I’m 36
My name is John, I’m 36
My name is John, I’m 36

txt = “For only {price:.2f} dollars!”
print(txt.format(price = 49))

txt = “For only {price:.2f} dollars!”
print(txt.format(price = 49))
txt = “For only {price:.2f} dollars!”
print(txt.format(price = 49))
For only 49.00 dollars!

45
Q

How can you make a dictionary to a list?

A

(ig) list(dictionary_name.keys())

If you want to print the keys in alphabetical order, you first make a list of the keys in the dictionary using the keys method available in dictionary objects

46
Q

extra

The method returns a string where some specified characters are replaced with the character described in a dictionary, or in a mapping table.

Parameter Description
table Required. Either a dictionary, or a mapping table describing how to perform the replace

If a character is not specified in the dictionary/table, the character will not be replaced.
If you use a dictionary, you must use ascii codes instead of characters.(don’t worry about how ascil code work now)

A

use a dictionary with ascii codes to replace 83 (S) with 80 (P):

What uses translate() and describe and its parameters with it

mydict = {83: 80}

txt = “Hello Sam!”

print(txt.translate(mydict))
Hello Pam!

47
Q

extra

The method returns a mapping table that can be used with the translate() method to replace specified characters.

Parameter Values
Parameter Description
x Required. If only one parameter is specified, this has to be a dictionary describing how to perform the replace. If two or more parameters are specified, this parameter has to be a string specifying the characters you want to replace.
y Optional. A string with the same length as parameter x. Each character in the first parameter will be replaced with the corresponding character in this string.
z Optional. A string describing which characters to remove from the original string.

A

Describe and how to use maketrans(), what parameters use it?

https://www.w3schools.com/python/ref_string_maketrans.asp

txt = “Hi Sam!”

x = “mSa”
y = “eJo”

mytable = str.maketrans(x, y)

print(txt.translate(mytable))
Hi Joe!

txt = “Hello Sam!”
mytable = str.maketrans(“S”, “P”)
print(txt.translate(mytable))

Hello Pam!

txt = “Good night Sam!”

x = “mSa”
y = “eJo”
z = “odnght”

mytable = str.maketrans(x, y, z)
print(txt.translate(mytable))
G i Joe!

48
Q

The method returns a view object. The view object contains the key-value pairs of the dictionary, as tuples in a list.

The view object will reflect any changes done to the dictionary

No parameters

When an item in the dictionary changes value, the view object also gets updated:

Bascially it does this dict_items([ ])

A

Describe and the parameters in items(). What do you use on it, and if the thing that you use it change, what happens?

car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}

x = car.items()

print(x)
dict_items([(‘brand’, ‘Ford’), (‘model’, ‘Mustang’), (‘year’, 1964)])

car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}

x = car.items()

car[“year”] = 2018

print(x)

car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}

x = car.items()

car[“year”] = 2018

print(x)

car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}

x = car.items()

car[“year”] = 2018

print(x)

dict_items([(‘brand’, ‘Ford’), (‘model’, ‘Mustang’), (‘year’, 2018)])

49
Q

The what? keyword is used to create small anonymous functions.
The same what? function can take any number of arguments, but can only have one expression.

The expression is evaluated and the result is returned.

A

Describe lambda

x = lambda a : a + 10
print(x(5))
15

x = lambda a, b, c : a + b + c
print(x(5, 6, 3))
14

50
Q

json.dumps vs json.loads

A

(ig) json.dumps: Python object → JSON string
json.loads: JSON string → Python object

51
Q

How to do parsing, Serialization?

A

Serialization=
some_string = json.dumps(student_data)

parsing=
some_data = json.loads(some_string)

52
Q

What method returns True if all the characters are digits, otherwise False. What is this used on?

A

What does this do:(used on strings) string.isdigit()

53
Q

Explain what is a frame?(don’t have to go all the way, just give a brief summary)

A

a frame is a structure that represents a single execution context for a function call. Each time a function is called, Python creates a new frame to store the state and details of that particular execution. Frames are essential for tracking variables, function calls, and the flow of execution in a program.

def add(x, y):
result = x + y
return result

def multiply(a, b):
return a * add(a, b)

print(multiply(2, 3))
When multiply(2, 3) is called, a frame for multiply is created, storing a=2 and b=3.
Inside multiply, add(a, b) is called, which creates a new frame for add, with x=2 and y=3.
The add function finishes, and its frame is removed, returning control back to multiply.
Finally, multiply finishes and its frame is removed after printing the result.

54
Q

With try and except, how to know the reason for exception?

A

(ig) To know the specific reason for an exception in a try-except block, you can use the as keyword to capture the exception object. The exception object provides details about the error, including the error message, which can help you understand why the exception occurred.
try:
# Code that might raise an exception
result = 10 / 0
except ZeroDivisionError as e:
print(“An error occurred:”, e
(variable can be named anything)

	Directly Print e: Printing e itself usually gives you the error message.
	**str(e) give you the reason for exception
	type(e) give you the type of the exception
55
Q

What’s an value error, is it an exception error?

A

An exception that occurs when a function receives an argument of the correct type but an inappropriate or invalid value. In other words, the data type is correct, but the specific value of the data is not acceptable for that function or operation.

int(“hello”) # Raises ValueError: invalid literal for int() with base 10: ‘hello’
a, b = [1, 2, 3] # Raises ValueError: too many values to unpack (expected 2)a, b = [1, 2, 3] # Raises ValueError: too many values to unpack (expected 2)

56
Q

How to raise error or exception, how to do it and explanation of it

A

(ig) Use raise keyword. The raise keyword raises an error and stops the control flow of the program.
Python Raise Syntax

raise {name_of_ the_ exception_class}

The basic way to raise an error is:

raise Exception(“user text”)

Raising an exception Without Specifying Exception Class
When we use the raise keyword, there’s no compulsion to give an exception class along with it. When we do not give any exception class name with the raise keyword, it reraises the exception that last occurred.

a = 5

if a % 2 != 0:
raise Exception(“The number shouldn’t be an odd integer”)
s = ‘apple’

try:
num = int(s)
except ValueError:
raise ValueError(“String can’t be changed into integer”)

	s = 'apple'

try:
num = int(s)
except:
raise