Python Flashcards
What does it mean that Python has dynamic types and what practical side effects are a result of that?
Only runtime objects have a value, not the variables themselves (that store the objects). This allows you to store different types in the same variable during execution, and means you don’t have to declare variable types when declaring them.
Does Python have a strong or weak typing system?
Strong
What does it mean that Python is strongly typed?
Variables won’t change types unless it is explicitly cast to something else. So ‘125’ doesn’t automatically become an int when you try to add 4 to it, even though it could be done, you would have to explicitly cast it to an int yourself.
How to represent infinity?
inf = float(‘inf’) or import math, math.inf
What does REPL stand for?
Read Evaluate Print Loop
When will the code in the else condition of a for (or while) loop run?
If the loop completed without breaking.
Does the “or” operator return anything? If so, what? Does it always evaluate every operand and why or why not?
Yes. The first truthy operand, or the last operand regardless of its truthiness. No, it will stop as soon as it finds a truthy operand which could be the first.
Does the “and” operator return anything? If so what? Does it always evaluate every operand, and why or why not?
Yes, the last operand (if all were truthy) or the first non-truthy operand. No, it will stop early if it finds something non-truthy, as anything non-truthy would make the result non-truthy.
How to get the lowercase version of a string?
string.lower()
Name two ways to get environment variables w/ Python. Why is one preferred over the other?
os.environ[‘variable’] (will error if variable doesn’t exit) or os.getenv(‘variable’) better cause will return None if doesn’t exist, can optionally specify a default value.
How do you open a file in python for reading and writing?
f = open(‘path’, mode=’r+t’) or r+b for binary, t is text
How to open a new file in Python?
mode=’x’, which will error if file alread exists. ‘w’ would work but would blank out the file if it does exist.
What can you use in Python to ensure a file is closed once operations are complete?
with open() as var:
stuff
Will call close if stuff fails or completes.
How to access arguments passed to script?
Import sys, sys.argv. 0 is path to script. Or argparse
What is the flow for exception handling in python?
Try, except - if try hit an error, else - if no error, finally - runs regardless of if hit an error or not