Python is one of the most popular programming languages used by developers worldwide. It's an open-source language that's easy to learn, flexible, and versatile. Python has become the go-to language for many developers and companies, making it a highly sought-after skill in the job market. That's why internships in Python are becoming increasingly popular among students and recent graduates. In this blog, we will explore what a Python internship is, the benefits of taking one, and how to find the best Python internships. What is a Python Internship? A Python internship is an opportunity for students and recent graduates to gain practical experience working with Python. It's a short-term position, typically lasting between 3-6 months, that allows interns to apply their knowledge to real-world projects. During a Python internship, you'll work under the guidance of experienced developers and learn how to solve problems using Python. Benefits of a Python Internship There are several benefits to taking a Python internship, including: Practical Experience: Interning in Python will provide you with practical experience working with the language. You'll have the opportunity to apply your knowledge to real-world projects, which is a valuable experience when it comes to building your career. Networking Opportunities: Python internships offer networking opportunities that can lead to future job opportunities. You'll be working with experienced developers who can offer guidance and mentorship, and you'll also have the opportunity to meet other interns and professionals in the field. Enhanced Resume: Having a Python internship on your resume can make you stand out to potential employers. It shows that you have practical experience working with the language and have demonstrated your ability to work on real-world projects. Skill Development: Python internships offer the opportunity to develop your skills in the language. You'll be working on projects that challenge you and require you to learn new concepts, which will help you grow as a developer. How to Find the Best Python Internships There are several ways to find Python internships, including: Job Boards: Many job boards, such as Indeed and Glassdoor, have a dedicated section for internships. You can search for Python internships in your area and apply directly through the job board. Company Websites: Many companies advertise their internships on their websites. You can search for Python internships on company websites and apply directly through their career portal. Career Fairs: Attend career fairs to meet with company representatives and learn about their internship programs. You can also ask for advice on how to best apply for internships and what skills you should focus on developing. Online Communities: Join online communities, such as LinkedIn groups or Python developer forums, to connect with professionals in the field. These communities often share internship opportunities and offer advice on how to succeed in the field. Conclusion A Python internship is a valuable experience for students and recent graduates looking to gain practical experience working with Python. It offers networking opportunities, skill development, and enhances your resume. There are several ways to find Python internships, including job boards, company websites, career fairs, and online communities. By taking a Python internship, you'll be on your way to building a successful career as a developer.
any()
on a list?any()
function will randomly return any
item from the list.any()
function returns True
if
any item in the list evaluates to True. Otherwise, it returns False.any()
function takes as arguments the
list
to check inside, and the item to check for. If "any" of the items in the list
match
the item to check for, the function returns True.any()
function returns a Boolean value
that
answers the question "Are there any items in this list?"example
if any([True, False, False, False]) == True:
print('Yes, there is True')
>>> 'Yes, there is True'
None
.
if/else
statement, used when testing for equality between objects.
Explanation
Attributes defined under the class, arguments goes under the functions. arguments usually refer as parameter, whereas attributes are the constructor of the class or an instance of a class.
count, fruit, price = (2, 'apple', 3.5)
tuple assignment
tuple unpacking
tuple matching
tuple duplication
.delete()
methodpop(my_list)
del(my_list)
.pop()
methodexample
my_list = [1,2,3]
my_list.pop(0)
my_list
>>>[2,3]
class Game(LogicGame): pass
def Game(LogicGame): pass
def Game.LogicGame(): pass
class Game.LogicGame(): pass
Explanation:
The parent class which is inherited is passed as an argument to the child class. Therefore, here the first option is the right answer.
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
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
Explanation - use '''
to start the doc and add output
of
the cell after >>>
set
list
None
dictionary
You can only build a stack from scratch.
college_years = ['Freshman', 'Sophomore', 'Junior', 'Senior']
return list(enumerate(college_years, 2019))
[('Freshman', 2019), ('Sophomore', 2020), ('Junior', 2021), ('Senior', 2022)]
[(2019, 2020, 2021, 2022), ('Freshman', 'Sophomore', 'Junior', 'Senior')]
[('Freshman', 'Sophomore', 'Junior', 'Senior'), (2019, 2020, 2021, 2022)]
[(2019, 'Freshman'), (2020, 'Sophomore'), (2021, 'Junior'), (2022, 'Senior')]
self
means that no other arguments are
required
to be passed into the method.self
method;
it's just historic computer science jargon that Python keeps to stay consistent with
other
programming languages.self
refers to the instance
whose
method was called.self
refers to the class that was inherited
from to create the object using self
.Simple example
class my_secrets:
def __init__(self, password):
self.password = password
pass
instance = my_secrets('1234')
instance.password
>>>'1234'
namedtuple
members and refer to them that way, similarly to how you would access keys in
dictionary
.
tuple
.namedtuples
are just as memory efficient as
regular tuples
.namedtuples
because they are available in the standard library.
We need to import it using:from collections import namedtuple
None
.my_game = class.Game()
my_game = class(Game)
my_game = Game()
my_game = Game.create()
map()
function do?Explanation: - The synax for map()
function is
list(map(function,iterable))
. The simple area finder using map would be like this
import math
radius = [1,2,3]
area = list(map(lambda x: round(math.pi*(x**2), 2), radius))
area
>>> [3.14, 12.57, 28.27]
None
.True
.
pass
statement in Python?
yield
statement of a
generator and return a value of None.while
or
for loop
and return to the start of the loop.
slot
dictionary
queue
sorted list
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)]
output = []
fruit_tuple_0 = (first[0], quantities[0], price[0])
output.append(fruit_tuple)
fruit_tuple_1 = (first[1], quantities[1], price[1])
output.append(fruit_tuple)
fruit_tuple_2 = (first[2], quantities[2], price[2])
output.append(fruit_tuple)
return output
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
groceries = zip(fruits, quantities, prices)
return groceries
>>> [
('Apples', 5, 1.50),
('Oranges', 3, 2.25),
('Bananas', 4, 0.89)
]
i = 0
output = []
for fruit in fruits:
for qty in quantities:
for price in prices:
output.append((fruit, qty, price))
i += 1
return output
all()
function returns a Boolean value
that
answers the question "Are all the items in this list the same?all()
function returns True if all the
items in the list can be converted to strings. Otherwise, it returns False.all()
function will return all the
values
in the list.all()
function returns True
if
all items in the list evaluate to True. Otherwise, it returns False.Explanation - all()
returns true if all in the list are True, see
example below
test = [True,False,False,False]
if all(test) is True:
print('Yeah all are True')
else:
print('There is an imposter')
>>> 'There is an imposter'
(Answer format may vary. Game and roll (or dice_roll) should each be called with no parameters.)
>>> dice = Game()
>>> dice.roll()
>>> dice = Game(self)
>>> dice.roll(self)
>>> dice = Game()
>>> dice.roll(self)
>>> dice = Game(self)
>>> dice.roll()
.append()
method?set
and a list
?
def print_alpha_nums(abc_list, num_list):
for char in abc_list:
for num in num_list:
print(char, num)
return
print_alpha_nums(['a', 'b', 'c'], [1, 2, 3])
a 1
a 2
a 3
b 1
b 2
b 3
c 1
c 2
c 3
['a', 'b', 'c'], [1, 2, 3]
aaa
bbb
ccc
111
222
333
a 1 2 3
b 1 2 3
c 1 2 3
def sum(a, b):
# a = 1
# b = 2
# sum(a, b) = 3
return a + b
def sum(a, b):
"""
a = 1
b = 2
sum(a, b) = 3
"""
return a + b
def sum(a, b):
"""
>>> a = 1
>>> b = 2
>>> sum(a, b)
3
"""
return a + b
def sum(a, b):
'''
a = 1
b = 2
sum(a, b) = 3
'''
return a + b
Explanation: Use """
to start and end the docstring
and
use >>>
to represent the output. If you write this correctly you can also
run
the doctest using build-in doctest module
Example
# namedtuple function accepts the following arguments to generate a class
from collections import namedtuple
>>> Point = namedtuple('Point',['x','y'])
>>> point = Point(100, 200)
>>> point
Point(x=100, y=200)
# Which let you use both unpacking and iteration to access
>>> x, y = point
>>> print(f'({x}, {y})')
(100, 200)
>>> for coordinate in point:
print(coordinate)
100
200
&&
=
==
||
fruit_info = {
'fruit': 'apple',
'count': 2,
'price': 3.5
}
fruit_info ['price'] = 1.5
my_list [3.5] = 1.5
1.5 = fruit_info ['price]
my_list['price'] == 1.5
5 != 6
yes
False
True
None
Explanation - !=
is equivalent to not equal to in
python
__init__()
method do?
Example:
class test:
def __init__(self):
print('I came here without your permission lol')
pass
t1 = test()
>>> 'I came here without your permission lol'
How many microprocessors it would take to run your code in less than one second
How many lines of code are in your code file
The amount of space taken up in memory as a function of the input size
How many copies of the code file could fit in 1 GB of memory
fruit_info = {'fruit': 'apple', 'count': 2, 'price': 3.5}
fruit_info =('fruit': 'apple', 'count': 2,'price': 3.5 ).dict()
fruit_info = ['fruit': 'apple', 'count': 2,'price': 3.5 ].dict()
fruit_info = to_dict('fruit': 'apple', 'count': 2, 'price': 3.5)
fruits = {'Apples': 5, 'Oranges': 3, 'Bananas': 4}
fruit_names = [x in fruits.keys() for x]
fruit_names = for x in fruits.keys() *
fruit_names = [x for x in fruits.keys()]
fruit_names = x for x in fruits.keys()
self
keyword when defining or calling methods on an
instance of an object?self
refers to the class that was inherited
from to create the object using self
.self
method.
It's just legacy computer science jargon that Python keeps to stay consistent with other
programming languages.self
means that no other arguments are
required
to be passed into the method.self
refers to the instance
whose
method was called.Explanation: - Try running the example of the Q42 without passing
self
argument inside the __init__
, you'll understand the reason. You'll get the
error like this __init__() takes 0 positional arguments but 1 was given
, this means
that something is going inside even if haven't specified, which is instance itself.
def getMaxNum(list_of_nums): # body of function goes here
func get_max_num(list_of_nums): # body of function goes here
func getMaxNum(list_of_nums): # body of function goes here
def get_max_num(list_of_nums): # body of function goes here
maxValue = 255
max_value = 255
MAX_VALUE = 255
MaxValue = 255
Explanation - deque
is used to create block chanin and in that
there is
first in first out approch, which means the last element to enter will be the first to
leave.
my_set = {0, 'apple', 3.5}
my_set = to_set(0, 'apple', 3.5)
my_set = (0, 'apple', 3.5).to_set()
my_set = (0, 'apple', 3.5).set()
__init__()
method that takes no
parameters?
class __init__(self):
pass
def __init__():
pass
class __init__():
pass
def __init__(self):
pass
def tax(my_float):
'''Calculates the sales tax of a purchase. Takes in a float representing the subtotal as an argument and returns a float representing the sales tax.'''
pass
def tx(amt):
'''Gets the tax on an amount.'''
def sales_tax(amount):
'''Calculates the sales tax of a purchase. Takes in a float representing the subtotal as an argument and returns a float representing the sales tax.'''
def calculate_sales_tax(subtotal):
pass
mixin
?mixin
to force a function to
accept
an argument at runtime even if the argument wasn't included in the function's
definition.mixin
to allow a decorator to
accept
keyword arguments.mixin
to make sure that a
class's
attributes and methods don't interfere with global variables and functions.mixin
to define that functionality.
Explanation Stack uses the last in first out approach
with
keyword?
with
keyword lets you choose which
application to open the file in.with
keyword acts like a
for
loop, and lets you access each line in the file one by one.
with
keyword
for opening a file in Python.with
keyword in Python, Python will make sure the file gets closed, even if an exception or error
is
thrown.
python3 -m doctest <_filename_>
python3 <_filename_>
python3 <_filename_> rundoctests
python3 doctest
Explanation:
The lambda notation is basically an anonymous function that can take any number of arguments with only single expression (i.e, cannot be overloaded). It has been introducted in other programming languages, such as C++ and Java. The lambda notation allows programmers to "bypass" function declaration.
def get_next_card():
# method body goes here
def get_next_card(self):
# method body goes here
def self.get_next_card():
# method body goes here
def self.get_next_card(self):
# method body goes here
get_max_num([57, 99, 31, 18])
call.(get_max_num)
def get_max_num([57, 99, 31, 18])
call.get_max_num([57, 99, 31, 18])
-- This is a comment
# This is a comment
/_ This is a comment _\
// This is a comment
my_list = ['kiwi', 'apple', 'banana']
orange = my_list[1]
my_list[1] = 'orange'
my_list['orange'] = 1
my_list[1] == orange
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.")
else:
print("There is no one in the pool.")
num_people = 5
if num_people > 10:
print("There is a lot of people in the pool.")
if num_people > 4:
print("There are some people in the pool.")
else:
print("There is no one in the pool.")
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.")
else;
print("There is no one in the pool.")
if num_people > 10;
print("There is a lot of people in the pool.")
if num_people > 4;
print("There are some people in the pool.")
else;
print("There is no one in the pool.")
defaultdict
work?defaultdict
will automatically create a
dictionary for you that has keys which are the integers 0-10.defaultdict
forces a dictionary to only
accept
keys that are of the types specified when you created the defaultdict
(such as
strings or integers).defaultdict
with a nonexistent key, a new default key-value pair will be
created
for you instead of throwing a KeyError
.
defaultdict
stores a copy of a dictionary
in
memory that you can default to if the original gets unintentionally modified.variety
to the
fruit_info
dictionary that has a value of Red Delicious
?
fruit_info['variety'] == 'Red Delicious'
fruit_info['variety'] = 'Red Delicious'
red_delicious = fruit_info['variety']
red_delicious == fruit_info['variety']
while
loop?Simple Example
i = 1
while i<6:
print('Countdown:',i)
i = i + 1
__init__()
method that sets
instance-specific attributes upon creation of a new class instance?def __init__(self, attr1, attr2):
attr1 = attr1
attr2 = attr2
def __init__(attr1, attr2):
attr1 = attr1
attr2 = attr2
def __init__(self, attr1, attr2):
self.attr1 = attr1
self.attr2 = attr2
def __init__(attr1, attr2):
self.attr1 = attr1
self.attr2 = attr2
Explanation: When instantiating a new object from a given class, the
__init__()
method will take both attr1
and attr2
, and set
its
values to their corresponding object attribute, that's why the need of using
self.attr1 = attr1
instead of attr1 = attr1
.
def count_recursive(n=1):
if n > 3:
return
print(n)
count_recursive(n + 1)
1
1
2
2
3
3
3
2
1
3
3
2
2
1
1
1
2
3
Intersect
; union
|
; &
&
; |
&&
; ||
import numpy as np
np.ones([1,2,3,4,5])
open
function. What might be the easiest solution?
{x for x in range(100) if x%3 == 0}
def Game(): pass
def Game: pass
class Game: pass
class Game(): pass
my_game = Game(self) self.my_game.roll_dice()
my_game = Game() self.my_game.roll_dice()
my_game = Game() my_game.roll_dice()
my_game = Game(self) my_game.roll_dice(self)
a = np.array([1,2,3,4])
print(a[[False, True, False, False]])
{0,2}
[2]
{2}
[0,2,0,0]
z = y.split(';')
len(z)
Explanation:
y="stuff;thing;junk"
len(z) ==> 3
y="stuff;thing;junk;"
len(z) ==> 4
num_list = [1,2,3,4,5]
num_list.remove(2)
print(num_list)
[1,2,4,5]
[1,3,4,5]
[3,4,5]
[1,2,3]
Explanation:
num_list = [1,2,3,4,5]
num_list.pop(2)
>>> [1,2,4,5]
num_list.remove(2)
>>> [1,3,4,5]
[10,9,8,7,6,5,4,3,2,1]
reversed(list(range(1,11)))
list(reversed(range(1,10)))
list(range(10,1,-1))
list(reversed(range(1,11)))
import math
print(math.pow(2,10)) # prints 2 elevated to the 10th power
print(2^10)
print(2**10)
y = [x*2 for x in range(1,10)]
print(y)
y = 1
for i in range(1,10):
y = y * 2
print(y)
[]
are _, {}
are _, and ()
are
_.
table = np.array([
[1,3],
[2,4]])
print(table.max(axis=1))
[2, 4]
[3, 4]
[4]
[1,2]
number = 3
print (f"The number is {number}")
The number is 3
the number is 3
THE NUMBER IS 3
my_tuple tup(2, 'apple', 3.5) %D
my_tuple [2, 'apple', 3.5].tuple() %D
my_tuple = (2, 'apple', 3.5)
my_tuple = [2, 'apple', 3.5]
write('w')
scan('s')
append('a')
read('r')
set
list
tuple
dictionary
sys.exc_info()
os.system()
os.getcwd()
sys.executable
my_dictionary = {
'A': 1,
'B': 2,
'C': 3,
'D': 4,
'E': 5
}
letters = []
for letter in my_dictionary.values():
letters.append(letter)
letters = my_dictionary.keys()
letters = [letter for (letter, number) in my_dictionary.items()]
letters4 = list(my_dictionary)
Explanation: The first one (the correct option) returns the list of the values (the numbers). The rest of the options return a list of the keys.
print
function. What function can you use within NumPy to force it to print the
entire
array?
set_printparams
set_printoptions
set_fullprint
setp_printwhole
try/except
blocks when
you
want to run some code, but need a way to execute different code if an exception is raised.
try/except
blocks inside of unit
tests
so that the unit testes will always pass.try/except
blocks so that you can
demonstrate to your code reviewers that you tried a new approach, but if the new approach is
not
what they were looking for, they can leave comments under the except
keyword.
try/except
blocks so that none of
your
functions or methods return None
.because of the level of indentation after the for loop
because of the end keyword at the end of the for loop
because of the block is surrounded by brackets ({})
because of the blank space at the end of the body of the for loop
x = {1,2,3,4,5}
x.add(5)
x.add(6)
{1, 2, 3, 4, 5, 5, 6}
{5, 6, 1, 2, 3, 4, 5, 6}
{6, 1, 2, 3, 4, 5}
{1, 2, 3, 4, 5, 6}
Explanation: The .add()
method adds the element to the set only if
it
doesn't exist.
fruit_info = {
'fruit': 'apple',
'count': 2,
'price': 3.5
}
my_keys = fruit_info.to_keys()
my_keys = fruit_info.all_keys()
my_keys = fruit_info.keys
my_keys = fruit_info.keys()
def be_friendly(greet = "How are you!", name):
pass
name
is a reserved word.np
, which choice will return True
?a = np.zeros([3,4])
b = a.copy()
np.array_equal(a,b)
a = np.empty([3,4])
b = np.empty([3,4])
np.array_equal(a,b)
a = np.zeros([3,4])
b = np.zeros([4,3])
np.array_equal(a,b)
a = np.array([1, np.nan])
np.array_equal(a,a)
// This is a comment
# This is a comment
-- This is a comment
/* This is a comment *\
import numpy as np
a = np.array([1,2,3])
b = np.array([4,5,6])
c = a*b
d = np.dot(a,b)
c = [ a[1] * b[1], a[2] * b[2], a[3] * b[3] ]
d = sum(c)
c = a[0] * b[0], a[1] * b[1], a[2] * b[2]
d = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
c = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
d = sum(a) + sum(b)
c = [ a[0] * b[0], a[1] * b[1], a[2] * b[2] ]
d = sum(c)
linalg.eig() and .matmul()
linalg.inv() and .dot()
linalg.det() and .dot()
linalg.inv() and .eye()
Explanation: Understanding this answer requires knowledge of linear algebra. Some systems of equations can be solved by the method of diagonalization, which involves finding the eigenvectors and eigenvalues of the system's matrix and multiplying related matrices.
my_list = (2, 'apple', 3.5)
my_list = [2, 'apple', 3.5]
my_list = [2, 'apple', 3.5].to_list()
my_list = to_list(2, 'apple', 3.5)
num_list = [21, 13, 19, 3, 11, 5, 18]
num_list.sort()
num_list[len(num_list) // 2]
Explanation: The median is the value separating the higher half from the lower half of a data sample. Here it is 13.
vector
of type np.array with 10,000
elements.
How can you turn vector
into a variable named matrix
with dimensions
100x100?matrix = (vector.shape = (100,100))
matrix = vector.to_matrix(100,100)
matrix = matrix(vector,100,100)
matrix = vector.reshape(100, 100)
def myFunction(country = "France"):
print("Hello, I am from", country)
myFunction("Spain")
myFunction("")
myFunction()
Hello, I am from Spain
Hello, I am from
Hello, I am from
Hello, I am from France
Hello, I am from France
Hello, I am from France
Hello, I am from Spain
Hello, I am from
Hello, I am from France
Hello, I am from Spain
Hello, I am from France
Hello, I am from France
sum(titanic['Survived'])
[x for x in titanic['Survived'] if x == 1]
len(titanic["Survived"])
sum(titanic['Survived']==0)
Explanation: The titanic['Survived']
returns a
pandas.Series
object, which contains the Survived
column of the
DataFrame
.
Adding the values of this column (i.e. sum(titanic['Survived'])
) returns
the
total number of survivors since a survivor is represented by a 1 and a loss by 0.
characters = ["Iron Man", "Spider Man", "Captain America"]
actors = ["Downey", "Holland", "Evans"]
# example output : [("IronMan", "Downey"), ("Spider Man", "Holland"), ("Captain America", "Evans")]
[(x,y)] for x in characters for y in actors]
zip(characters, actors)
[ ]
d = {}
for x in range(1, len(characters)):
d[x] = actors[x]
{x:y for x in characters for y in actors}
{x : x*x for x in range(1,100)}
def jaccard(a, b): return len (a | b) / len (a & b)
def jaccard(a, b): return len (a & b) / len (a | b)
def jaccard(a, b): return len (a && b) / len (a || b)
def jaccard(a, b): return a.intersection(b) / a.union(b)
[1,2,3] * 3
[3,2,3]
[1, 2, 3, 1, 2, 3, 1, 2, 3]
[3,6,9]
[1,2,3,4]
, what is the value of numbers[-2]
?() -empty parameter self -refers to all instances within a class init -a reserved method, aka a constructor init() -always executed when the class is being initiated
sin
function from the math
library.
What
is the correct syntax for importing only that function?using math.sin
import math.sin
from math import sin
import sin from math
0
the count of all True values
a type error
None
print ("foo" if (256).bit_length() > 8 else "bar")
random.uniform(0,50);plt.hist
random.gauss(50,20);plt.hist
random();plt.scatter
random.triangular(0,50);plt.bar
import numpy as np
a = np.arange(100)
b = a[50:60:2]
my_object.get_shape()
my_object.shape
my_object.dim()
len(my_object)
len(mylist); len(mylist)
1; len(mylist)
2; len(mylist)
0; len(mylist)
Explanation: Can use a break statement and the value being searched can be the first element of the list, given that it is non-empty.
import numpy as np
def can_matrices_be_multiplied (matrix1, matrix2):
rowsMat1, columnsMat1 = matrix1.shape
rowsMat2, columnsMat2 = matrix2.shape
if _____ == ______ :
print('The matrices can be multipled!')
return True
else:
return False
[(x, x+1) for x in range(1,5)]
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.fathername = super.name
self.name = name
def introduce(self):
print("My name is", self.name, "son of", self.fathername)
king = Person("Joffrey")
king.introduce()
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.fathername = self.name
self.name = name
def introduce(self):
print("My name is", self.name, "son of", self.fathername)
king = Person("Joffrey")
king.introduce()
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.name = name
def introduce(self):
print("My name is", self.name, "son of", super.name)
king = Person("Joffrey")
king.introduce()
class Father():
name = 'Robert'
class Person(Father):
def __init__(self, name):
self.name = name
def introduce(self):
print("My name is", self.name, "son of", base.name)
king = Person("Joffrey")
king.introduce()
Explanation: In the first, super does not have .name (should be self.name), The third drops Robert, and base is not defined in the 4th.
animals = {
'a': ['ant', 'antelope', 'armadillo'],
'b': ['beetle', 'bear', 'bat'],
'c': ['cat', 'cougar', 'camel']
}
animals = defaultdict(list, animals)
print(animals['b'])
print(animals['d'])
['beetle', 'bear', 'bat']
[]
['beetle', 'bear', 'bat']
# an exception will be thrown
['beetle', 'bear', 'bat']
None
['bat', 'bear', 'beetle']
[]
Explanation: Dictionaries usually result in an exception when using the square
bracket syntax. Defaultdict here returns a default value dedicated by the first parameter so
instead
of throwing an exception, they return the default. Note that this needs to be imported as
follows:
from collections import defaultdict
[x*2 for x in range(1,n)]
x = 18
if x > 10:
if x > 15:
print('A')
else:
print('B')
else:
print('C')
for i in range(5): pass
Explanation: Python threading is restricted to a single CPU at one time. The multiprocessing library will allow you to run code on different processors.
x = 5
y = 1 + (20 if x < 5 else 30)
Explanation: If x < 5 ==> y = 1 + 20 Else y = 1 + 30
Explanation: Pickling is the process of sterilizing a Python object, that is, conversion of a byte stream into Python object hierarchy. The reverse of this process is known as unpickling.
print("codescracker".endswith("er"))
print("programming".center())
x = 1j
print(x**2 == -1)
j
has not been initialized
Explanation: The letter j
acts as the imaginary unit in Python,
therefore x**2
means j**2
which is equal to -1
. The
statement
x**2 == -1
is evaluated as True
.
print(0xA + 0xB + 0xC)
Explanation: A, B and C are hexadecimal integers with values 10, 11 and 12 respectively, so the sum of A, B and C is 33.
for i in range(5):
print(i)
else:
print("Done!")
import functools
import time
def timer(MISSING_ARG_1):
@functools.wraps(func)
def wrapper(*args, **kwargs):
start_time = time.perf_counter()
rval = func(*args, **kwargs)
end_time = time.perf_counter()
duration = end_time - start_time
print(f"Executed in {duration:.4f} seconds")
return MISSING_ARG_2
return MISSING_ARG_3
@timer
def execution_fn():
for i in range(3):
time.sleep(1)
execution_fn()
Which of the following choices are the missing arguments?
MISSING_ARG_1 = wrapper
MISSING_ARG_2 = rval
MISSING_ARG_3 = func
MISSING_ARG_1 = func
MISSING_ARG_2 = rval
MISSING_ARG_3 = wrapper
MISSING_ARG_1 is empty
MISSING_ARG_2 = rval
MISSING_ARG_3 = wrapper
MISSING_ARG_1 is empty
MISSING_ARG_2 = rval
MISSING_ARG_3 = func
a = np.array([[1, 2], [3, 4], [5, 6]])
c = a[(a > 3) & (a < 11)]
print(c)
[[3, 4], [5, 6]]
[False, False, False, True, True, True]
[[0,0], [3, 4], [5, 6]]
[4 5 6]
apple
in the list with
the
string orange
?my_list = [2, 'apple', 3.5]
orange = my_list[1]
my_list[1] = 'orange'
my_list['orange'] = 1
my_list[1] == orange
randint
be called?[ [ [ randint(1,100) for i in range(m) ] for j in range(n) ] for k in range(p) ]
MyClass.__mro__
MyClass.hierarchy()
callable(MyClass)
dir(MyClass)
Explanation: MRO stands for Method Resolution Order. It returns a list of types the class is derived from, in the order they are searched for methods.
employees = {
'alice':{
'position':'Lead Developer',
'salary':1000
},
'bob':{
'position': 'Lead Artist',
'salary':2000
},
'charlie':{
'position':'cfo',
'salary':3000
}
}
employess['alice']['salary'] = employees['charlie']['salary']
employees.alice.salary = employees.charlie.salary
employees['alice'][1] = employees['charlie'][1]
employees['alice'].salary = employees['charlie'].salary
Explanation: This is accessing a key in a nested dictionary inside another dictionary
The command employees['alice']['salary'] = employees['charlie']['salary'] assigns the value of the 'salary' key in the dictionary of the employee 'charlie' to the 'salary' key in the dictionary of the employee 'alice'. It is the same thing as:
employees = {
'alice': {'position': 'Lead Developer', 'salary': 1000},
'bob': {'position': 'Lead Artist', 'salary': 2000},
'charlie': {'position': 'cfo', 'salary': 3000}
}
# or:
employees = {'alice': {'position': 'Lead Developer', 'salary': 1000},
'bob': {'position': 'Lead Artist', 'salary': 2000},
'charlie': {'position': 'cfo', 'salary': 3000}}
mylist = []
for i in range(m):
for j in range(n):
mylist.append((i,j))
Explanation: This code will run for m x n times, if you run this code, it will
create m x n tuples.
The first loop runs for m times and the inner loop will run for n
times.
While the single iteration of first loop will only be completed when all of the n iterations of
inner loop are completed. This is the same process for 2nd, 3rd, ... mth iterations for outer
loop.
Overall, both loops will run m x n times
{x : [y for y in range (1, x) if x % y == 0] for x in range (2, 100)}