Python Flashcards
Memorise Python Syntax
How would you define a function in Python?
def functionName(args...): return value
What is the equivalent of a javascript array in python?
It’s a list.
How do you define a list in Python?
listName = []
How do you initialize a list with 11 slots in python?
list = [None] * 11
Are python lists typed?
No.
How do you define a class in python?
class MyCustomHashTable: def \_\_init\_\_(self, length): self.table = ['None'] * length
def findItemHashPosition(self, item): return remainder(item, self.length()) ~~~ ~~~
How do you convert a string to integer in python?
(int('1') == 1) == True
How do you convert an integer to string in python?
('{}'.format(1) == '1') == True
How do you define a calculated property in Python?
You can define calculated properties in python by using the @property decorator. The @property decorator acts as a getter and enables retrieving its result by simply accessing its name like a property. ` MyCustomHashTable(11).tableSize `
class MyCustomHashTable:
def \_\_init\_\_(self, length): self.table = ['None'] * length ~~~
@property def tableSize(self): return len(self.table)
print(MyCustomHashTable(11).tableSize) // prints 11
~~~
How do you define infinity in Python?
print(float("inf") > 9999 // prints True
How do you check if a value is a bool in Python?
There are three ways to check type equality in Python.
print(type(True) == bool) print(isinstance(True, bool)) print(issubclass(True, bool))
A few more things to consider.
isinstance
Use this built-in function to find out if a given object is an instance of a certain class or any of its subclasses. You can even pass a tuple of classes to be checked for the object. The only gotcha you will discover is this: in Python a bool object is an instance of int! Yes, not kidding!
issubclass
This built-in function is similar to isinstance, but to check if a type is an instance of a class or any of its subclasses. Again, the only gotcha is that bool type is subclass of int type.
type
If a single argument (object) is passed to type() built-in, it returns type of the given object. If three arguments (name, bases and dict) are passed, it returns a new type object.
A few more things to consider…
>>> isinstance(True, int) True >>> isinstance(True, float) False >>> isinstance(3, int) True >>> isinstance([1,2,3], list) True >>> isinstance("aa", str) True >>> isinstance(u"as", unicode) True >>> issubclass(bool, int) True
How do you iterate through the characters of a string in Python?
A string in python is iterable and has native support.
for char in "string": print char
That prints
s t r i n g