Basics Flashcards

1
Q

Print hello world!

A

print(“hello world!”)

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

Two ways to indent

A

Tab

Four spaces

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

Make 3 into a float and assign to prob

A

prob = float(3)

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

What is the type of test in the below?

test = 3

A

int

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

Why use double quotes over single quotes?

A

If you want to use an apostrophe or single quote. Otherwise, preference

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

Define a string named mystring with value hello.

A

mystring = “hello”

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

Assign mystring value:

Don’t worry about apostrophes.

A

mystring = “Don’t worry about apostrophes.”

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

Concatenate the below two variables into helloworld:
hello = “hello”
world = “world”

A

helloworld = hello + world

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

assign 3 and 4 to a and b respectively (one line)

A

a, b = 3, 4

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

what will happen in the below code?
one = 1
two = 2
hello = “hello”

print(one + two + hello)

A

TypeError: unsupported operand type(s) for +: ‘int’ and ‘str’

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

what is a list?

A

a type of array that can contain any type of variable and as many variables as needed.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q
what will be the output of the below?
mylist = []
mylist.append(1)
mylist.append(2)
mylist.append(3)
print(mylist)
A

[1, 2, 3]

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

what will be the output of the below:
mylist = [1,2,3]
print(mylist[10])

A

IndexError: list index out of range

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

what is the output of the below (remember PEMDAS):
number = 1 + 2 * 3 / 4.0
print(number)

A

2.5

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

what is the % operator do?

A

returns remainders

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

what is the output of:
remainder = 11 % 3
print(remainder)

A

2

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

Assign 2^3 to the variable ‘cubed’

A

cubed = 2 ** 3

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

what is the output here:
helloworld = “hello” + “ “ + “world”
print(helloworld)

A

hello world

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

assign “hellohellohellohello” to lottahello using the string hello and an operator.

A

lottahello = “hello” * 3
OR
lottahello = “hello” + “hello” + “hello”

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q
what would be the output of the below:
even_numbers = [2,4,6,8]
odd_numbers = [1,3,5,7]
all_numbers = odd_numbers + even_numbers
print(all_numbers)
A

[1, 3, 5, 7, 2, 4, 6, 8]

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

what would be the output of the below:

print([1,2,3] * 3)

A

[1, 2, 3, 1, 2, 3, 1, 2, 3]

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

what are two methods in formatting strings? provide an example of each.

A

two types:
1. c type:
%s - String (or any object with a string representation, like numbers)

%d - Integers

%f - Floating point numbers

%.f - Floating point numbers with a fixed amount of digits to the right of the dot.

%x/%X - Integers in hex representation (lowercase/uppercase)

  1. str.format()

name = “Amit”
print(“hello, %s!”, name)
print(“hello, {}”.format(name))

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

what is the output here:
astring = “Hello world!”
print(astring.index(“o”))

A

4, looks for the first “o”. Indexing starts at 0, not 1.

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

Count how many l’s there are in variable “astring”.

astring = “Hello world!”

A

astring.count(“l”)

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

how do you index a string based on a value? say the value you are looking for is “a”

A

str.index(“a”)

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

print the “o” in astring from “hello” using []:

astring = “Hello world!”

A

print(astring[4])

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

given str[start:stop:step], how can you print every other value from astring = “splicing strings” starting at “l”? What would the output be?

A

print(astring[2::2])

output: lcn tig

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

given astring = “Hello world!”, what value for the “step” portion of splicing would produce the same output as below:
print(astring[3:7])

A

ans = 1
see modified print statement below:
print(astring[3:7:1])

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

using astring = “Hello world!”, print the reverse of this.

A

print(astring[::-1])

remember, str[start:stop:step]

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

Assign astring variable to another variable called astringUpper and make the entire string all upper case

A

astringUpper = astring.upper()

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

Assign astring variable to another variable called astringLower and make the entire string all lower case

A

astringLower = astring.lower()

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

How can you check if astring starts with “hello”?

A

print(astring.startswith(“hello”))

if True, will print True

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

How can you check if astring ends with “orld!”?

A

print(astring.endswith(“orld!”))

if True, will print True

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

Split astring = “Hello world!” on the space. What would the output be?

A

print(astring.split(“ “))

output: [‘Hello’, ‘world!’]

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

how can you check if variable a equals 3?

A

a == 3

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

how can you check if variable a is not equals 3?

A

a != 3

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

“and” and “or” are operators – true or false?

A

true

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

“in” cannot be used to check an iterable object – true or false?

A

false, “in” operator could be used to check if a specified object exists within an iterable object container, such as a list

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

A statement is evaluated as true if one of the following is correct: – 2 reason, list them

A
  1. The “True” boolean variable is given, or calculated using an expression, such as an arithmetic comparison. 2. An object which is not considered “empty” is passed.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
40
Q

Give at least 4 examples for objects which are considered as empty: – list them

A
  1. An empty string: “” 2. An empty list: [] 3. The number zero: 0 4. The false boolean variable: False
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
41
Q

x = [1,2,3]
y = [1,2,3]
Why does this print out False?
print(x is y)

A

Unlike the double equals operator “==”, the “is” operator does not match the values of the variables, but the instances themselves

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

what does using “not” before a boolean do? give two examples (one for each boolean)

A

it inverts it.
print(not False) # Prints out True
print((not False) == (False)) # Prints out False

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

what do for loops do?

A

For loops iterate over a given sequence

44
Q

How long does a while loop repeat for?

A

While loops repeat as long as a certain boolean condition is met.

45
Q

what is the difference between “break” and “continue”?

A

break is used to exit a for loop or a while loop, whereas continue is used to skip the current block, and return to the “for” or “while” statement

46
Q

can we use “else” clause for loops?

A

we can use else for loops. When the loop condition of “for” or “while” statement fails then code part in “else” is executed. If break statement is executed inside for loop then the “else” part is skipped. Note that “else” part is executed even if there is a continue statement.

example:
# Prints out 0,1,2,3,4 and then it prints "count value reached 5"
count=0
while(count<5):
    print(count)
    count +=1
else:
    print("count value reached %d" %(count))
# Prints out 1,2,3,4
for i in range(1, 10):
    if(i%5==0):
        break
    print(i)
else:
    print("this is not printed because for loop is terminated because of break but not due to fail in condition")
47
Q

what are functions?

A

Functions are a convenient way to divide your code into useful blocks, allowing us to order our code, make it more readable, reuse it and save some time. Also functions are a key way to define interfaces so programmers can share their code.

48
Q

Create a function named my_function that has no parameter but prints: “Hello From My Function!”)

A
def my_function():
    print("Hello From My Function!")
49
Q

Create a function named my_function_with_args that has parameters username and greeting and prints: “Hell, username, From My Function! I wish you greeting”)

A
def my_function_with_args(username, greeting):
    print("Hello, {} , From My Function!, I wish you {}".format(username, greeting))
OR
def my_function_with_args(username, greeting):
    print("Hello, %s , From My Function!, I wish you %s"%(username, greeting))
50
Q

Create a function sum_two_numbers that takes two variable a and b and returns the sum of it

A
def sum_two_numbers(a, b):
    return a + b
51
Q

Create a function sum_two_numbers that takes two variable a and b and returns the sum of it. Then call the function with a = 4 and b = 3 and assign the value to variable named x.

A
def sum_two_numbers(a, b):
    return a + b

x = sum_two_numbers(4, 3)

52
Q

what is the difference between an object and a class in Python?

A

Object is simply a collection of data (variables) and methods (functions) that act on those data. And, class is a blueprint for the object. We can think of class as a sketch (prototype) of a house.

53
Q

what does the simplest form of a class definition look like?

A

class ClassName:

.
.
.
54
Q

what is a namespace?

A

A namespace is a mapping from names to objects. Most namespaces are currently implemented as Python dictionaries, but that’s normally not noticeable in any way (except for performance), and it may change in the future.

55
Q

What are the two kinds of operations that are suppored by class objects?

A

Class objects support two kinds of operations: attribute references and instantiation

56
Q

What are attribute references?

A

Valid attribute names are all the names that were in the class’s namespace when the class object was created. Attribute references use the standard syntax used for all attribute references in Python: obj.name.

57
Q
What are the attribute references of the below class, and what do they return?
class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'
A

MyClass.i and MyClass.f are valid attribute references, returning an integer and a function object, respectively

58
Q

What does __doc__ attribute do?

A

Returns the docstring belonging to the class

59
Q
In the below example, what does the MyClass.\_\_doc\_\_ attribute return?
class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        return 'hello world'
A

“A simple example class”

60
Q
In the below example, what does the MyClass.f.\_\_doc\_\_ attribute return?
class MyClass:
    """A simple example class"""
    i = 12345
    def f(self):
        """A return of hello world"""
        return 'hello world'
A

“A return of hello world”

61
Q

What kind of notation does class instantiation use?

A

Class instantiation uses function notation. Just pretend that the class object is a parameterless function that returns a new instance of the class.

62
Q

What does the following do?

x = MyClass()

A

creates a new instance of the class and assigns this object to the local variable x

63
Q

Many classes like to create objects with instances customized to a specific initial state. What are those methods usually called?

A

def __init__(self):
.
.

64
Q

What happens to the __init__() method upon class instantiation?

A

It is automatically invoked.

65
Q
For:
>>> class Complex:
...     def \_\_init\_\_(self, realpart, imagpart):
...         self.r = realpart
...         self.i = imagpart
...
>>> x = Complex(3.0, -4.5)

what is the value of x.r and x.i?

A

x. r = 3.0

x. i = -4.5

66
Q

What is a dictionary?

A

A dictionary is a data type similar to arrays, but works with keys and values instead of indexes.

67
Q
What does the below output:
phonebook = {}
phonebook["John"] = 938477566
phonebook["Jack"] = 938377264
phonebook["Jill"] = 947662781
print(phonebook)
A

{‘Jack’: 938377264, ‘John’: 938477566, ‘Jill’: 947662781}

68
Q
phonebook = {
    "John" : 938477566,
    "Jack" : 938377264,
    "Jill" : 947662781
}
print(phonebook)
A

{‘Jack’: 938377264, ‘John’: 938477566, ‘Jill’: 947662781}

69
Q

What is the following code doing:

phonebook = {“John” : 938477566,”Jack” : 938377264,”Jill” : 947662781}
for name, number in phonebook.items():
print(“Phone number of %s is %d” % (name, number))

A

iterating over a dictionary

70
Q

what is the syntax to remove a value from a dictionary?

A
phonebook = {
   "John" : 938477566,
   "Jack" : 938377264,
   "Jill" : 947662781
}
del phonebook["John"]
print(phonebook)
71
Q
What does the following do:
phonebook = {
   "John" : 938477566,
   "Jack" : 938377264,
   "Jill" : 947662781
}
del phonebook["John"]
print(phonebook)
A

remove a value from the dictionary

72
Q
What does the following do:
phonebook = {
   "John" : 938477566,
   "Jack" : 938377264,
   "Jill" : 947662781
}
phonebook.pop("John")
print(phonebook)
A

remove a value from the dictionary

73
Q

What is a set?

A

A set is well defined collection of distinct objects.

74
Q

What is a set in Python?

A
  • unordered
  • elements are unique (duplicates are not allowed)
  • set can be modified, but elements inside set must be hashable
75
Q

What does hashable mean?

A

A type of object where it’s hash value remains the same during it’s lifetime. All immutable objects are hashable, but not all hashable objects are immutable

76
Q

True or False. Lists and dictionaries are hashable.

A

False. Lists and dictionaries are two mutable types that are not hashable.

77
Q

What are the two ways to define a set in Python?

A
In: set = (['foo', 'bar'])
Out: {'bar', foo'}
# sets are unordered

Using the {} brackets:
x = {“bar”, “foo”}

78
Q

What would be the output of this set creation:
set(“hello”)

Why?

A

{“e”, “h”, “l”, “o”}

  • sets cannot contain duplicates (one “l” is dropped out)
  • sets are unordered
79
Q

True or False. Sets can contain different object types within a set.

A

True.

80
Q

What function allows to find the length of a set?

A

len()

81
Q

What is the length of the below set:

x = {1, 1, 2}

A
  1. The 2 “1”s become one.

x will print {1, 2}

82
Q

What is the length of the below set:

x = {1, (1, 2)}

A
  1. Counts 1 and the tuple.
83
Q

How can you check for membership in a set? Check for both “baz” and “foo” in:
x = {“foo”, “bar}

A

Using “in”.
“baz” in x – False
“foo” in x – True

84
Q

True or False. You can loop through a set the same way you can loop through a list or tuple.

A

True.

85
Q

What are the two ways you can union sets? Show both for x1 and x2 (two sets).

A

using the “|” operator:
x1 | x2

using the .union() function:

x1. union(x2)
x1. union(x2, x3)

86
Q

What can you use the .union() for that you cannot use the “|” operator for? Give an example.

A

When you are unioning an iterable.
x1.union((1,2,3))

x1 | (1,2,3)&raquo_space; will give an TypeError

87
Q

What is the union of sets?

A

Set of all distinct elements in all sets

88
Q

What is the intersection of sets?

A

Set of only elements that exist in all sets.

89
Q

What are the two ways you can intersect sets? Show both for x1 and x2 (two sets).

A

using the “&” operator:
x1 & x2

using the .intersection() function:

x1. intersection(x2)
x1. intersection(x2, x3)

90
Q

What is the difference of sets?

A

Set of only elements that exist in the first set, but do not exist in any after.

91
Q

What are the two ways you can find the difference of sets? Show both for x1 and x2 (two sets).

A

using the “-“ operator:
x1 - x2

using the .intersection() function:

x1. difference(x2)
x1. difference(x2, x3)

92
Q

What is symmetric difference of sets?

A

This is the set of elements that exist only in a single set, but not in multiple. (Outer Join, in SQL)

93
Q

What are the two ways you can find the symmetric difference of sets? Show both for x1 and x2 (two sets).

A

using the “^” operator:

x1 ^ x2

94
Q

What is isdisjoint()?

A

Determines whether or not any two sets have any elements in common.

95
Q
x1 = {"foo", "bar", "baz"}
x2 = {"baz", "qux", "quzz"}

what will x1.isdisjoint(x2) yield? Why?

A

False. Because they share the element, “baz”.

96
Q
x1 = {"foo", "bar", "baz"}
x2 = {"baz", "qux", "quzz"}

what will x1.isdisjoint(x2 - {“baz”}) yield? Why?

A

True. x2 - {“baz”} removes “baz” from x2 and therefore, x1 and x2 have no elements in common.

97
Q

What is issubset()?

A

A set is a subset of another set if every element in the first set are in the second set.

98
Q

What are the two ways you can find the is subset of sets? Show both for x1 and x2 (two sets).

A

using the “<=” operator:

x1 <= x2

99
Q

What is the difference between proper subset and issubset()? List 3.

A
  1. proper subset does not have a method
  2. proper subset does not work on identical subsets
  3. The operator is “
100
Q

What is issuperset()?

A

A set is considered a superset of another set if the first set contains every element of the second set.

101
Q

What are the two ways you can find if the set is a superset? Show both for x1 and x2 (two sets).

A

using the “>=” operator:

x1 >= x2

102
Q

What is the difference between proper superset and issuperset()? List 3.

A
  1. proper superset does not have a method
  2. proper superset does not work on identical subsets
  3. The operator is “>” , not “>=”
103
Q

How can you add an element to a set, x?

A

x.add(). Must be hashable element.

104
Q

How can you remove an element from a set, x?

List two ways, and differences.

A

x. remove() - if does not exist, will throw keyError.

x. discard( does not exist, will throw not keyError.

105
Q

What does x.pop() do for a set?

A

It will remove a random element from the set and return the value it’s removed.

106
Q

How can you remove all the elements from a set, x?

A

x.clear(). Will remove all elements from the set x.

107
Q

What are the two ways you can update a set to include elements it does not currently have? Show both for x1 and x2 (two sets).

A

using the “|=” operator:
x1 |= x2, operands need to be sets

using the .symmetric_difference() function:
x1.issuperset(x2) arguments need to be iterables