# Отчет по теме 2 Баранов Эмиль, А-03-23 # Тема 2 Базовые типы объектов ## 2 Изучаем простые объекты. Рассматриваем операции присваивания значения объектам-переменным ```py f1=16; f2=3 f1,f2 (16, 3) f1;f2 16 3 dir() ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'f1', 'f2'] dir(f1) ['__abs__', '__add__', '__and__', '__bool__', '__ceil__', '__class__', '__delattr__', '__dir__', '__divmod__', '__doc__', '__eq__', '__float__', '__floor__', '__floordiv__', '__format__', '__ge__', '__getattribute__', '__getnewargs__', '__getstate__', '__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__', 'as_integer_ratio', 'bit_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes'] type(f2) del f1,f2 dir() ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__'] ``` ## 3 Изучаем правила именования объектов в Python.n ```py gg1=1.6 #значение в виде вещественного числа hh1='Строка' #значение в виде символьной строки 73sr=3 #неправильное имя – начинается с цифры - будет диагностика! SyntaxError: invalid decimal literal and=7 #недопустимое имя – совпадает с ключевым словом - будет диагностика! SyntaxError: invalid syntax ``` ![](Skr1.png) ## 4 Выводим список ключевых слов с помощью инструкции ```py import keyword ``` ## 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'] ``` - Изучаем назначение функций: abs, len, max, min, pow, round, sorted, sum, zip ```py def show_help(): functions = [abs, len, max, min, pow, round, sorted, sum, zip] names = ['abs', 'len', 'max', 'min', 'pow', 'round', 'sorted', 'sum', 'zip'] for i, func in enumerate(functions): print(f"\n{'='*30}") print(f"HELP ПО {names[i].upper()}()") print('='*30) help(func) show_help() ============================== HELP ПО ABS() ============================== Help on built-in function abs in module builtins: abs(x, /) Return the absolute value of the argument. ============================== HELP ПО LEN() ============================== Help on built-in function len in module builtins: len(obj, /) Return the number of items in a container. ============================== HELP ПО MAX() ============================== Help on built-in function max in module builtins: max(...) max(iterable, *[, default=obj, key=func]) -> value max(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its biggest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the largest argument. ============================== HELP ПО MIN() ============================== Help on built-in function min in module builtins: min(...) min(iterable, *[, default=obj, key=func]) -> value min(arg1, arg2, *args, *[, key=func]) -> value With a single iterable argument, return its smallest item. The default keyword-only argument specifies an object to return if the provided iterable is empty. With two or more arguments, return the smallest argument. ============================== HELP ПО POW() ============================== Help on built-in function pow in module builtins: pow(base, exp, mod=None) Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments Some types, such as ints, are able to use a more efficient algorithm when invoked using the three argument form. ============================== HELP ПО ROUND() ============================== Help on built-in function round in module builtins: round(number, ndigits=None) Round a number to a given precision in decimal digits. The return value is an integer if ndigits is omitted or None. Otherwise the return value has the same type as the number. ndigits may be negative. ============================== HELP ПО SORTED() ============================== Help on built-in function sorted in module builtins: sorted(iterable, /, *, key=None, reverse=False) Return a new list containing all items from the iterable in ascending order. A custom key function can be supplied to customize the sort order, and the reverse flag can be set to request the result in descending order. ============================== HELP ПО SUM() ============================== Help on built-in function sum in module builtins: sum(iterable, /, start=0) Return the sum of a 'start' value (default: 0) plus an iterable of numbers When the iterable is empty, return the start value. This function is intended specifically for use with numeric values and may reject non-numeric types. ============================== HELP ПО ZIP() ============================== Help on class zip in module builtins: class zip(object) | zip(*iterables, strict=False) --> Yield tuples until an input is exhausted. | | >>> list(zip('abcdefg', range(3), range(4))) | [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)] | | The zip object yields n-length tuples, where n is the number of iterables | passed as positional arguments to zip(). The i-th element in every tuple | comes from the i-th iterable argument to zip(). This continues until the | shortest argument is exhausted. | | If strict is true and one of the arguments is exhausted before the others, | raise a ValueError. | | Methods defined here: | | __getattribute__(self, name, /) | Return getattr(self, name). | | __iter__(self, /) | Implement iter(self). | | __next__(self, /) | Implement next(self). | | __reduce__(...) | Return state information for pickling. | | __setstate__(...) | Set state information for unpickling. | | ---------------------------------------------------------------------- | Static methods defined here: | | __new__(*args, **kwargs) from builtins.type | Create and return a new object. See help(type) for accurate signature. ``` ## 6 Убедился, что малые и большие буквы в именах объектов различаются ```py Ggl=45 Ggl 45 ggl Traceback (most recent call last): File "", line 1, in ggl NameError: name 'ggl' is not defined. Did you mean: 'Ggl'? ``` ## 7 Изучаем простые базовые типы объектов ### 7.1 Логический тип. ```py bb1=True; bb2=False bb1;bb2 True False type(bb1) #функция, показывающая тип (класс) объекта ``` ### 7.2 Другие простые типы ```py ii1=-1234567890 ff1=-8.9876e-12 #экспоненциальная форма записи вещественного числа dv1=0b1101010 #Это – двоичное число. В объекте какого класса оно сохранено? vsm1=0o52765 #Это – восьмеричное число shest1=0x7109af6 #Это – шестнадцатеричное число cc1=2-3j a=3.67; b=-0.45 cc2=complex(a,b) #Создается комплексное число ``` ### 7.3 Строка символов ```py ss1='Это - строка символов' ss1="Это - строка символов" ss1a="Это - \" строка символов \", \n \t выводимая на двух строках" print(ss1a) Это - " строка символов ", выводимая на двух строках sslb= 'Меня зовут: \n <БарановЭ.К.>' mnogo="""Нетрудно заметить , что в результате операции над числами разных типов получается число, имеющее более сложный тип из тех, которые участвуют в операции.""" print(mnogo) Нетрудно заметить , что в результате операции над числами разных типов получается число, имеющее более сложный тип из тех, которые участвуют в операции. print(sslb) Меня зовут: <БарановЭ.К.> s1='Это - строка символов' ss1[0] 'Э' ss1[8] 'р' ss1[-2] 'о' ss1[6:9] 'стр' ss1[13:] 'символов' ss1[:13] 'Это - строка ' ss1[5:-8] ' строка ' ss1[3:17:2] ' тоасм' ss1[17:3:-2] 'омсаот ' ss1=ss1[:4]+'='+ss1[5:] ``` ## 8 Изучаем более сложные типы объектов ### 8.1 ```py spis1=[111,'Spisok',5-9j] print(spis1) [111, 'Spisok', (5-9j)] stup=[0,0,1,1,1,1,1,1,1] print(stup) [0, 0, 1, 1, 1, 1, 1, 1, 1] spis=[1,2,3,4, 5,6,7, 8,9,10] print(spis) [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] spis1[-1] (5-9j) stup[-8::2] [0, 1, 1, 1] spis1[1]='Список' print(spis1) [111, 'Список', (5-9j)] len(spis1) 3 ``` С помощью '.append' можно добавить какой-либо элемент в список, а '.pop' - удалить. ```py spis1.append('New Item') spis1 [111, 'Список', (5-9j), 'New Item'] spis1.append(ss1b) spis1 [111, 'Spisok', (5-9j), 'New Item', 'Меня зовут: \n БарановЭ.К'] spis1.pop(1) 'Spisok' spis1 [111, (5-9j), 'New Item', 'Меня зовут: \n БарановЭ.К'] ``` ```py spis1.insert(1, 'TITAN') вставит второй аргумент под номер индекса элемента. spis1 [111, 'TITAN', (5-9j), 'New Item', 'Меня зовут: \n БарановЭ.К.'] spis1.remove('TITAN') - удалит тот элемент, который полностью соответствует указанному в команде аргументу. spis1 [111, (5-9j), 'New Item', 'Меня зовут: \n БарановЭ.К'] spis1.clear() - удаляет все элементы из списка. spis1 [] spis1 [5, 3, 2, 1, 7, 6, 9] spis1.sort() - сортировка списка как и по числам* spis1 [1, 2, 3, 5, 6, 7, 9] spisbukva = ['b', 'a', 'c', 'g', 't'] spisbukva.sort() - *так и по алфавиту spisbukva ['a', 'b', 'c', 'g', 't'] spisbukva.reverse() - перемешивает элементы в обратном порядке spisbukva ['t', 'g', 'c', 'b', 'a'] spis1 [1, 2, 3, 5, 6, 7, 9] spis111 = spis1.copy() - копирует список. spis111 [1, 2, 3, 5, 6, 7, 9] spis1 [1, 2, 3, 5, 6, 7, 9] spis1.count(5) - считает то, сколько раз элемент из аргумента появляется в списке. 1 spis1.index(9) - возвращает индекс элемента, совпадающего по значению с аргументом. 6 ``` ```py spis2=[spis1, [4,5,6,7]] - элементы переменной - два списка spis2 [[1, 2, 3, 5, 6, 7, 9], [4, 5, 6, 7]] spis2[0][1] - обращение ко второму элементу первого списка 2 spis2[0][1]=78 - замена значения того же элемента на другое spis2 [[1, 78, 3, 5, 6, 7, 9], [4, 5, 6, 7]] spis1 [1, 78, 3, 5, 6, 7, 9] spis2 содержит не копию списка spis1, а ссылку на тот же самый объект в памяти. В памяти создается объект-список, и spis1 указывает на него. spis2[0] - это не копия spis1, а та же самая ссылка на тот же объект в памяти. ``` Был придуман список, содержащий в себе 4 элемента разных типов: число, строка, логическое значение и список. ```py list = ['glad', 18, True, ['a','b','c','d']] list ['glad', 18, True, ['a', 'b', 'c', 'd']] type(list) ``` ### 8.2 Кортежи Похож на список, но изменить его нельзя ```py kort1=(222,'Kortezh',77+8j) type(kort1) kort1[2] = 90 Traceback (most recent call last): File "", line 1, in kort1[2] = 90 TypeError: 'tuple' object does not support item assignment ``` Однако можно переопределить (добавить или удалить определенные элементы). ```py kort1= kort1+(1,2) - добавление kort1 (222, 'Kortezh', (77+8j), 1, 2) kort2=kort1[:2]+kort1[3:] - удаление kort2 (222, 'Kortezh', 1, 2) ``` Определение индекса и подсчёт заданного элемента: ```py kort1.index(2) 4 kort1 (222, 'Kortezh', (77+8j), 1, 2) kort1.count(222) 1 my_tuple = ( 42, # целое число "Привет", # строка [1, 2, 3], # список (4, 5, 6) #кортеж ) ``` ### 8.3 Словарь Является совокупностью пар типа 'key:value' ```py dic1={'Saratov':145, 'Orel':56, 'Vologda':45} dic1['Saratov'] 145 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] dic1 {'Saratov': 145, 'Orel': 56, 'Vologda': 45, 'Pskov': 78} ``` ```py dic2={1:'mean',2:'standart deviation',3:'correlation'} dic3={'statistics':dic2,'POAS':['base','elementary','programming']} - элементом словаря может являться сам словарь dic3 {'statistics': {1: 'mean', 2: 'standart deviation', 3: 'correlation'}, 'POAS': ['base', 'elementary', 'programming']} dic3['statistics'][2] 'standart deviation' ``` ```py dic4=dict([(1,['A','B','C']),(2,[4,5]),('Q','Prim'),('Stroka',ss1b)]) dic4 {1: ['A', 'B', 'C'], 2: [4, 5], 'Q': 'Prim', 'Stroka': 'Меня зовут: Анисенков П.Д.'} dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b])) dic5 {'A': 16, 'B': -3, 'C': 9, 'Stroka': 'Меня зовут: Анисенков П.Д.'} ``` ```py tupl3 = ('A', 'B', 'C', 'D', 'E', 'F','G') l1st = ['1', '2', '3', '4', '5'] dict227 = dict(zip(tupl3,l1st)) dict227 {'A': '1', 'B': '2', 'C': '3', 'D': '4', 'E': '5'} len(dict227) 5 - элеменов получится пять, ведь команда zip работала столько раз, сколько элементов в наиболее маленьком объекте ``` ```py AVTI={'Курс I':[22,23,17,24,30,29,28,25,23,0,4,31,30,33,18,12,27],'Курс II':[18,16,12,15,29,18,21,23,13,0,4,20,31,26,16,], 'Курс III':[17,12,0,6,17,15,19,19,0,0,5,17,22,18,12], 'Курс IV':[27,16,0,13,17,15,19,20,0,0,2,15,18,16,17]} AVTI['Курс III'][5] 15 ``` ### 8.4 Множество ипы разные или одинаковые, но только неизменяемые и неповторяющиеся. ```py mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'} print(mnoz1) {'двигатель', 'датчик', 'микропроцессор', 'линия связи'} len(mnoz1) 4 ``` операции во множестве: ```py 'датчик' in mnoz1 True mnoz1.add('реле') print(mnoz1) {'двигатель', 'датчик', 'линия связи', 'микропроцессор', 'реле'} mnoz1.remove('линия связи') print(mnoz1) {'двигатель', 'датчик', 'микропроцессор', 'реле'} ``` Было создано множество: ```py mnoz1 = {'лев', '1', True, ('тигр', 1, 3)} mnoz1 {'1', True, 'лев', ('тигр', 1, 3)} mnoz1.remove(True) mnoz1 {'1', 'лев', ('тигр', 1, 3)} mnoz1.add('черный') mnoz1 {('тигр', 1, 3), 'лев', '1', 'черный'} ``` ## Контрольное задание familia = 'Baranov' bukva = familia[0] import keyword sp_kw = keyword.kwlist sp_kw.remove('nonlocal') print(sp_kw) ['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', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'] print(sp_kw.count('nonlocal')) 0 kort_nam = ('Emil', 'Shma', 'Egor', 'Butka') print(type(kort_nam)) kort_nam = kort_nam + ('Denis', 'Alena') print(kort_nam.count('Dima')) 0 key = ['str', 'list', 'tuple'] value = [familia, sp_kw, kort_nam] dict_bas = dict(zip(key, value)) print(dict_bas) {'str': 'Баранов', 'list': ['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'], 'tuple': ('Emil', 'Shma', 'Egor', 'Butka')}