Fundamentals Flashcards
(150 cards)
Run a string as Python
exec ‘print(“Hello”)’
Delete from Dictionary
del X[Y]
Create anonymous function
s = lambda y: y ** y
print(s(4))
Make a List
j = [1, ‘two’, 3.0]
thislist = list((“apple”, “banana”, “cherry”))
Dictionary
d = {‘x’: 1, ‘y’: ‘two’}
thisdict = dict(name = “John”, age = 36, country = “Norway”)
Tuple
mytuple = (“apple”, “banana”, “cherry”)
thistuple = tuple((“apple”, “banana”, “cherry”))
Set
myset = {“apple”, “banana”, “cherry”}
thisset = set((“apple”, “banana”, “cherry”))
Floor division //
9 // 4 = 2
Modulus %
9 % 4 = 1
How methods work under the hood? mystuff.append(‘hello’)
append(mystuff, ‘hello’)
How to pass agruments into a script?
from sys import argv
script, first_arg = argv
print(“The script is called:”, script, “first variable is:”, first_arg)
»>python ex13.py my_first_arg
2 tips for reading code
Read code backwards from bottom to the top.
Comment every line
What 6 tools from ModernPyProjects I’m going to use?
- VS Code
- Pyenv (change Py versions)
- pipx (install global packages)
- Default venv
- Cookie-cutter (create project from template)
- pip-tools (pin dependencies)
Removes all the elements from the dictionary
dictionary.clear()
Returns a copy of the dictionary
dictionary.copy()
x = car.copy()
Returns a dictionary with the specified keys and value
dict.fromkeys(keys, value)
x = (‘key1’, ‘key2’, ‘key3’)
y = 0
thisdict = dict.fromkeys(x, y)
print(thisdict)
Returns the value of the specified key
dictionary.get(keyname, value)
x = car.get(“model”)
print(x)
Returns a list containing a tuple for each key value pair
dictionary.items()
x = car.items()
print(x)
Returns a list containing the dictionary’s keys
dictionary.keys()
x = car.keys()
print(x)
»>dict_keys([‘brand’, ‘model’, ‘year’])
Removes the element with the specified key
dictionary.pop(keyname, defaultvalue)
car.pop(“model”)
print(car)
Removes the last inserted key-value pair
dictionary.popitem()
car = {
“brand”: “Ford”,
“model”: “Mustang”,
“year”: 1964
}
car.popitem()
print(car)
»>{‘brand’: ‘Ford’, ‘model’: ‘Mustang’}
Returns the value of the specified key. If the key does not exist: insert the key, with the specified value
dictionary.setdefault(keyname, value)
x = car.setdefault(“model”, “Bronco”)
Updates the dictionary with the specified key-value pairs
dictionary.update(iterable)
car.update({“color”: “White”})
Returns a list of all the values in the dictionary
values()
x = car.values()
print(x)
»>dict_values([‘Ford’, ‘Mustang’, 1964])