What is a good way to ensure certain conditions are impossible in your app?
Use assertions!
\>\>\> **def** apply\_discount(price, discount):...**assert** discount \<= 100, 'Whoa! Were not paying people to take our merchandise!'...**return** price \* discount ...\>\>\> apply\_discount(14700, 50)735000\>\>\> apply\_discount(14700, 200) Traceback (most recent call last):File "", line 1, **in** \<module\>File "", line 2, **in** apply\_discount AssertionError: Whoa! Were **not** paying people to take our merchandise!
Remember that assertions can be disabled at runtime, so don’t use them to enforce rules.
Explain these Python naming conventions:
What are the keywords and builtins in Python?
\>\>\> **import** keyword \>\>\> keyword.kwlist ['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue','def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in','is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']\>\>\> **import** builtins \>\>\> dir(builtins)['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError','BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError','ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError','Exception', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning','GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError','IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError','NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError','PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError','ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError','SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError','UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning','ValueError', 'Warning', 'ZeroDivisionError', '\_', '\_\_build\_class\_\_', '\_\_debug\_\_', '\_\_doc\_\_', '\_\_import\_\_','\_\_loader\_\_', '\_\_name\_\_', '\_\_package\_\_', '\_\_spec\_\_', 'abs', 'all', 'any', 'ascii', 'bin', 'bool', 'breakpoint','bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr','dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr','globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len','license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow','print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted','staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
How do you get the size of something in memory?
\>\>\> **import** sys \>\>\> size = sys.getsizeof \>\>\> **print**(size('a'), 'bytes in memory')50 bytes **in** memory \>\>\> **print**(size('0'), 'bytes in memory')50 bytes **in** memory \>\>\> **print**(size('10'), 'bytes in memory')51 bytes **in** memory \>\>\> **print**(size('10\*10'), 'bytes in memory')54 bytes **in** memory \>\>\> **print**(size('9999999999999'), 'bytes in memory')62 bytes **in** memory \>\>\> **print**(size('999\*\*999'), 'bytes in memory')57 bytes **in** memoryWhat will this code output? Explain.
\>\>\> **from** collections **import** namedtuple \>\>\> Person = namedtuple('Person', 'first\_name last\_name age')\>\>\> bob = Person('Bob', 'Smith', 47)\>\>\> **print**(f'''... {bob[0]}... {bob.last\_name}... {type(bob)}... ''')Tuples are great for storing ordered data you don’t want changed, like configuration settings.
But if they get really long, it can get hard to remember which values are in which index. Named Tuples let you name the values:
\>\>\> **from** collections **import** namedtuple \>\>\> Person = namedtuple('Person', 'first\_name last\_name age')\>\>\> bob = Person('Bob', 'Smith', 47)\>\>\> **print**(f'''... {bob[0]}... {bob.last\_name}... {type(bob)}... ''') Bob Smith \<**class**'\_\_main\_\_.Person'\>Elegantly loop through a csv file…
**import** csv **from** collections **import** namedtuple **with** open("data.csv") **as** f: reader = csv.reader(f) top\_row = next(reader) top\_row = [t.lower().split() **for** t **in** top\_row] top\_row = ['\_'.join(t) **for** t **in** top\_row] Data = namedtuple("Data", top\_row) data = [Data(\*r) **for** r **in** reader]**print**(data)#or**import** pandas **as** pd data = pd.read\_csv('data.csv').to\_dict(orient='row')**print**(data)What does this code output? Explain.
\>\>\> line = (1, 2, 3, 4, 5)\>\>\> a, \*b, c = line \>\>\> **print**(f'''... {a}... {b}... {c}... {type(line)}''')The splat * lets you unpack variables:
\>\>\> line = (1, 2, 3, 4, 5)\>\>\> a, \*b, c = line \>\>\> **print**(f'''... {a}... {b}... {c}... {type(line)}''')1[2, 3, 4]5\<**class**'tuple'\>Find the most common words in some text.
\>\>\> #Get some text ...how about the Zen of Python?... **import** this \>\>\> text = "".join([this.d.get(c, c) **for** c **in** this.s])\>\>\>\>\>\> **from** collections **import** Counter \>\>\> word\_count = Counter(text.split())\>\>\> **print**(word\_count.most\_common(3))[('is', 10), ('better', 8), ('than', 8)]Sort these by last name alphabetically:
‘Daniel Dennett’, ‘Ned Batchelder’, ‘Raymond Hettinger’, ‘Ludwig Wittgenstein’, ‘Brian Jones’, ‘David Beazley’
\>\>\> names = ['Daniel Dennett', 'Ned Batchelder', 'Raymond Hettinger', 'Ludwig Wittgenstein', 'Brian Jones', 'David Beazley']\>\>\> **print**(sorted(names, key=**lambda** name: name.split()[-1].lower()))['Ned Batchelder', 'David Beazley', 'Daniel Dennett', 'Raymond Hettinger', 'Brian Jones', 'Ludwig Wittgenstein']\>\>\>
What will this print? Explain.
\>\>\> **print**(f'''... {True}... {True.\_\_class\_\_}... {True.\_\_class\_\_.\_\_bases\_\_}... {True.\_\_class\_\_.\_\_bases\_\_[0]}... {True.\_\_class\_\_.\_\_bases\_\_[0].\_\_bases\_\_}... {True.\_\_class\_\_.\_\_bases\_\_[0].\_\_bases\_\_[0]}... {type(True).\_\_mro\_\_}... ''')\>\>\> **print**(f'''... {True}... {True.\_\_class\_\_}... {True.\_\_class\_\_.\_\_bases\_\_}... {True.\_\_class\_\_.\_\_bases\_\_[0]}... {True.\_\_class\_\_.\_\_bases\_\_[0].\_\_bases\_\_}... {True.\_\_class\_\_.\_\_bases\_\_[0].\_\_bases\_\_[0]}... {type(True).\_\_mro\_\_}... ''')True\<**class**'bool'\>(\<**class**'int'\>,)\<**class**'int'\>(\<**class**'object'\>,)\<**class**'object'\>(\<**class**'bool'\>, \<**class**'int'\>, \<**class**'object'\>) \<\<-Method Resolution OrderHow do you figure out where everything is in Python?
\>\>\> **from** pprint **import** pprint \>\>\> **import** sys \>\>\> pprint(sys.path)['','/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip','/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8','/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload','/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages']\>\>\> pprint(sys.modules){'\_\_main\_\_': \<module '\_\_main\_\_' (built-**in**)\>,'\_abc': \<module '\_abc' (built-**in**)\>,'\_ast': \<module '\_ast' (built-**in**)\>,'\_bootlocale': \<module '\_bootlocale' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/\_bootlocale.py'\>,'\_codecs': \<module '\_codecs' (built-**in**)\>,'\_collections': \<module '\_collections' (built-**in**)\>,'\_collections\_abc': \<module '\_collections\_abc' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/\_collections\_abc.py'\>,'\_frozen\_importlib': \<module 'importlib.\_bootstrap' (frozen)\>,'\_frozen\_importlib\_external': \<module 'importlib.\_bootstrap\_external' (frozen)\>,'\_functools': \<module '\_functools' (built-**in**)\>,'\_heapq': \<module '\_heapq' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/\_heapq.cpython-38-darwin.so'\>,'\_imp': \<module '\_imp' (built-**in**)\>,'\_io': \<module 'io' (built-**in**)\>,'\_locale': \<module '\_locale' (built-**in**)\>,'\_opcode': \<module '\_opcode' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/\_opcode.cpython-38-darwin.so'\>,'\_operator': \<module '\_operator' (built-**in**)\>,'\_posixsubprocess': \<module '\_posixsubprocess' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/\_posixsubprocess.cpython-38-darwin.so'\>,'\_signal': \<module '\_signal' (built-**in**)\>,'\_sitebuiltins': \<module '\_sitebuiltins' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/\_sitebuiltins.py'\>,'\_sre': \<module '\_sre' (built-**in**)\>,'\_stat': \<module '\_stat' (built-**in**)\>,'\_thread': \<module '\_thread' (built-**in**)\>,'\_warnings': \<module '\_warnings' (built-**in**)\>,'\_weakref': \<module '\_weakref' (built-**in**)\>,'\_weakrefset': \<module '\_weakrefset' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/\_weakrefset.py'\>,'abc': \<module 'abc' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/abc.py'\>,'ast': \<module 'ast' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/ast.py'\>,'atexit': \<module 'atexit' (built-**in**)\>,'builtins': \<module 'builtins' (built-**in**)\>,'codecs': \<module 'codecs' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/codecs.py'\>,'collections': \<module 'collections' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/collections/\_\_init\_\_.py'\>,'collections.abc': \<module 'collections.abc' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/collections/abc.py'\>,'contextlib': \<module 'contextlib' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/contextlib.py'\>,'copyreg': \<module 'copyreg' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/copyreg.py'\>,'dis': \<module 'dis' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/dis.py'\>,'encodings': \<module 'encodings' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/encodings/\_\_init\_\_.py'\>,'encodings.aliases': \<module 'encodings.aliases' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/encodings/aliases.py'\>,'encodings.latin\_1': \<module 'encodings.latin\_1' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/encodings/latin\_1.py'\>,'encodings.utf\_8': \<module 'encodings.utf\_8' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/encodings/utf\_8.py'\>,'enum': \<module 'enum' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/enum.py'\>,'errno': \<module 'errno' (built-**in**)\>,'functools': \<module 'functools' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/functools.py'\>,'genericpath': \<module 'genericpath' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/genericpath.py'\>,'heapq': \<module 'heapq' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/heapq.py'\>,'importlib': \<module 'importlib' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/\_\_init\_\_.py'\>,'importlib.\_bootstrap': \<module 'importlib.\_bootstrap' (frozen)\>,'importlib.\_bootstrap\_external': \<module 'importlib.\_bootstrap\_external' (frozen)\>,'importlib.abc': \<module 'importlib.abc' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/abc.py'\>,'importlib.machinery': \<module 'importlib.machinery' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/machinery.py'\>,'importlib.util': \<module 'importlib.util' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/importlib/util.py'\>,'inspect': \<module 'inspect' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/inspect.py'\>,'io': \<module 'io' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/io.py'\>,'itertools': \<module 'itertools' (built-**in**)\>,'keyword': \<module 'keyword' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/keyword.py'\>,'linecache': \<module 'linecache' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/linecache.py'\>,'marshal': \<module 'marshal' (built-**in**)\>,'math': \<module 'math' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/math.cpython-38-darwin.so'\>,'opcode': \<module 'opcode' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/opcode.py'\>,'operator': \<module 'operator' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/operator.py'\>,'os': \<module 'os' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/os.py'\>,'os.path': \<module 'posixpath' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/posixpath.py'\>,'pkgutil': \<module 'pkgutil' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/pkgutil.py'\>,'platform': \<module 'platform' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/platform.py'\>,'posix': \<module 'posix' (built-**in**)\>,'posixpath': \<module 'posixpath' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/posixpath.py'\>,'pprint': \<module 'pprint' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/pprint.py'\>,'pydoc': \<module 'pydoc' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/pydoc.py'\>,'re': \<module 're' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/re.py'\>,'readline': \<module 'readline' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/readline.cpython-38-darwin.so'\>,'reprlib': \<module 'reprlib' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/reprlib.py'\>,'rlcompleter': \<module 'rlcompleter' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/rlcompleter.py'\>,'select': \<module 'select' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload/select.cpython-38-darwin.so'\>,'selectors': \<module 'selectors' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/selectors.py'\>,'signal': \<module 'signal' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/signal.py'\>,'site': \<module 'site' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site.py'\>,'sre\_compile': \<module 'sre\_compile' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/sre\_compile.py'\>,'sre\_constants': \<module 'sre\_constants' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/sre\_constants.py'\>,'sre\_parse': \<module 'sre\_parse' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/sre\_parse.py'\>,'stat': \<module 'stat' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/stat.py'\>,'subprocess': \<module 'subprocess' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/subprocess.py'\>,'sys': \<module 'sys' (built-**in**)\>,'threading': \<module 'threading' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/threading.py'\>,'time': \<module 'time' (built-**in**)\>,'token': \<module 'token' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/token.py'\>,'tokenize': \<module 'tokenize' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/tokenize.py'\>,'traceback': \<module 'traceback' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/traceback.py'\>,'types': \<module 'types' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/types.py'\>,'urllib': \<module 'urllib' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/\_\_init\_\_.py'\>,'urllib.parse': \<module 'urllib.parse' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/urllib/parse.py'\>,'warnings': \<module 'warnings' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/warnings.py'\>,'weakref': \<module 'weakref' **from**'/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/weakref.py'\>,'zipimport': \<module 'zipimport' (frozen)\>}Explain * and **
*args and **kwargs is a common idiom for accepting an arbitrary number of arguments to functions:
\>\>\> **def** foo(\*args):...**for** a **in** args:...**print**(a)...\>\>\> foo(1,2,3)123\>\>\> foo(a=1, b=2, c=3) Traceback (most recent call last):File "<stdin>"</stdin>, line 1, **in** \<module\>TypeError: foo() got an unexpected keyword argument 'a'\>\>\>\>\>\> **def** foo(\*\*kwargs):...**for** a **in** kwargs:...**print**(a, kwargs[a])...\>\>\> foo(1,2,3) Traceback (most recent call last):File "<stdin>"</stdin>, line 1, **in** \<module\>TypeError: foo() takes 0 positional arguments but 3 were given \>\>\> foo(a=1, b=2, c=3) a 1 b 2 c 3
How do you go to a specific line number in Sublime Text 3?
ctrl-g
How can you quickly inspect an object?
\>\>\> **from** django.contrib.auth **import** get\_user\_model \>\>\> **from** pprint **import** pprint \>\>\> User = get\_user\_model()\>\>\> user = User.objects.first()\>\>\> pprint(user.\_\_dict\_\_){'\_state': \<django.db.models.base.ModelState object at 0x10352e5e0\>,'age': None,'date\_joined': datetime.datetime(2020, 2, 8, 17, 38, 42, 384643, tzinfo=\<UTC\>),'email': 'asdf@asdf.com','first\_name': '','id': 1,'is\_active': True,'is\_staff': True,'is\_superuser': True,'last\_login': datetime.datetime(2020, 2, 8, 19, 33, 29, 257231, tzinfo=\<UTC\>),'last\_name': '','password': 'pbkdf2\_sha256$180000$HDGLb5M1aoMb$nCG7eCIlAbVucVwMAsgbxWA5Vgz2P4ihNGF+55r5FDA=','student\_id': None,'username': 'admin'}Write the shortest possible function using any() to test for a palindrome.
Write the shortest possible function using all() to test for a palindrome.
**def** palindromic(sequence):"""Return True if the sequence is the same thing in reverse."""**return** all( n == m **for** n, m **in** zip(sequence, reversed(sequence)))
**def** palindromic(sequence):"""Return True if the sequence is the same thing in reverse."""**return** **not** any( n != m **for** n, m **in** zip(sequence, reversed(sequence)))