# Отчет по Теме 2 Грудинин Егор, А-03-23 ## 1 Изучение простых объектов ```py >>> f1 = 16; f2 = 3 >>> f1,f2 (16, 3) >>> f1;f2 16 3 >>> dir() ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'f1', 'f2', 'os'] >>> 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', 'is_integer', 'numerator', 'real', 'to_bytes'] >>> type(f2) >>> del f1,f2 >>> dir() ['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os'] ``` ## 2 Изучение правил именования объектов ```py >>> gg1 = 1.6 >>> gg1 1.6 >>> hh1 = 'Строка' >>> hh1 'Строка' >>> 73sr=3 SyntaxError: invalid decimal literal >>> and=7 SyntaxError: invalid syntax ``` ## 3 Cписок rлючевых слов ```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'] >>> kwls = keyword.kwlist ls ['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'] ``` ## 4 Встроенные идентификаторы ```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', 'PythonFinalizationError', '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', '_', '_IncompleteInputError', '__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'] ``` ## 5 Изучение назначения функций ```py >>> abs(-1) 1 >>> len(dir(builtins)) 161 >>> max(1,2,3,43,-10,-5) 43 >>> min(-1,-22,-50,12,63,3) -50 >>> pow(2,3) 8 >>> round(3.141592,2) 3.14 >>> sorted([1,5,3,73,61,0,3]) [0, 1, 3, 3, 5, 61, 73] >>> sum([1,2,3,4,5,6,7,8,9]) 45 >>> sum([1,2,3,4,5,6,7,8,9], 10) 55 >>> fn = ['Egor', 'Ivan', 'Lex'] >>> ln = ['Grudinin', 'Ivanov', 'Petrov'] >>> b = [2005, 2004, 1995] >>> data = zip(fn, ln, b) >>> list(data) [('Egor', 'Grudinin', 2005), ('Ivan', 'Ivanov', 2004), ('Lex', 'Petrov', 1995)] ``` ## 6 Важность регистра ```py >>> Gg1=45 >>> gg1; Gg1 1.6 45 ``` ## 7 Базовые типы объектов ```py >>> bb1 = True; bb2 = False >>> bb1; bb2 True False >>> type(bb1) >>> ii1 = -123456789 >>> type(ii1) >>> ff1=-8.9876e-12 >>> type(ff1) >>> dv1=0b1101010 >>> type(dv1) >>> vsm1=0o52765 >>> type(vsm1) >>> shest1=0x7109af6 >>> type(shest1) >>> cc1=2-3j >>> type(cc1) >>> a=3.67; b=-0.45 >>> cc2=complex(a,b) >>> type(cc2) >>> cc2 (3.67-0.45j) ``` ### 7.1 Строка символов ```py >>> ss1='Это - строка символов' >>> ss1; type(ss1) 'Это - строка символов' >>> ss1a="Это - \" строка символов \", \n \t выводимая на двух строках" >>> print(ss1a) Это - " строка символов ", выводимая на двух строках >>> ss1b = 'Меня зовут \n Грудинин Е.К.' >>> print(ss1b) Меня зовут Грудинин Е.К. >>> mnogo="""Нетрудно заметить , что в результате операции над числами разных типов получается число, имеющее более сложный тип из тех, которые участвуют в операции.""" >>> print(mnogo) Нетрудно заметить , что в результате операции над числами разных типов получается число, имеющее более сложный тип из тех, которые участвуют в операции. >>> ss1[0] 'Э' >>> ss1[8] 'р' >>> ss1[-2] 'о' ``` ### 7.2 Срезы ```py >>> ss1[6:9] 'стр' >>> ss1[13:] 'символов' >>> ss1[:13] 'Это - строка ' >>> >>> ss1[5:-8] ' строка ' >>> ss1[3:17:2] ' тоасм' ``` С отрицательным шагом ```py >>> ss1[17:3:-2] 'омсаот ' ``` ```py >>> ss1[-4:3:-2] 'омсаот ' ``` Строка - неизменяемый объект ```py >>> ss1[4]='=' Traceback (most recent call last): File "", line 1, in ss1[4]='=' TypeError: 'str' object does not support item assignment ``` ```py >>> ss1=ss1[:4]+'='+ss1[5:] >>> ss1 'Это = строка символов' >>> ss1b = ss1b[:13] + 'Грудинин Е.К.'; ss1b >>> print(ss1b) Меня зовут Грудинин Е.К. ``` ```py >>> a = 10; a; type(a) 10 >>> a = 1.14; a; type(a) 1.14 >>> a = True; a; type(a) True >>> a = 4 + 2j; a; type(a) (4+2j) >>> a = complex(4,2); a; type(a) (4+2j) >>> a = 'Hello, World!'; a; type(a) 'Hello, World!' ``` ## 8 Более сложные типы объектов ### 8.1 Списки #### 8.1.1 Индексы и срезы ```py >>> spis1=[111,'Spisok',5-9j]; 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] >>> spis = [1,2,3,4, 5,6,7, 8,9,10]; spis [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] >>> spis[-1] 10 >>> stup[-8::2] [0, 1, 1, 1] ``` ```py >>> spis1[1]='Список'; spis1 [111, 'Список', (5-9j)] ``` #### 8.1.2 Методы списков Все методы списка spis1 можно увидеть камандой dir (они, методы, без двойных нижних подчеркиваний): ```py >>> dir(spis1) ['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort'] ``` ```py >>> spis1.append('New item') >>> spis1 [111, 'Список', (5-9j), 'New item'] >>> spis1+['New item']; spis1 [111, 'Список', (5-9j), 'New item', 'New item'] [111, 'Список', (5-9j), 'New item'] ``` Что не сохраняет изменения списка spis1, а только отображает измененый список. ```py >>> spis1.append(ss1b); spis1 [111, 'Список', (5-9j), 'New item', 'Меня зовут \n Ivanov I.I.'] >>> spis1.pop(1); spis1 'Список' [111, (5-9j), 'New item', 'Меня зовут \n Ivanov I.I.'] >>> spis1.insert(1,"Второй элемент"); spis1 [111, 'Второй элемент', 'Второй элемент', (5-9j), 'New item', 'Меня зовут \n Ivanov I.I.'] >>> ls = [1,2,3,4,5,2]; ls.remove(2); ls [1, 3, 4, 5, 2] >>> help(ls.extend) >>> ls.extend([3,4,5,6]) >>> ls [1, 3, 4, 5, 2, 3, 4, 5, 6] >>> ls.extend([3,4,5,6]); ls [1, 3, 4, 5, 2, 3, 4, 5, 6, 3, 4, 5, 6] >>> ls.clear(); ls [] >>> ls = [1,2,5,4,7,6,9] >>> ls.sort(); ls [1, 2, 4, 5, 6, 7, 9] >>> ls.sort(reverse = True); ls [9, 7, 6, 5, 4, 2, 1] >>> ls; ls.reverse(); ls [9, 7, 6, 5, 4, 2, 1] [1, 2, 4, 5, 6, 7, 9] >>> spis2 = [[1,2], [3,4],5,6,7] >>> cp = spis2.copy() >>> cp [[1, 2], [3, 4], 5, 6, 7] >>> cp[0][0] = 100; cp[3] = 200 >>> spis2; cp [[100, 2], [3, 4], 5, 6, 7] [[100, 2], [3, 4], 5, 200, 7] ``` Можно заметить, что при изменении в cp (копии) части вложенного списка, изменения затронули и исходный список spis2. ```py >>> a = [1,2,2,3,3,3,4,4,4,4] >>> a.count(1); a.count(2); a.count(4) 1 2 4 >>> a.index(4) 6 ``` #### 8.1.3 Вложенные списки ```py >>> spis2=[spis1,[4,5,6,7]]; spis2 [[111, 'Второй элемент', 'Второй элемент', (5-9j), 'New item', 'Меня зовут \n Ivanov I.I.'], [4, 5, 6, 7]] >>> spis2[0][1] 'Второй элемент' >>> spis2[0][1] = 78; spis2 [[111, 78, 'Второй элемент', (5-9j), 'New item', 'Меня зовут \n Ivanov I.I.'], [4, 5, 6, 7]] >>> spis1 [111, 78, 'Второй элемент', (5-9j), 'New item', 'Меня зовут \n Ivanov I.I.'] ``` Заметим, что при изменении spis2[0][1] = 78, касающегося на первый взгляд только списка spis2, изменился и список spis1, который является составной чатсью списка spis2. ```py >>> ls = [1,'два',True,[4,4,4,4]]; ls [1, 'два', True, [4, 4, 4, 4]] >>> type(ls[0]);type(ls[1]);type(ls[2]); type(ls[3]) ``` ### 8.2 Кортежи и их методы ```py >>> kort1=(222,'Kortezh',77+8j); kort1 (222, 'Kortezh', (77+8j)) >>> kort1[0] = 1 Traceback (most recent call last): File "", line 1, in kort1[0] = 1 TypeError: 'tuple' object does not support item assignment >>> kort1= kort1+(1,2); kort1 (222, 'Kortezh', (77+8j), 1, 2) >>> kort1= kort1+(ss1b,); kort1 (222, 'Kortezh', (77+8j), 1, 2, 'Меня зовут \n Ivanov I.I.') >>> type((0,)) >>> kort2=kort1[:2]+kort1[3:]; kort2 (222, 'Kortezh', 1, 2, 'Меня зовут \n Ivanov I.I.') >>> kort1.index(2) 4 >>> kort1.count(222) 1 ``` ### 8.3 Словари ```py >>> dic1={'Saratov':145, 'Orel':56, 'Vologda':45}; dic1 {'Saratov': 145, 'Orel': 56, 'Vologda': 45} >>> 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'}; 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' >>> 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 Ivanov I.I.'} >>> dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b])); dic5 {'A': 16, 'B': -3, 'C': 9, 'Stroka': 'Меня зовут \n Ivanov I.I.'} >>> keys = (11,22,33,44,55,66,77) >>> values = ['один','два','три','четыре','пять'] >>> dict(zip(keys,values)) {11: 'один', 22: 'два', 33: 'три', 44: 'четыре', 55: 'пять'} >>> dict(zip(values,keys)) {'один': 11, 'два': 22, 'три': 33, 'четыре': 44, 'пять': 55} ``` ### 8.4 Множества. Операции с множествами ```py >>> mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}; mnoz1 {'двигатель', 'микропроцессор', 'датчик', 'линия связи'} >>> len(mnoz1) 4 >>> 'датчик' in mnoz1 True >>> mnoz1.add('реле'); mnoz1 {'линия связи', 'микропроцессор', 'датчик', 'реле', 'двигатель'} >>> mnoz1.remove('линия связи'); mnoz1 {'микропроцессор', 'датчик', 'реле', 'двигатель'} ``` Заметим, что значение True = 1 не вошло в множество, так как уже есть 1. ```py >>> mnoz2 = {'строка',1,True,(5,6),1,'строка', False};mnoz2 {False, 1, (5, 6), 'строка'} >>> len(mnoz2) 4 >>> mnoz2.add(2); mnoz2 {False, 1, 2, 'строка', (5, 6)} >>> False in mnoz2 True >>> 'строка' in mnoz2 True >>> mnoz2.remove(2); mnoz2 {False, 1, 'строка', (5, 6)} ```