Fundamentals Flashcards
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])
Разделить строки можно с помощью …
;
print(‘Mother of Dragons.’); print(‘Drakarys!’)
Что такое Оператор?
Знак операции, такой как +, называют оператором
Что такое Операнд?
Операторы выполняют операции над определенными значениями, которые называются операндами
print(8 + 2)
В этом примере + — это оператор, а числа 8 и 2 — это операнды.
Бинарный операнд
Когда мы складываем, у нас есть два операнда: один слева, другой справа от знака +. Операции, которые требуют наличия двух операндов, называются бинарными
Унарные операции
Операция с одним операндом
Тернарные операции
Операция с тремя операндами
Коммутативный закон
«От перемены мест слагаемых сумма не меняется» — это один из базовых законов арифметики, который также называется коммутативным законом
Коммутативные операции
Сложение — это коммутативная операция: 3 + 2 = 2 + 3
Не коммутативные операции
Вычитание — это не коммутативная операция: 2 - 3 ≠ 3 - 2
Деление: 4 / 2 ≠ 2 / 4
Приоритет операций
Умножение и деление имеют больший приоритет, чем сложение и вычитание, а приоритет возведения в степень выше всех остальных арифметических операций
Какой из операторов может быть и унарным, и бинарным?
Унарный: - 3
Бинарный: 5 - 2
Adds an element at the end of the list
fruits = [‘apple’, ‘banana’, ‘cherry’]
fruits.append(“orange”)
Remove all elements from the list
fruits = [‘apple’, ‘banana’, ‘cherry’, ‘orange’]
fruits.clear()
The method returns a copy of the specified list.
fruits = [‘apple’, ‘banana’, ‘cherry’, ‘orange’]
x = fruits.copy()
The method returns the number of elements with the specified value.
fruits = [‘apple’, ‘banana’, ‘cherry’]
x = fruits.count(“cherry”)
The method adds the specified list elements (or any iterable) to the end of the current list.
fruits = [‘apple’, ‘banana’, ‘cherry’]
cars = [‘Ford’, ‘BMW’, ‘Volvo’]
fruits.extend(cars)
The method returns the position at the first occurrence of the specified value.
fruits = [‘apple’, ‘banana’, ‘cherry’]
x = fruits.index(“cherry”)
The method inserts the specified value at the specified position.
fruits = [‘apple’, ‘banana’, ‘cherry’]
fruits.insert(1, “orange”)
The method removes the element at the specified position.
fruits = [‘apple’, ‘banana’, ‘cherry’]
fruits.pop(1)
The method removes the first occurrence of the element with the specified value.
fruits = [‘apple’, ‘banana’, ‘cherry’]
fruits.remove(“banana”)
The method reverses the sorting order of the elements in a list.
fruits = [‘apple’, ‘banana’, ‘cherry’]
fruits.reverse()
The method sorts the list ascending by default.
list.sort(reverse=True|False, key=myFunc)
~~~
cars = [‘Ford’, ‘BMW’, ‘Volvo’]
cars.sort(reverse=True)
print(cars)
> > > [‘‘Volvo’’, ‘‘BMW’’, ‘“Ford”’]
~~~
Символ экранирования
\ — обратный слэш
Экранированные последовательности
\n — это пример экранированной последовательности (escape sequence)
Табуляция \t — разрыв, который получается при нажатии на кнопку Tab
Возврат каретки \r — работает только в Windows
Имена переменных регистрозависимы?
Имена переменных регистрозависимы, то есть имя hello и имя HELLO — это два разных имени для двух разных переменных
Соглашение об именовании констант
Константы принято именовать заглавными буквами и с _ в качестве разделителя между словами
Выражения (expressions)
Выражение — это любой корректный блок кода, который возвращает значение.
Когда интерпретатор видит выражение, он обрабатывает его и генерирует результат — значение выражения.
Инструкции (statements)
Инструкция — это команда, действие.
if, while, for — примеры инструкций. Они производят или контролируют действия, но не превращаются в значения.
Конкатенация
what = “Kings” + “road” # строки
first = “Kings”
what = first + “road” # строка и переменная
what = first + last # две переменные
Именование переменных: Магические числа
Проблема кроется в «магических числах» — magic numbers. Это числа, происхождение которых невозможно понять с первого взгляда — приходится глубоко вникать в то, что происходит в коде.
dollars_count = euros_count * 1.25
rubles_count = dollars_count * 60
В этом примере сложно понять, что значат числа 60 и 1.25
Альтернатива конкатенации строк
Интерполяция.
print(f’{greeting}, {first_name}!’)
# => Hello, Joffrey!
Буква f указывает на то, что мы создаем f-строку — шаблон, в который с помощью фигурных скобок подставляются значения переменных
Альтернатива \n
Multi-line строки
text = ‘'’Пример текста,
состоящего из
нескольких строк
‘’’ # создаст новую строку после текста
В конце текста есть пустая строка. Она появилась в тексте потому, что мы поставили закрывающие кавычки ‘’’ на новой строке. Если не переносить закрывающие кавычки на новую строку, то пустая строка в тексте не появится
Мульти-строчные строки и экранирование кавычек
Благодаря тройным кавычкам multi-line строки позволяют не экранировать кавычки внутри строки
Здесь не нужно экранировать ‘одинарные’ и “двойные” кавычки
Мульти-строчные строки f-строки
a = ‘A’
b = ‘B’
Слева добавился f
text = f’’‘{a} и {b}
сидели на трубе
‘’’
# А и B
# сидели на трубе
Извлечение элемента списка по индексу
first_name = ‘Alexander’
print(first_name[0]) # => A
Операция с квадратными скобками с цифрой извлекает элемент по индексу — позиции символа внутри строки.
Индексы начинаются с 0 почти во всех языках программирования.
Индекс последнего элемента равен длине строки минус единица.
Обращение к индексу за пределами строки приведет к ошибке
Подстрока
Подстрока — это некоторая часть строки, которую нужно найти и извлечь.