Python Flashcards

(60 cards)

1
Q

Create new virtual environment

A

python -m venv tutorial-env

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

Install latest version of requests

A

python -m pip install requests

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

Install requests version 2.6.0

A

python -m pip install requests==2.6.0

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Uninstall requests

A

python -m pip uninstall requests

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

Display all of the packages installed

A

python -m pip list

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

Upgrade the requests package to the latest version

A

python -m pip install --upgrade requests

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

Freeze and restore packages to requirements.txt (assume Linux OS)

A

python -m pip freeze > requirements.txt
python -m pip install -r requirements.txt

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

How to perform regular and floor division

A

17 / 3
17 // 3

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

Swap two variables (one liner)

A
a, b = 0, 1
a, b = b, a
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Ternary operator example

A

"yay!" if 0 > 1 else "nay!"

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

How to see if variable is None

A

Prefer is for comparison to None

None is a singleton and is faster than ==
Also, custom types may implement different logic when handling == None.

v is None

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

word = 'Python'
Get last character (n) with slicing

A

word[-1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

word = 'Python'
Get first two characters (Py) with slicing

A

word[:2]
word[0:2]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

Reverse a string with slicing

A

word[::-1]

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

How to create raw string (i.e. special chars are not parsed in it)

A

r"C:\some\name"

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

Concatenate strings

A

“Hello “ + “world!” # => “Hello world!”
“Hello “ “world!” # => “Hello world!” (implicit concatenation)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

Will this work?
word[0] = 'J'

A

TypeError: strings are immutable

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

How to use format strings?

A

f"{name} is {len(name)} characters long."

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

How to convert something string? Two methods, what is the difference between them.

A

The str() function is meant to return representations of values which are fairly human-readable

repr() is meant to generate representations which can be read by the interpreter

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
20
Q

If statement

A
if
elif
else
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
21
Q

Case statement

A
match status:
  case 400:
    return "Bad request"
  case 401 | 403 | 404:
    return "Other error"
  case _:
    return "Something's wrong with the internet"
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
22
Q

While loop(s)

A
while a < 10:
  pass
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
23
Q

For loop

A
for i in range(5):
  print(i)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
24
Q

Use range to generate iterables:
- [5, 6, 7, 8, 9]
- [0, 3, 6, 9]

A

range(5, 10)
range(0, 10, 3)

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
25
How to define custom exception?
User-defined Exceptions should typically be derived from the `Exception` class, either directly or indirectly. ``` class MyException(Exception): pass ```
26
- Exception handling structure, all components. - How to handle single and multiple exceptions?
``` try: raise IndexError("This is an index error") except IndexError as e: # Handle single exception except (TypeError, NameError): # Handle multiple exceptions else: # Called when no exception was called finally: # Called in the end ```
27
throw new exception, indicate it was caused by `e`
`raise RuntimeError from e`
28
Throw exception, clear previous errors
`raise RuntimeError from None`
29
How to automatically cleanup file handle (like one from `open("myfile.txt")`) even in case of error. How is this mechanism called.
Instead of try/finally to cleanup resources you can use a with statement (will close file handle in all cases) ``` with open("myfile.txt") as f: for line in f: print(line) ``` Its managed by **Context Manger**
30
When is `except* ` used?
By using `except* ` instead of except, we can selectively handle only the exceptions in the group that match a certain type ``` try: f() except* OSError as e: print("There were OSErrors") except* SystemError as e: print("There were SystemErrors") ```
31
Define a function that returns multiple values (x, y)
``` def swap(x, y): return y, x x, y = swap(x, y) ```
32
Call a function `def add(x, y)` by naming its keyword arguments (in any order)
`add(y=6, x=5)`
33
What is the problem with the following code, how to solve it: ``` def f(a, L=[]): L.append(a) ```
**The default value is evaluated only once**. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes. ``` # Default mutable type def f(a, L=[]): L.append(a) f(1) # ... f(2) # Each call will use the same instance of L! ``` Fix: ``` def f(a, L=None): if L is None: L = [] L.append(a) return L ```
34
How to define arbitrary argument lists (postional and keyword) in functions?
`def all_the_args(*args, **kwargs)`
35
`def combined_example(a, /, b, *, c)` What do `/` and `*` mean in this function
`a` is positional only argument `b` is regular `c` is keyword only argument
36
How are variables scoped in python? What are `nonlocal` and `global` keywords?
Variables in python are function scoped. They always overwrite variables from outer scopes (i.e. they define new variable under given name in current scope) - `nonlocal x` - use x from outer function scope (e.g. when defining closure functions) - `global x` - use x from global scope.
37
How to define closure in python? Give example
Must use nonlocal to access factory method variables ``` def create_avg(): total = 0 count = 0 def avg(n): nonlocal total, count total += n count += 1 return total / count return avg avg = create_avg() avg(3) avg(5) avg(7) ```
38
Example lambda taking two arguments
`lambda x, y: x ** 2 + y ** 2`
39
Import `ceil` and `floor` from `math` module
`from math import ceil, floor`
40
Import everything from `math` module
`from math import *`
41
Import everything from `math` module, alias it to `m`
`import math as m`
42
What are `__init__.py` files
The `__init__.py` files are required to make Python treat directories containing the file as packages (unless using a namespace package, a relatively advanced feature). In the simplest case, `__init__.py` can just be an empty file, but it can also execute initialization code for the package or set the `__all__` variable
43
How to import module using relative path (same module, parent module, sibling module)
``` from . import echo # this module from .. import formats # parent module from ..filters import equalizer # sibling filters module ```
44
How to manually create an iterator from iterable and drain it?
``` our_iterator = iter(our_iterable) next(our_iterator) # => "one" next(our_iterator) # Raises StopIteration ```
45
How to define generator?
``` def double_numbers(iterable): for i in iterable: yield i + i ```
46
How to define generator expression?
Similar to list comprehensions but with parentheses instead of square brackets `sum(i*i for i in range(10))` These expressions are designed for situations where the generator is used right away by an enclosing function.
47
How to define function decorator (that do nothing, just skelton) ?
``` from functools import wraps def log_function(func): @wraps(func) def wrapper(*args, **kwargs): return func(*args, **kwargs) return wrapper ```
48
Round `x` to `n` digits
`round(x, n)`
49
String: capitalize - First char - First char of each word
``` str.capitalize() # first char capitalized str.title() # words start with an uppercase ```
50
String: justify text according to specified width. Set the text: - In the middle - On the left - On the right
``` str.center(width, fillchar=' ', /) str.ljust(width, fillchar=' ', /) str.rjust(width, fillchar=' ', /) ```
51
String: convert string to utf-8 bytes
`str.encode(encoding='utf-8')`
52
String: return true if string starts / ends with given string
``` str.startswith(prefix[, start[, end]]) str.endswith(suffix[, start[, end]]) ```
53
String: search substring (from start and from end). Two methods, how they differ.
``` # Return -1 if sub is not found. Method specific to string str.find(sub[, start[, end]]) str.rfind(sub[, start[, end]]) Like find(), but raise ValueError when the substring is not found. str.index(sub[, start[, end]]) str.rindex(sub[, start[, end]]) ```
54
String: Split string using separator. Join it using "-"
``` str.split(sep=None, maxsplit=-1) "-".join(iterable, /) ```
55
String: convert entire string to uppercase / lowercase letters
``` str.upper() str.lower() ```
56
String: trim spaces (from beginning, end, both sides)
``` # chars argument defaults to removing whitespace str.strip(chars=None, /) str.lstrip(chars=None, /) str.rstrip(chars=None, /) ```
57
String: replace substring
`str.replace(old, new, /, count=-1)`
58
Create `bytes` from hex string. Convert `bytes` to hex.
``` bytes.fromhex('2Ef0 F1f2 ') b'\xf0\xf1\xf2'.hex() ```
59
What is GIL?
The Python Global Interpreter Lock or GIL, in simple words, is a mutex (or a lock) that allows only one thread to hold the control of the Python interpreter.
60
What is walrus operator?
Assigns the result to the variable, and returns that value simultaneously. ``` if match := re.search(r'Error: (.*)', text): # 'match' is assigned AND evaluated for truthiness in one line print(f"Log details: {match.group(1)}") ```