форкнуто от main/python-labs
Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
604 строки
22 KiB
Markdown
604 строки
22 KiB
Markdown
# Протокол по Теме 2 <ЦветковаТА>»
|
|
## пункт2:
|
|
изучили простые объекты и присваивание
|
|
```py
|
|
>>>f1=16; f2=3
|
|
>>>f1,f2
|
|
(16, 3)
|
|
```
|
|
Или через точку с запятой. тогда друг за другом:
|
|
```py
|
|
>>> f1; f2
|
|
16
|
|
3
|
|
```
|
|
Узнаем какие объекты уже существуют в среде
|
|
```py
|
|
>>>dir()
|
|
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'f1', 'f2']
|
|
```
|
|
|
|
Еще эта функция может показать атрибуты объекта:
|
|
```py
|
|
|
|
>>> dir (f1)
|
|
['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__',
|
|
'__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__gt__',
|
|
'__hash__', '__index__', '__init__', '__init_subclass__', '__int__', '__invert__', '__le__', '__lshift__', '__lt__', '__mod__',
|
|
'__mul__', '__ne__', '__neg__', '__new__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdivmod__',
|
|
'__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__round__',
|
|
'__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__sizeof__', '__str__', '__sub__',
|
|
'__subclasshook__', '__truediv__', '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag',
|
|
'numerator', 'real', 'to_bytes']
|
|
```
|
|
Функция del необходима для удаления объекта
|
|
```py
|
|
>>> del f1,f2
|
|
>>>dir()
|
|
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
|
|
```
|
|
## Пункт3:
|
|
```py
|
|
>>>gg1=1.6 #значение в виде вещественного числа
|
|
>>>hh1='Строка' #значение в виде символьной строки
|
|
>>>73sr=3 #неправильное имя – начинается с цифры - будет диагностика!
|
|
SyntaxError: invalid decimal literal
|
|
>>>and=7 #недопустимое имя – совпадает с ключевым словом - будет диагностика!
|
|
SyntaxError: invalid syntax
|
|
```
|
|
## Пункт4:
|
|
Вывели список ключевых слов и присвоили команду к переменной
|
|
```py
|
|
>>>import keyword
|
|
>>>keyword.kwlist
|
|
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
|
|
>>>k=keyword.kwlist
|
|
k
|
|
['False', 'None', 'True', 'and', 'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
|
|
```
|
|
## Пункт5:
|
|
Выведем список встроенных идеентификаторов
|
|
```py
|
|
>>>import builtins
|
|
>>>dir(builtins)
|
|
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BaseExceptionGroup', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', 'EnvironmentError', 'Exception', 'ExceptionGroup', 'False', 'FileExistsError', 'FileNotFoundError', 'FloatingPointError', 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError', 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError', 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'ModuleNotFoundError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError', 'RecursionError', 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning', 'StopAsyncIteration', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'aiter', 'all', 'anext', 'any', 'ascii', 'bin', 'bool', 'breakpoint', 'bytearray', 'bytes', 'callable', 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit', 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview', 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property', 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars', 'zip']
|
|
```
|
|
модуль
|
|
```py
|
|
>>>abs(-7)
|
|
7
|
|
```
|
|
длинна
|
|
```py
|
|
>>>len([1,2])
|
|
2
|
|
```
|
|
максимум и минимум
|
|
```py
|
|
>>>max(20,5)
|
|
20
|
|
>>>min(20,5)
|
|
5
|
|
```
|
|
|
|
возведение в степень
|
|
```py
|
|
>>>pow(4,2)
|
|
16
|
|
```
|
|
возведение в степень по модулю
|
|
```py
|
|
>>>pow (5, 2, 2)
|
|
1
|
|
```
|
|
округление
|
|
```py
|
|
>>>round (33.2)
|
|
33
|
|
```
|
|
округление с определенной точностью
|
|
```py
|
|
>>>round (33.45826, 3)
|
|
33.458
|
|
```
|
|
сумма
|
|
```py
|
|
>>>sum ([2, 5])
|
|
7
|
|
```
|
|
сортировка и иобратная сортировка
|
|
```py
|
|
>>>sorted ([5, 4, 18, 40, -6, 0])
|
|
[-6, 0, 4, 5, 18, 40]
|
|
>>>sorted ([5, 4, 18, 40, -6, 0], reverse = True)
|
|
[40, 18, 5, 4, 0, -6]
|
|
```
|
|
Объединение объектов в кортеж (возвращается указатель на участок памяти)
|
|
```py
|
|
>>> list1 = [1, 2, 3]
|
|
>>> list2 = [4, 5, 6]
|
|
>>> zip (list1, list2)
|
|
<zip object at 0x0000000002C42E88>
|
|
Это итератор - указатель на объект памяти. Чтобы увидеть сам кортеж, итератор надо
|
|
преобразовать в другой объект
|
|
>>> list(zipped)
|
|
[(1, 4), (2, 5), (3, 6)]
|
|
```
|
|
## Пункт6:
|
|
Регестрочувствительность
|
|
```py
|
|
>>>Gg=45
|
|
>>>Gg
|
|
45
|
|
>>>gg
|
|
Traceback (most recent call last):
|
|
File "<pyshell#39>", line 1, in <module>
|
|
gg
|
|
NameError: name 'gg' is not defined. Did you mean: 'Gg'?
|
|
```
|
|
## Пункт7:
|
|
Типы объектов
|
|
```py
|
|
>>>bb1=True; bb2=False
|
|
>>>bb1;bb2
|
|
True
|
|
False
|
|
>>>type(bb1)
|
|
<class 'bool'>
|
|
тип (класс) объекта
|
|
```
|
|
Целое число (десятичное)
|
|
```py
|
|
>>> ii1 = 1234567890
|
|
>>> type(ii1)
|
|
<class 'int'>
|
|
```
|
|
|
|
Экспоненциальная форма записи числа
|
|
```py
|
|
>>> ff1 = 8.987e-12
|
|
>>> type(ff1)
|
|
<class 'float'>
|
|
```
|
|
Двоичное число (префикс 0b - binary)
|
|
```py
|
|
>>> dv1 = 0b1100101
|
|
>>> type(bb1)
|
|
<class 'bool'>
|
|
```
|
|
Восьмеричное число (0о - octal)
|
|
```py
|
|
>>> vsm1 = 0o52765
|
|
>>> type(vsm1)
|
|
<class 'int'>
|
|
```
|
|
Шестнадцатеричное число (0х - hexadecimal)
|
|
```py
|
|
>>> shest1 = 0x7109af6
|
|
>>> type(shest1)
|
|
<class 'int'>
|
|
```
|
|
Комплексное число
|
|
```py
|
|
>>> cc1 = 2 - 3j
|
|
>>> type(cc1)
|
|
<class 'complex'>
|
|
```
|
|
```py
|
|
>>> a = 3.67
|
|
>>> b = 0.45
|
|
>>> cc2 = complex (a, b)
|
|
>>> cc2
|
|
(3.67+0.45j)
|
|
>>> type (cc2)
|
|
<class 'complex'>
|
|
```
|
|
Строка символов
|
|
```py
|
|
>>> ss1='Это - строка символов'
|
|
>>> ss1="Это - строка символов"
|
|
>>> ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"
|
|
>>> print(ss1a)
|
|
Это - " строка символов ",
|
|
выводимая на двух строках
|
|
>>> ss1b= 'Меня зовут: \n <Цветкова ТА>'
|
|
>>> print(ss1b)
|
|
Меня зовут:
|
|
<Цветкова ТА>
|
|
```
|
|
```py
|
|
>>> mnogo="""Нетрудно заметить , что в результате операции
|
|
... над числами разных типов получается число,
|
|
... имеющее более сложный тип из тех, которые участвуют в операции."""
|
|
>>> print(mnogo)
|
|
Нетрудно заметить , что в результате операции
|
|
над числами разных типов получается число,
|
|
имеющее более сложный тип из тех, которые участвуют в операции.
|
|
```
|
|
При вводе такой строки символ приглашения в начале строки не появится, пока не будет вновь введены тройные кавычки.
|
|
|
|
|
|
Обратимся к отдельным элементам с помощью квадратных кавычек
|
|
(нумерация с нуля):
|
|
```py
|
|
>>> mnogo[5]
|
|
'д'
|
|
```
|
|
Обращение начиная с последнего элемента:
|
|
```py
|
|
>>> ss1b[-1]
|
|
'>'
|
|
```
|
|
Срезы:
|
|
```py
|
|
>>> ss1[7:10]
|
|
'тро'
|
|
```
|
|
Срез с шагом в 2:
|
|
```py
|
|
>>> ss1[7:14:2]
|
|
'тоас'
|
|
```
|
|
```py
|
|
>>> ss1[5:-8]
|
|
' строка '
|
|
```
|
|
|
|
Задав шаг -1, можно вывести строку в обратном порядке:
|
|
```py
|
|
>>> ss1[::-1]
|
|
'воловмис акортс - отЭ'
|
|
```
|
|
К элементу можно обратиться как по нумерации с начала, так и с конца:
|
|
```py
|
|
>>> ss1[17:3:-2]
|
|
'омсаот '
|
|
>>> ss1[-4:3:-2]
|
|
'омсаот '
|
|
```
|
|
|
|
Строка является неизменяемым объектом
|
|
```py
|
|
>>> ss1[4]='=' # Будет диагностика!
|
|
Traceback (most recent call last):
|
|
File "<stdin>", line 1, in <module>
|
|
TypeError: 'str' object does not support item assignment
|
|
>>> ss1=ss1[:4]+'='+ss1[5:]
|
|
>>> print(ss1)
|
|
Это = строка символов
|
|
```
|
|
Новый объект на основе среза из старого:
|
|
```py
|
|
>>> ss1b_cut = ss1b [::-1]
|
|
>>> ss1b_cut
|
|
'>АТ авоктевЦ< \n :тувоз янеМ'
|
|
```
|
|
## Пункт8:
|
|
Список
|
|
```py
|
|
>>> spis1 = ["111", 'spisok', 5 - 9j]
|
|
>>> stup=[0,0,1,1,1,1,1,1,1]
|
|
>>> stup
|
|
[0, 0, 1, 1, 1, 1, 1, 1, 1]
|
|
>>> pis=[1,2,3,4,
|
|
... 5,6,7,
|
|
... 8,9,10]
|
|
>>> pis
|
|
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
|
|
>>> spis1 [-1]
|
|
(5-9j)
|
|
>>> stup [-8 :: 2]
|
|
[0, 1, 1, 1]
|
|
>>> spis1[1]='Список'
|
|
>>> spis1
|
|
['111', 'Список', (5-9j)]
|
|
>>> len(spis1)
|
|
3
|
|
```
|
|
Методы списка
|
|
Добавление в конец (append)
|
|
```py
|
|
>>> help(spis1.append)
|
|
Help on built-in function append:
|
|
|
|
append(object, /) method of builtins.list instance
|
|
Append object to the end of the list.
|
|
|
|
>>> spis1.append('New item') # В конец списка добавлен элемент «New item»
|
|
>>> spis1
|
|
['111', 'Список', (5-9j), 'New item']
|
|
>>> spis1+['New item']
|
|
Только возвращает результат, но не фиксирует такое значение!
|
|
['111', 'Список', (5-9j), 'New item', 'New item']
|
|
```
|
|
Удаление элемента по индексу
|
|
```py
|
|
>>> spis1.pop(1)
|
|
'Список'
|
|
>>> spis1
|
|
['111', (5-9j), 'New item', 'Меня зовут: \n <Цветкова ТА>']
|
|
```
|
|
Вставка элемента в определенное место по индексу (insert)
|
|
```py
|
|
>>> spis1.insert(2, "hello")
|
|
>>> spis1
|
|
['111', (5-9j), 'hello', 'New item', 'Меня зовут: \n <Цветкова ТА>']
|
|
```
|
|
Удаление элемента по значению (remove)
|
|
```py
|
|
>>> help(spis1.remove)
|
|
Help on built-in function remove:
|
|
|
|
remove(value, /) method of builtins.list instance
|
|
Remove first occurrence of value.
|
|
|
|
Raises ValueError if the value is not present.
|
|
|
|
>>> spis1.remove(111)
|
|
>>> spis1
|
|
[(5-9j), 'hello', 'New item', 'Меня зовут: \n <Цветкова ТА>']
|
|
```
|
|
```py
|
|
>>> spis1.remove('222')
|
|
Traceback (most recent call last):
|
|
File "<pyshell#39>", line 1, in <module>
|
|
spis1.remove('222')
|
|
```
|
|
Добавление элементов объекта в конец другого объекта (extend)
|
|
```py
|
|
>>> help(spis1.extend)
|
|
Help on built-in function extend:
|
|
|
|
extend(iterable, /) method of builtins.list instance
|
|
Extend list by appending elements from the iterable.
|
|
>>> end1 = [77, "lab"]
|
|
>>> spis1.extend(end1)
|
|
>>> spis1
|
|
[(5-9j), 'hello', 'New item', 'Меня зовут: \n <Цветкова ТА>', '77', 'lab']
|
|
```
|
|
|
|
6. Полное очищение списка (clear)
|
|
```py
|
|
>>> help(spis1.clear)
|
|
Help on built-in function clear:
|
|
|
|
clear() method of builtins.list instance
|
|
Remove all items from list.
|
|
|
|
>>> end1.clear()
|
|
>>> end1
|
|
[]
|
|
```
|
|
Сортировка списка БЕЗ создания нового объекта (sort)
|
|
```py
|
|
>>> help(spis1.sort)
|
|
Help on built-in function sort:
|
|
|
|
sort(*, key=None, reverse=False) method of builtins.list instance
|
|
Sort the list in ascending order and return None.
|
|
|
|
The sort is in-place (i.e. the list itself is modified) and stable (i.e. the
|
|
order of two equal elements is maintained).
|
|
|
|
If a key function is given, apply it once to each list item and sort them,
|
|
ascending or descending, according to their function values.
|
|
|
|
The reverse flag can be set to sort in descending order.
|
|
>>> abc = [4,7,-3,0]
|
|
>>> abc.sort(key = abs, reverse = True)
|
|
>>> abc
|
|
[7, 4, -3, 0]
|
|
```
|
|
При этом некоторые key's не применимы для некоторых типов (у string нет abs,
|
|
у complex нет длины и т.д.)
|
|
|
|
Создание копии списка (copy)
|
|
```py
|
|
>>> help(abc.copy)
|
|
Help on built-in function copy:
|
|
|
|
copy() method of builtins.list instance
|
|
Return a shallow copy of the list.
|
|
|
|
>>> abccopy=abc.copy()
|
|
>>> abccopy
|
|
[7, 4, -3, 0]
|
|
```
|
|
Поиск индекса по значению (index)
|
|
```py
|
|
>>> help(abccopy.index)
|
|
Help on built-in function index:
|
|
|
|
index(value, start=0, stop=9223372036854775807, /) method of builtins.list instance
|
|
Return first index of value.
|
|
|
|
Raises ValueError if the value is not present.
|
|
|
|
>>> abccopy.index(0)
|
|
3
|
|
```
|
|
Подсчет количества элементов по значению (count)
|
|
```py
|
|
>>> help(abccopy.count)
|
|
Help on built-in function count:
|
|
|
|
count(value, /) method of builtins.list instance
|
|
Return number of occurrences of value.
|
|
|
|
>>> abccopy.count(4)
|
|
1
|
|
```
|
|
Вложенные списки:
|
|
```py
|
|
>>> spis2=[spis1,[4,5,6,7]]
|
|
>>> spis2
|
|
[['111', (5-9j), 'hello', 'New item', 'Меня зовут: \n <Цветкова ТА>', '77', 'lab'], [4, 5, 6, 7]]
|
|
>>> spis2[0][1]
|
|
(5-9j)
|
|
>>> spis2[0][1]=78
|
|
>>> spis2
|
|
[['111', 78, 'hello', 'New item', 'Меня зовут: \n <Цветкова ТА>', '77', 'lab'], [4, 5, 6, 7]]
|
|
>>> spis1
|
|
[['111', 78, 'hello', 'New item', 'Меня зовут: \n <Цветкова ТА>', '>'
|
|
```
|
|
spis1 тоже изменился. Это происходит потому, что python работает не просто с
|
|
объектами, а с ссылками на участки памяти. То есть, в Python списки передаются по ссылке,
|
|
а не по значению.
|
|
|
|
Кортеж: последовательность как список, но неизменяемая как строка.
|
|
```py
|
|
>>> kort1=(222,'Kortezh',77+8j)
|
|
>>> kort1= kort1+(1,2)
|
|
>>> kort1= kort1+(ss1b,)
|
|
>>> kort1
|
|
(222, 'Kortezh', (77+8j), 1, 2, 'Меня зовут: \n <Цветкова ТА>')
|
|
>>> kort2=kort1[:2]+kort1[3:]
|
|
>>> kort2
|
|
(222, 'Kortezh', 1, 2, 'Меня зовут: \n <Цветкова ТА>')
|
|
>>> kort1.index(2)
|
|
4
|
|
>>> kort1.count(222)
|
|
1
|
|
>>> kort1[2]=90
|
|
Traceback (most recent call last):
|
|
File "<stdin>", line 1, in <module>
|
|
TypeError: 'tuple' object does not support item assignment
|
|
>>> kortstr = ("gjgvu", 4, [1,2,3], (1,2))
|
|
>>> kortstr
|
|
('gjgvu', 4, [1, 2, 3], (1, 2))
|
|
>>> type(kortstr[3])
|
|
<class 'tuple'>
|
|
>>> type(kortstr[2])
|
|
<class 'list'>
|
|
```
|
|
|
|
Словарь (dictionary) - содержит в себе совокупность пар
|
|
"ключ (key) (неизменяемый)": "значение (value) (любого типа)"
|
|
```py
|
|
>>> dic1={'Saratov':145, 'Orel':56, 'Vologda':45}
|
|
>>> dic1
|
|
{'Saratov': 145, 'Orel': 56, 'Vologda': 45}
|
|
>>> dic1[1]
|
|
Traceback (most recent call last):
|
|
File "<pyshell#99>", line 1, in <module> #как видно, обратиться по индексу нельзя
|
|
dic1[1]
|
|
KeyError: 1
|
|
>>> dic1['Orel']
|
|
56
|
|
>>> dic1['Pskov']=78
|
|
>>> dic1
|
|
{'Saratov': 145, 'Orel': 56, 'Vologda': 45, 'Pskov': 78}
|
|
>>> sorted(dic1.keys())
|
|
['Orel', 'Pskov', 'Saratov', 'Vologda']
|
|
>>> sorted(dic1.values())
|
|
[45, 56, 78, 145]
|
|
>>> dic2={1:'mean',2:'standart deviation',3:'correlation'}
|
|
>>> dic3={'statistics':dic2,'POAS':['base','elementary','programming']}
|
|
>>> dic3['statistics'][2]
|
|
'standart deviation'
|
|
>>> dic4=dict([(1,['A','B','C']),(2,[4,5]),('Q','Prim'),('Stroka',ss1b)])
|
|
>>> dic4
|
|
{1: ['A', 'B', 'C'], 2: [4, 5], 'Q': 'Prim', 'Stroka': 'Меня зовут: \n <Цветкова ТА>'}
|
|
>>> dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b]))
|
|
>>> dic5
|
|
{'A': 16, 'B': -3, 'C': 9, 'Stroka': 'Меня зовут: \n <Цветкова ТА>'}
|
|
```
|
|
Создание собственного словаря на основе кортежа из семи элементов и списка из пяти:
|
|
```py
|
|
>>> a0223=('спать', 'учиться','работать', 'кмы','барс','лекции','общежитие')
|
|
>>> a0123=['1', '2', '3', '4', '5']
|
|
>>> MPEI=dict(zip(a0123, a0223))
|
|
>>> MPEI
|
|
{'1': 'спать', '2': 'учиться', '3': 'работать', '4': 'кмы', '5': 'барс'}
|
|
```
|
|
В итоговом словаре пять объектов. Это связано с работой функции zip:
|
|
длина итогового объекта = минимальной длине составляющего
|
|
объекта.
|
|
|
|
Словари: состоят из НЕповторяющихся неизменяемых элементов
|
|
```py
|
|
>>> mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}
|
|
>>> mnoz1
|
|
{'двигатель', 'линия связи', 'датчик', 'микропроцессор'}
|
|
>>> len(mnoz1)
|
|
4
|
|
>>> 'датчик' in mnoz1
|
|
True
|
|
>>> mnoz1.add('реле')
|
|
>>> mnoz1.remove('линия связи')
|
|
>>> mnoz1
|
|
{'реле', 'микропроцессор', 'датчик', 'двигатель'}
|
|
```
|
|
|
|
|
|
Общее контрольное задание:
|
|
|
|
1. Создать переменную с именем familia и со значением -
|
|
символьной строкой – своей фамилией в латинской транскрипции.
|
|
```py
|
|
>>> familia = 'Tsvetkova'
|
|
```
|
|
2. Создать переменную со значением, совпадающим с первой
|
|
буквой из familia.
|
|
```py
|
|
>>> fam1 = familia[0]
|
|
>>> fam1
|
|
'T'
|
|
```
|
|
3. Создать переменную с именем sp_kw со значением –
|
|
списком всей ключевых слов языка Python.
|
|
```py
|
|
>>> import keyword
|
|
>>> sp_kw = keyword.kwlist
|
|
>>> sp_kw
|
|
['False', 'None', 'True', '__peg_parser__', 'and',
|
|
'as', 'assert', 'async', 'await', 'break', 'class', 'continue', 'def',
|
|
'del', 'elif', 'else', 'except', 'finally', 'for', 'from', 'global', 'if',
|
|
'import', 'in', 'is', 'lambda', 'nonlocal', 'not', 'or', 'pass', 'raise',
|
|
'return', 'try', 'while', 'with', 'yield']
|
|
```
|
|
4. Удалите из списка sp_kw значение 'nonlocal'. Выводом списка в
|
|
командном окне IDLE убедитесь, что это значение удалено из списка.
|
|
```py
|
|
>>> sp_kw.remove('nonlocal')
|
|
>>> sp_kw
|
|
['False', 'None', 'True', '__peg_parser__', 'and', 'as', 'assert',
|
|
'async', 'await', 'break', 'class', 'continue', 'def', 'del', 'elif',
|
|
'else', 'except', 'finally', 'for', 'from', 'global', 'if', 'import',
|
|
'in', 'is', 'lambda', 'not', 'or', 'pass', 'raise', 'return', 'try',
|
|
'while', 'with', 'yield']
|
|
```
|
|
5. Создайте кортеж kort_nam с именами: вашим и еще 3-х студентов
|
|
из вашей группы. Напишите инструкцию, позволяющую убедиться, что тип
|
|
переменной – это tuple.
|
|
```py
|
|
>>> kort_nam = ('Stas', 'Dana', 'Katya', 'Tanya')
|
|
>>> type(kort_nam)
|
|
<class 'tuple'>
|
|
```
|
|
6. Напишите инструкцию, добавляющую в kort_nam имена
|
|
еще двух студентов.
|
|
```py
|
|
>>> kort_nam += ('Andrey', 'Nastya')
|
|
>>> kort_nam
|
|
('Stas', 'Dana', 'Katya', 'Tanya', 'Andrey', 'Nastya')
|
|
```
|
|
7. Напишите инструкцию, позволяющую определить, сколько раз в
|
|
кортеже присутствуют студенты с именем «Дима».
|
|
```py
|
|
>>> kort_nam.count("Dima")
|
|
0
|
|
```
|
|
8. Создайте словарь dict_bas, в котором ключами являются русские
|
|
названия типов переменных, использованных в предыдущих операторах,
|
|
а значениями – ранее созданные переменные, соответствующие этим типам.
|
|
```py
|
|
>>> dict_bas = {"строка": familia, "символ": fam1, "список": sp_kw,
|
|
"кортеж": kort_nam,}
|
|
>>> dict_bas
|
|
{'строка': 'Ishutina', 'символ': 'I', 'список': ['False', 'None', 'True',
|
|
'__peg_parser__', 'and', 'as', 'assert', 'async', 'await', 'break', 'class',
|
|
'continue', 'def', 'del', 'elif', 'else', 'except', 'finally', 'for', 'from',
|
|
'global', 'if', 'import', 'in', 'is', 'lambda', 'not', 'or', 'pass', 'raise',
|
|
'return', 'try', 'while', 'with', 'yield'], 'кортеж': (''Stas', 'Dana', 'Katya', 'Tanya', 'Andrey', 'Nastya')}
|
|
``` |