What is the python equivalent to javascript's null?
None
What do python's functions return by default?
None
What will the following evaluate to: c = true
What ever the value of the variable "true" is. Use True
to represent a boolean value.
What is the python equivalent of Javascript's &&
and
What is the python equivalent of Javascript's ||
or
What is the python equivalent of Javascript's !
not
Which in the following list evaluate to True
?
item | evalues to: |
---|---|
['a'] | True |
[range(1)] | true |
None | False |
'' | False |
' ' | True |
(0) | True |
() | False |
range() | Throws error |
range(0) | False |
How would you assure input prints as an integer?
Cast it to int: print(int(19))
How would you assure input prints with decimal places?
Cast it to float: float()
or enter it as a float: 2.24
or 2.0
What is wrong with the following:
a = 17.0
b = '17'
print(a + ' and ' + b)
TypeError: unsupported operand type(s) for +: 'float' and 'str'.
Python does not automatically convert types like Javascript does.
What are the two significant differences in arithmetic operators in Python from Javascript?
Math.pow()
is Javascript. **
is Python
//
is integer division in Python
What is integer division?
The reverse of modulo, where the answer is rounded:
5 // 2 = 2
7 / 2 = 3.5
7 // 2 = 3
7 % 2 = 1
How do you quote a string that is going to span multiple lines?
'''
. Then line breaks will be preserved:
print('''My instructions are very long so to make them
more readable in the code I am putting them on
more than one line. I can even include "quotes"
of any kind because they won't get confused withthe end of the string!''')
Can you use 3-quotes ("""
) in place of 3 single quotes '''
to accomplish the same thing, quotes spanning multiple lines?
Yes, but convention is to reserve """
for multi-line comments and function doc strings.
How would you create a function docstring in python?
def print_hello(name):
"""
This is a docstring that explains what the function does.
It can be multiple lines, handy!
You can use any combination of ' and " in these becausepython is looking for ending triple " characters
to determine the end.
"""
print(f"Hello, {name}")
print_hello('Mary')
Output:
Hello, Mary.
How do you determine the length of a string?
len("Spaghetti")
-> returns 9
How do you extract i
from the string "spaghetti"
print ("Spaghetti"[-1])
How do you extract 'paghetti' from the string "spaghetti"?
print("Spaghetti"[1:])
How would you extract 'hett' from the string 'spaghetti'?
print("Spaghetti"[4:-1])
In string indexing, does the 2nd term include the ending letter?
No!
Do indexes past the beginning or end of a string yield an error?
print("Spaghetti"[15])
Yes! IndexError: string index out of range
Does a range past the beginning or end of a string yield an error?
No!
What does the following yield?
print("Spaghetti"[15])
IndexError: string index out of range
What does the following yield?
print("Spaghetti"[:15])
Spaghetti
What does the following yield?
print("Spaghetti"[-15:])
Spaghetti
What does the following yield?
print("Spaghetti"[15:20])
An empty string
What does the following yield?
print("Spaghetti"[4:4]
An empty string. Remember, the last argument is one past the index you want.
What is the python equivalent of "mystring".indexOf(s)
?
"mystring".index("s")
How do you count the number of "t's" in "Spaghetti"?
print("Spaghetti".count("t"))
: prints 2
In python, how do you concatenate two stirngs?
print("gold" + "fish")
Print the following using the String.format()
method:
"Your name is <first_name> <last_name>"
print("Your name is {0} {1}".format(first_name, last_name))
Print the following using the f-string
"Your name is <first_name> <last_name>"
print(f'Your name is {first_name} {last_name}')
What string method will turn all characters into upper case?
s.upper()
What string method will turn all characters into lower case
s.lower()
What string method will return True
if all of the characters are lowercase?
s.islower()
What string method will return False
if any of the characters are not uppercase?
is.upper()
What string method will return True
if it begins with a "He"?
s.startswith("He")
What string method will return False
if the string doesn't end with "lo"
s.endswith("lo")
What string method will return an array based upon space separators?
s.split()
: This is like Javascript split, but no input is considered splitting on spaces.
Split the folowing string into an array of strings, removing the "-"
s = "i-am-a-dog"
s.split("-")
Will s.upper()
mutate your string?
No. Your original string remains intact. s.upper()
returns a copy of the string, converted to upper case
How would you determine if a string is not blank, and has only letters?
s.isalpha()
How would you determine if a string is not blank, and contains only numeric characters?
isdecimal()
How would you determine if a string is not blank, and contains either or both letters and numbers?
isalnum()
How would you determine whether a string consists only of spaces, tabs, and newlines and is not blank?
isspace()
How would you determine whether every word in a string begin with an uppercase letter, followed only by lowercase letters?
istitle()
Define duck typing
It is better to ask for forgiveness, than ask for permission.
If it looks like a duck and quacks like a duck, then it must be a duck
This is where <try> blocks should be used to enforce data integrity
How are variables scoped in python?
Variables are block scoped.
Can you reassign variables in python?
a = 'Any old string'
a = 5
Yes. Much like let
in javascript
Can you chain assignments?
count = max = min = 0
Yes
Is ===
a valid comparison operator in Python?
No. Use ==
The following Javascript comparison operators - are they different in Python?
>
<
>=
<=
==
!=
Nope. They're the same
Order the precedence of the following:
and
)or
)not
)
not
) are applied first (part of each number)and
) happen nextor
) are the last stepFix the following line of code:
print(a == not b)
print (a == (not b))
not must either be on the left of the expression, or must be separated with parens. Otherwise python will try to evaluate (a == not) first. (Left to right)
Will the following code evaluate to True if a is not the same as b?
print(not a == b)
Yes.
What is short-circuit evaluation?
When the left side of the comparison determines the outcome, the right side is not evalutated
Will the right side of comparison be evaluated in the case of True
and ...
Yes
Will the right side of the expression be evaluated in the case of False
and ...
No
Will the right side of the expression be evaluated in the case of True
or ...
No
Will the right side of the expression be evaluated in the case of False
or ...
Yes
Which of the following assignment operators are NOT supported in Javascript
+=
-=
*=
/=
%=
**=
//=
**=
//=
How do you write an if, else if, else statement in Python?
if name == 'Monica':
print('Hi, Monica.')
elif: age < 12:
print('You are not Monica, kiddo.')
else:
print('You are neither Monica nor a little kid.')
How do you write a for loop to iterate over every letter in the string "abcdefg"?
for c in "abcdefg":
print(c)
How do you write a for loop to execute 5 times?
for i in range(5):
How would you see what is included in a range?
a = range(5)
print(list(a))
If you don't convert a to a list, you will get: range(0, 5)
.
Converting a to a list prints: [0, 1, 2, 3, 4]
What is the structure in Python called, that has key/value pairs?
Dictionaries
What type of parens are used in dictionaries? {}
, ()
or []
{}
. Think Dictionaries are the same as Javascript key/value pairs - and they are Javascript objects.
How would you loop over all of the values in a dictionary?
spam = {'color': 'red', 'age': 42}
for v in spam.values():
print(v)
Write code that will iterate over the following tuples, destructuring them to use in your for loop
spam = [ ('color', 'red'), ('age', 42) ]
spam = [('color', 'red'), ('age', 42) ]
for k, v in spam:
print('Key: ' + k + ' Value: ' + str(v))
How do you stop further code evaluation in a while loop, and return to the while condition?
continue
How do you get out of a while loop prematurely?
break
Write a while loop that will execute 5 times, then exit using a break statement
spam = 0
while True:
print('Hello, world.')
spam += 1
if spam < 5:
continue
break
How do you define a function in python?
Replace the "function" keyword in Javascript with the "def" keyword. Also add a ":" at the end of the function declaration.
def printCopyright():
print("Copyright 2020. Me, myself and I. All rights reserved.")
Write a function that will add two numbers together, passing in positional arguments
def add (num1, num2):
return (num1 + num2)
print(add(2, 3)) # <= 5
Write a function that takes a default argument
def greeting(name, saying="Hello"):
print(saying, name)
greeting("Monica") #=> Hello Monica
greeting("Monica", saying="Hi") #=> Hi Monica
What is wrong with the following code?
def appendItem(itemName, itemList = [] ):
itemList.append(itemName)
return itemList
print(appendItem('notebook'))
print(appendItem('pencil))
print(appendItem('eraser'))
Using a mutable object for a default parameter will yield unexpected results. All invocations of the function reference the same mutable object:
print(appendItem('notebook')) #=> ['notebook']
print(appendItem('pencil)) #=> ['notebook', 'pencil']
print(appendItem('eraser')) #=> ['notebook', 'pencil', 'eraser']
What is the Python equivalent to fat arrow functions in Javascript?
Lambda
How do you write a Lambda function in Python?
toUpper = lambda s: s.upper()
toUpper('hello') #=> HELLO
What is the difference in writing Lambdas and fat arrow functions in Javascript?
Lambda functions, although they may be written as multi-line functions, it is considered bad form to write a multi-line Lambda function. If they can't be written on one line, better to use a regular function in Python.
What is the result of running the following code?
def average(num1, num2):
return num1 + num2 / 2
average(1)
Unlike Javascript, Python will throw an error.
# => TypeError: average() missing 1 required positional argument: 'num2'
What is the result of running the following code?
def average(num1, num2):
return num1 + num2 / 2
average(1, 2, 3)
# => TypeError: average() takes 2 positional arguments but 3 were given
How would you write a function that accepts a variable length of positional arguments?
def add(a, b, *args):
total = a +
for n in args:
total += n
return total
add(1, 2) # Args is none, returns 3
add(2, 3, 4, 5) #args is 4 and 5, returns 14
What is a keyword argument?
Keyword arguments use the name of the params in the function declaration to assign values in the function call.
def my_function(child3, child2, child1):
print("The youngest child is " + child3)
my_function(child1 = "Emil", child2 = "Tobias", child3 = "Linus")
Can you pass keyword arguments to a function call in a different order than the params listed in the function declaration?
Yes. You can pass your arguments in any order when you're using keyword arguments.
Using the following kwargs, and code, what will be printed?
def print_names_and_countries(greeting, **kwargs):
for k, v in kwargs.items():
print(greeting, k, "from", v)
print_names_and_countries("Hi",
Monica="Sweden",
Charles="British Virgin Islands",
Carlo="Portugal")
# kwargs would be:
# {
# 'Monica': 'Sweden',
# 'Charles': 'British Virgin Islands',
# 'Carlo': Portugal
# }
# prints:
#Hi Monica from Sweden
#Hi Charles from British Virgin Islands
#Hi Carlo from Portugal
What does the kwargs structure in the above code look like?
{'Monica': 'Sweden', 'Charles': 'British Virgin Islands', 'Carlo': 'Portugal'}
Is the following legal?
def example(arg_1, arg_2, *args, kw_1="shark", kw_2="blowfish", **kwargs):
pass
Yes. arg_1, arg_2 are positional parameters. *args would take the rest of the unnamed arguments, kw_1 and kw_2 are default keyword args, and the rest of the args go into kwargs.
What is the output for the following code?
def example(arg_1, arg_2, *args, kw_1="shark", kw_2="blowfish", **kwargs):
print("arg_1: ", arg_1)
print("arg_2: ", arg_2)
print("*args: ", args)
print("kw_1: ", kw_1)
print("kw_2: ", kw_2)
print("kwargs: ", kwargs)
example("Arg1", "Arg2", "args1", "args2", "args3", kw_1="myShark", Hello="Hello", Monica="Sweden", Charles="British Virgin Islands")
arg_1: Arg1
arg_2: Arg2
*args: ('args1', 'args2', 'args3')
kw_1: myShark
kw_2: blowfish
kwargs: {'Hello': 'Hello', 'Monica': 'Sweden', 'Charles': 'British Virgin Islands'}
Are Lists mutable?
Yes!
How do you determine if something is in a list?
print(1 in [1, 2, 3]) #>True
Using the list built in function, declare a list called specials
specials = list()
How do you declare an empty_list?
empty_list = []
What are sets?
Unordered collection of distinct objects
How do you define a set?
Sets use curlies like dictionaries: school_bag = {'book', 'paper', 'pencil' }
How do you test an element is in a set?
The same way you test an element is in a dictionary: Print(1 in {1, 1, 2, 3}) #> True
What is a Tuple?
Tuples are immutable lists of items
How would you convert a set into a tuple?
a = { 1, 2, 3 } # > Create a set
a = tuple(a) # > Cast it to a tuple
What is this?
colors = 'red', 'blue', 'green'
numbers = 1, 2, 3
Tuple. You can declare a tuple with or without parenthesis.
How do you test a value exists in a tuple?
The same way you test a value is in a set or dictionary: print(1 in (1, 2, 3)) # > True
What is a range?
A range is an immutable list of numbers. Often they are used in for
loops
What are the 3 elements of a range?
Which is required when specifying a range?
Only the stop param is required.
In the following list, write a range that will include all elements:
[ 0, 1, 2, 3, 4 ]
range(5) # > range(0,5) ... or list(range(5)) yields [0, 1, 2, 3, 4]
Define a range that starts at 0, goes up to 25, and prints in steps of 5
range(0,25,5) # > [0, 5, 10, 15, 20]
Write a function that will take a list, and determine which elements are odd
def isOdd(num):
return num % 2
filtered = filter(isOdd, [1,2,3,4]) # > <filter object at 0x10d565a90>
print(list(filtered)) # > [1, 3]
Transform a list to uppercase
def toUpper(str):
return str.upper()
upperCased = map(toUpper, ['a', 'b', 'c']) # > >map object at 0x10d5658b0<
print(list(upperCased)) # => ['A', 'B', 'C']
Sorted a list, and reversed for the list ['Banana', orange', 'apple']
sortedItems = sorted(['Banana', 'orange', 'apple'], key=str.lower, reverse=True)
Transform the list ['First', 'Second', 'Third', 'Fourth']
into tuples of the form (1, 'First'), (2, 'Second'), (3, 'Third'), (4, 'Fourth')
quarters = ['First', 'Second', 'Third', 'Fourth']
enumerate(quarters) # > >enumerate object at 0x10d585080>
print(enumerate(quarters, start=1)) # [(0, 'First'), (1, 'Second'), (2, 'Third'), (3, 'Fourth')]
Convert the two lists into one list of triplets:
x_coords = [0, 1, 2, 3, 4]
y_coords = [2, 3, 5, 3, 5]
z_coords = [3, 5, 2, 1, 4]
Use zip:
coords = zip(x_coords, y_coords, z_coords)
print(list(coords)) # => [ (0, 2, 3), (1, 3, 5), (2, 5, 2), (3, 3, 1), (4, 5, 4)]
Determine the length of the following [1, 2, 3]
len([1, 2, 3]) # => 3
Determine the length of the following: { 'Name': 'Bob', 'Email': 'bob@bob.com'}
len({ 'Name': 'Bob', 'Email': 'bob@bob.com'}) # > 2
Determine the max value in: [1, 4, 6, 2]
max[1, 4, 6, 2]
Determine the min value of : [1, 4, 6, 2]
min([1, 4, 6,2])
Determine the sum of (1, 2, 3)
sum(1, 2, 3)
Determine if any of the list evaluates to true: [True, False, False]
any([True, False, False]) :
This applies to truthy/falsey values as well
Determine if ALL of the list have truthy values: ['a', 'b', 'c']
all(['a','b','c']) # > True
How do you determine all the attributes of an object, including it's methods and dunder methods?
dir()
['__call__', '__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__self__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__text_signature__']
Import the Node class from your tree.py file in the same directory
Without a __init__.py in your import directory: from tree import Node
With an __init__.py in your import directory: from .tree import Node
In your math directory, you have files addition, subtraction, division and multiplication. Make them available to other files for import.
In your math directory, add the file named __init__.py Then add the following lines to __init__.py:
from .addition import add
from .subtraction import subtract
from .division import divide
from .multiplication import multiply
Using the math library you just prepared for export, import the add method, such that you do NOT have to specify math.add()
but rather add()
from math import add
>
Define a class called AngryBird with a constructor setting values x and y to passed in values, or default values of 0
class AngryBird:
def __init__(self, x=0, y=0):
self._x = x
self._y = y
In your class you wrote above, define a getter and a setter property that will handle the value of x
#Getter
@property
def x(self):
return self._x
#Setter
@x.setter
def x(self, value)
if value < 0:
value = 0
self._x = value
Also in the class you wrote above, define a dunder repr method that will print out a useful string indicating the state of your class
#Dunder Repr ... called by 'print'
def __repr++(self):
return f"<AngryBird ({self._x}, {self._y})>" "
What is the constructor method in Python?
def __init__(self):
How do you call the super constructor for your constructor?
super().__init__()
What are list comprehensions?
They are a way to transform a list from one format to another. They are a Pythonic
alternative to using map
or filter
Transform the following code into a list comprehension:
squares = []
for i in range(10):
squares.append(i**2)
print(squares)
Remember, the format for a list comprehension is: newList = [value loop condition]
squares = [i**2 for i in range(10)] # => Where i**2 is the value, and for i in range(10) is the loop
Write a list comprehension to print out all the vowels in the following sentence: sentence = 'the rocket came back from mars'
Remember, the format for a list comprehension is: newList = [value loop condition
Here the value is the character we're printing, the loop is for each character in the sentence, and the condition is the if statement
sentence = 'the rocket came back from mars'
vowels = [character for character in sentence if character in 'aeiou']
print(vowels) # => ['e', 'o', 'e', 'a', 'e', 'a', 'o', 'a']
Write a list comprehsion that will take the following dictionary and capitalize the first letter of all the keys:
person = {
'name': 'Corina',
'age': 32,
'height': 1.4
}
newPerson = { key.title(): value for key, value in person.items() }
Title case the following dictionary keys and values:
person = {
'firstName': 'corina',
'lastName': 'jones',
'homeTown': 'concord'
}
First, what will the for-loop look like to do this?
for key, value in person.items(): # To get the key and the value, use the items() method
newPerson = { key.title() : value.title() } # Title case both the key and the value
print(newPerson) # Just so we can see what we've done to confirm
{'Firstname': 'Corina'}
{'Lastname': 'Jones'}
{'Hometown': 'Concord'}
newList = [value loop condition]
value: { key.title() : value.title() }
loop: for key, value in person.items()
newPerson = { key.title(): value.title() for key, value in person.items() }
print(newPerson)
#prints: {'Firstname': 'Corina', 'Lastname': 'Jones', 'Hometown': 'Concord'}