honPyt Flashcards
While using Python in interactive mode, which variable is the default prompt for continuation lines?
…
While using Python in interactive mode, which variable holds the value of the last printed expression?
_ (underscore)
With the variable assignment name=”Python”, what will be the output of print(name[-1])?
“n”
What would be the output of this code?
def welcome(name): return "Welcome " + name, "Good Bye " + name
wish = welcome(“Joe”)
print(wish)
(Brainscape doesn’t seem to allow indentation, so just pretend this is all indented properly)
(‘Welcome Joe’, ‘Good Bye Joe’)
What would be the output of this code?
A = 15 B = 10 C = A/B D = A//B E = A%B print(C) print(D) print(E)
1.5
1
5
What does the “//” operator do?
Floor division (or integer division), a normal division operation except that it returns the largest possible integer.
(this behaves differently when negative numbers are involved)
What would be the output of this code?
Elements=["ether", "air", "fire", "water"] print(Elements[0]) print(Elements[3]) print(Elements[2]) Elements[2] = "earth" print(Elements[2])
ether
water
fire
earth
What would be the output of this code?
data = (x*10 for x in range(3)) for i in data: print(i) for j in data: print(j)
(Brainscape doesn’t seem to allow indentation, so just pretend this is all indented properly)
0
10
20
(this only returns the first loop, as generator data can only be used once)
What would be the output of this code?
names = ['a', 'b', 'c'] names_copy = names names_copy[2] = 'h' print(names) print(names_copy)
[‘a’, ‘b’, ‘h’]
[‘a’, ‘b’, ‘h’]
In Python, Assignment statements do not copy objects, they create bindings between a target and an object
It only creates a new variable that shares the reference of the original object
What would be the output of this code?
x = 3 + 2j
y = 3 - 2j
z = x + y
print(z)
(6+0j)
What would be the output of this code?
for i in range(3):
print(i)
else:
print(“Done!”)
(Brainscape doesn’t seem to allow indentation, so just pretend this is all indented properly)
0
1
2
Done!
What is the slicing operator in Python?
:
What does trunc() do?
trunc() rounds down positive floats, and rounds up negative floats
math. trunc(3.5) # 3
math. trunc(-3.5) # -3
Can you use remove() to delete an element from an array by giving it an index number?
No
What keyword can be used to remove an item from a list based on its index?
del
numbers = [50, 60, 70, 80]
del numbers[1] # numbers = [50, 70, 80]
How would you use pop() to remove the first element of an array?
pop(0)
numbers = [50, 60, 70, 80]
numbers.pop(0) # [60, 70, 80]
What would be the output of this code?
a, b, c, d = 1, ‘cat’, 6, 9
print(c)
6
What would be the output of this code?
a, b, c, d = 1
print(c)
TypeError: cannot unpack non-iterable int object
What is the lambda keyword used for?
It is used for creating simple anonymous functions
What keyword can be used to force a particular exception to occur?
raise
Which module will process command line arguments for a Python script?
os
What is the syntax of a lambda function on Python?
lambda arguments: expression
How would you make a deep copy of an array?
Use copy()
arr2 = arr1.copy()
Using filter() how would you use lambda to select all numbers over 5 from array my_list?
filter(lambda x: x > 5, my_list)
Can lambda only be used for numeric expressions?
Yes
Which if the following statements will not print all the elements of the list below?
letters=[“d”,”e”,”a”,”g”,”b”]
print(letters[:])
print(letters[0:])
print(letters[:-3])
print(letters[:10])
print(letters[:-3])
What would be the output of the code below?
>>> a = "Welcome" >>> b = "Welcome" >>> c = "Good-Bye" >>> d = "Good-Bye" >>> a is b >>> c is d
True
False
“Welcome” and “Welcome” turn out to be the same because they are constants, less than 20 characters long or not subject to constant folding (in this case both!), and contain only ASCII letters, digits and underscores
Which function will return DirEntry objects instead of strings while trying to list the contents of the directory?
os.scandir()
What is an abstract class?
An abstract class exists only so that other “concrete” classes can inherit from the abstract class
What happens when you use any() on a list?
The any() function returns True if any item in the list evaluates to True. Otherwise, it returns False
What data structure does a binary tree degenerate to if it isn’t balanced properly?
linked list
What are static methods?
Static methods serve mostly as utility methods or helper methods, since they can’t access or modify a class’s state
What are attributes?
Attributes are a way to hold data, or describe a state for a class or an instance of a class
What is the term to describe this code?
count, fruit, price = (2, ‘apple’, 3.5)
tuple unpacking
What built-in list method would you use to remove items from a list?
pop()
What is one of the most common use of Python’s sys library?
to capture command-line arguments given at a file’s runtime
What is the runtime of accessing a value in a dictionary by using its key?
O(1), also called constant time
What is the correct syntax for defining a class called Game?
class Game:
What is the correct way to write a doctest?
A def sum(a, b): """ sum(4, 3) 7 sum(-4, 5) 1 """ return a + b
B def sum(a, b): """ >>> sum(4, 3) 7 >>> sum(-4, 5) 1 """ return a + b
C def sum(a, b): """ # >>> sum(4, 3) # 7 # >>> sum(-4, 5) # 1 """ return a + b
D def sum(a, b): ### >>> sum(4, 3) 7 >>> sum(-4, 5) 1 ### return a + b
def sum(a, b): """ >>> sum(4, 3) 7 >>> sum(-4, 5) 1 """ return a + b
What built-in Python data type is commonly used to represent a stack?
list
you can only build a stack from scratch
What would this expression return?
college_years = ['Freshman', 'Sophomore', 'Junior', 'Senior'] return list(enumerate(college_years, 2019))
[(2019, ‘Freshman’), (2020, ‘Sophomore’), (2021, ‘Junior’), (2022, ‘Senior’)]
How does defaultdict work?
If you try to access a key in a dictionary that doesn’t exist, defaultdict will create a new key for you instead of throwing a KeyError
What is the correct syntax for defining a class called “Game”, if it inherits from a parent class called “LogicGame”?
class Game(LogicGame):
What is the purpose of the “self” keyword when defining or calling instance methods?
self refers to the instance whose method was called
Can you assign a name to each of the namedtuple members and refer to them that way, similarly to how you would access keys in dictionary?
Yes
What is an instance method?
Instance methods can modify the state of an instance or the state of its parent class
Which choice is the most syntactically correct example of the conditional branching?
num_people = 5
if num_people > 10:
print(“There is a lot of people in the pool.”)
elif num_people > 4:
print(“There are some people in the pool.”)
elif num_people > 0:
print(“There are a few people in the pool.”)
else:
print(“There is no one in the pool.”)
Is it true that encapsulation only allows data to be changed by methods?
No
What is the purpose of an if/else statement?
It executes one chunk of code if a condition is true, but a different chunk of code if the condition is false
What built-in Python data type is commonly used to represent a queue?
list
What is the correct syntax for instantiating a new object of the type Game?
x = Game()
What does the built-in map() function do?
It applies a function to each item in an iterable and returns the value of that function
If there is no return keyword in a function, what happens?
If the return keyword is absent, the function will return None
What is the purpose of the pass statement in Python?
It is a null operation used mainly as a placeholder in functions, classes, etc.
If you have a loop or a function that is not implemented yet, but we want to implement it in the future, it cannot have an empty body. The interpreter would give an error. So, we use the pass statement to construct a body that does nothing
What is the term used to describe items that may be passed into a function?
arguments
Which collection type is used to associate values with unique keys?
dictionary
When does a for loop stop iterating?
when it has assessed each item in the iterable it is working on, or a break keyword is encountered
What is the runtime complexity of searching for a specific node within a singly linked list?
The runtime is O(n) because in the worst case, the node you are searching for is the last node, and every node in the linked list must be visited
Given the following three lists, how would you create a new list that matches the desired output printed below?
fruits = ['Apples', 'Oranges', 'Bananas'] quantities = [5, 3, 4] prices = [1.50, 2.25, 0.89]
Desired output
[(‘Apples’, 5, 1.50),
(‘Oranges’, 3, 2.25),
(‘Bananas’, 4, 0.89)]
i = 0 output = [] for fruit in fruits: temp_qty = quantities[i] temp_price = prices[i] output.append((fruit, temp_qty, temp_price)) i += 1 return output
(Brainscape doesn’t seem to allow indentation, so just pretend this is all indented properly)
What happens when you use the built-in function all() on a list?
The all() function returns True if all items in the list evaluate to True. Otherwise, it returns False
What is the correct syntax for calling an instance method on a class named Game?
> > > dice = Game()
|»_space;> dice.roll()
What is the algorithmic paradigm of quick sort?
backtracking
dynamic programming
decrease and conquer
divide and conquer
divide and conquer
What is runtime complexity of the list’s built-in .append() method?
O(1), also called constant time
What is key difference between a set and a list?
A set is an unordered collection items with no duplicates
A list is an ordered collection of items, that may include duplicates
What is the definition of abstraction as applied to object-oriented Python?
Abstraction means the implementation is hidden from the user, and only the relevant data or information is shown
What does this function print?
def my_func(abc_list, num_list): for char in abc_list: for num in num_list: print(char, num) return
my_func([‘a’, ‘b’, ‘c’], [1, 2, 3])
a 1 a 2 a 3 b 1 b 2 b 3 c 1 c 2 c 3