Create new virtual environment
python -m venv tutorial-env
Install latest version of requests
python -m pip install requests
Install requests version 2.6.0
python -m pip install requests==2.6.0
Uninstall requests
python -m pip uninstall requests
Display all of the packages installed
python -m pip list
Upgrade the requests package to the latest version
python -m pip install --upgrade requests
Freeze and restore packages to requirements.txt (assume Linux OS)
python -m pip freeze > requirements.txtpython -m pip install -r requirements.txt
How to perform regular and floor division
17 / 317 // 3
Swap two variables (one liner)
a, b = 0, 1 a, b = b, a
Ternary operator example
"yay!" if 0 > 1 else "nay!"
How to see if variable is None
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
word = 'Python'
Get last character (n) with slicing
word[-1]
word = 'Python'
Get first two characters (Py) with slicing
word[:2]word[0:2]
Reverse a string with slicing
word[::-1]
How to create raw string (i.e. special chars are not parsed in it)
r"C:\some\name"
Concatenate strings
“Hello “ + “world!” # => “Hello world!”
“Hello “ “world!” # => “Hello world!” (implicit concatenation)
Will this work?word[0] = 'J'
TypeError: strings are immutable
How to use format strings?
f"{name} is {len(name)} characters long."
How to convert something string? Two methods, what is the difference between them.
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
If statement
if elif else
Case statement
match status:
case 400:
return "Bad request"
case 401 | 403 | 404:
return "Other error"
case _:
return "Something's wrong with the internet"While loop(s)
while a < 10: pass
For loop
for i in range(5): print(i)
Use range to generate iterables:
- [5, 6, 7, 8, 9]
- [0, 3, 6, 9]
range(5, 10)range(0, 10, 3)