форкнуто от main/python-labs
Родитель
619fdaa6fb
Сommit
669cf0a11c
@ -0,0 +1,4 @@
|
||||
gg1=1.6 #значение в виде вещественного числа
|
||||
hh1='Строка' #значение в виде символьной строки
|
||||
73sr=3 #неправильное имя – начинается с цифры - будет диагностика!
|
||||
and=7 #недопустимое имя – совпадает с ключевым словом - будет диагностика!
|
||||
@ -0,0 +1,255 @@
|
||||
# Отчет по теме 2
|
||||
|
||||
Коваленко Дмитрий, А-01-23
|
||||
|
||||
## 2 Базовые типы объектов
|
||||
|
||||
### 2.1 Изучение простых объектов
|
||||
|
||||
```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__', '__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_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
|
||||
TypeError: type() takes 1 or 3 arguments
|
||||
>>> type(f2)
|
||||
<class 'int'>
|
||||
>>> del f1,f2
|
||||
>>> dir()
|
||||
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__']
|
||||
```
|
||||
Видим, что переменные имеют тип `int`. При помощи `dir(var)` можно узнать методы объекта, а при вызове `dir()` можно посмотреть, какие переменные есть в памяти. Как можно видеть из последнего запуска `dir()`, переменные `f1`, `f2` были удалены из памяти программы.
|
||||
### 2.2 Изучение правил именования
|
||||
|
||||
Создал программу [prog1.py](prog1.py) и записал в неё несколько комманд для проверки правил именования. Ожидаемо, получил ошибку на неправильном имени файла
|
||||
```
|
||||
vatarishin@MacBook-Air python-labs % /Library/Developer/CommandLineTools/usr/bin/python3 /Users/vatarishin/lab_sem_5/python-labs/
|
||||
TEMA2/prog1.py
|
||||
File "/Users/vatarishin/lab_sem_5/python-labs/TEMA2/prog1.py", line 3
|
||||
73sr=3 #неправильное имя – начинается с цифры - будет диагностика!
|
||||
^
|
||||
SyntaxError: invalid syntax
|
||||
```
|
||||
### 2.3 Изучение списка ключевых слов
|
||||
```
|
||||
>>> import keyword
|
||||
>>> kw = keyword.kwlist
|
||||
>>> print(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']
|
||||
```
|
||||
|
||||
### 2.4 Выведение списка встроенных идентификаторов
|
||||
```
|
||||
>>> import builtins
|
||||
>>> dir(builtins)
|
||||
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', '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', 'ZeroDivisionError', '__build_class__', '__debug__', '__doc__', '__import__', '__loader__', '__name__', '__package__', '__spec__', 'abs', 'all', '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']
|
||||
```
|
||||
Изучим функцию `zip()`
|
||||
|
||||
```
|
||||
Help on class zip in module builtins:
|
||||
|
||||
class zip(object)
|
||||
| zip(*iterables) --> A zip object yielding 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.
|
||||
```
|
||||
### 2.5 Рассмотрим значимость регистров
|
||||
```
|
||||
>>> Gg1=45
|
||||
>>> gg1
|
||||
Traceback (most recent call last):
|
||||
File "<stdin>", line 1, in <module>
|
||||
NameError: name 'gg1' is not defined
|
||||
>>> Gg1
|
||||
45
|
||||
```
|
||||
|
||||
### 2.6 Изучим простые типы объектов
|
||||
|
||||
Логический тип
|
||||
```
|
||||
>>> bb1=True; bb2=False
|
||||
>>> bb1;bb2
|
||||
True
|
||||
False
|
||||
>>> type(bb1)
|
||||
<class 'bool'>
|
||||
```
|
||||
|
||||
Прочие типы
|
||||
```
|
||||
>>> 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) #Создается комплексное число
|
||||
>>> cc2
|
||||
(3.67-0.45j)
|
||||
```
|
||||
Символьные строки
|
||||
```
|
||||
>> ss1='Это - строка символов'
|
||||
>>> ss1="Это - строка символов"
|
||||
>>> ss1a="Это - \" строка символов \", \n \t выводимая на двух строках";print(ss1a)
|
||||
Это - " строка символов ",
|
||||
выводимая на двух строках
|
||||
>>> ss1b= 'Меня зовут: \n Коваленко Д.М.'
|
||||
>>> print(ss1b)
|
||||
Меня зовут:
|
||||
Коваленко Д.М.
|
||||
>>> mnogo="""Нетрудно заметить , что в результате операции
|
||||
... над числами разных типов получается число,
|
||||
... имеющее более сложный тип из тех, которые участвуют в операции."""
|
||||
>>> print(mnogo)
|
||||
Нетрудно заметить , что в результате операции
|
||||
над числами разных типов получается число,
|
||||
имеющее более сложный тип из тех, которые участвуют в операции.
|
||||
>>> ss1="Это - строка символов"
|
||||
>>> ss1[0] #Это – символ «Э»
|
||||
'Э'
|
||||
>>> ss1[8] #А это – символ «р»
|
||||
'р'
|
||||
>>> ss1[-2] #А это – символ «о» (при знаке «-»(минус) отсчет от конца строки)
|
||||
'о'
|
||||
ss1[6:9] #Это часть строки – символы с 6-го индекса по 8-й (9-й не включается!)
|
||||
ss1[13:] #Это часть строки – с 13-го индекса и до конца
|
||||
ss1[:13] #Это часть строки – с начала и до 12-го индекса включительно
|
||||
ss1[5:-8] #Это часть строки – с 5-го индекса и до 8-го от конца
|
||||
ss1[3:17:2] #Часть строки – с 3-го по 16-й индексы с шагом 2
|
||||
>>> ss1[17:3:-2]
|
||||
'омсаот '
|
||||
>>> 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:]
|
||||
>>> ss1
|
||||
'Это = строка символов'
|
||||
```
|
||||
|
||||
### 2.7 Изучим более сложные типы объектов
|
||||
```
|
||||
>>> spis1=[111,'Spisok',5-9j]
|
||||
>>> spis1
|
||||
[111, 'Spisok', (5-9j)]
|
||||
>>> stup=[0,0,1,1,1,1,1,1,1]
|
||||
>>> spis=[1,2,3,4,
|
||||
... 5, 6, 7,
|
||||
... 8, 9]
|
||||
>>> stup[-8::2]
|
||||
[0, 1, 1, 1]
|
||||
>>> spis1[1]='Список'
|
||||
>>> spis1
|
||||
[111, 'Список', (5-9j)]
|
||||
|
||||
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')
|
||||
>>> spis1+['New item']
|
||||
[111, 'Список', (5-9j), 'New item', 'New item']
|
||||
>>> spis1.pop(1)
|
||||
'Список'
|
||||
>>> spis2=[spis1,[4,5,6,7]]
|
||||
>>> spis2
|
||||
[[111, (5-9j), 'New item'], [4, 5, 6, 7]]
|
||||
>>> spis2[0][1]
|
||||
(5-9j)
|
||||
>>> spis2[0][1]=78
|
||||
>>> spis1
|
||||
[111, 78, 'New item']
|
||||
```
|
||||
Видим, что при изменении вложенного списка, изменяется и сам исходный список. Это происходит потому что при создании `spis2` была использована ссылка на `spis1`. Чтобы списки были независимы, в `spis2` надо передовать копию списка.
|
||||
Создадим свой объект-список
|
||||
```myList1 = [1, '1', True, [1, '1', True]]```
|
||||
|
||||
### 2.8 Изучим кортежи
|
||||
|
||||
```
|
||||
>>> kort1=(222,'Kortezh',77+8j)
|
||||
>>> kort1
|
||||
(222, 'Kortezh', (77+8j))
|
||||
>>> kort1= kort1+(1,2)
|
||||
>>> kort1
|
||||
(222, 'Kortezh', (77+8j), 1, 2)
|
||||
>>> kort1= kort1+(ss1b,)
|
||||
>>> 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
|
||||
|
||||
kort0 = (0, '0', [False, False], (0, '0', False))
|
||||
```
|
||||
|
||||
### 2.9 Изучим словари
|
||||
|
||||
```
|
||||
>> 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'}
|
||||
>>> 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)])
|
||||
>>> dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b]))
|
||||
>>> 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
|
||||
```
|
||||
|
||||
### 2.10 Изучим множества
|
||||
|
||||
```
|
||||
>>> mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}
|
||||
>>> mnoz1
|
||||
{'двигатель', 'датчик', 'линия связи', 'микропроцессор'}
|
||||
>>> len(mnoz1)
|
||||
4
|
||||
>>> 'датчик' in mnoz1
|
||||
True
|
||||
>>> mnoz1.add('реле')
|
||||
>>> mnoz1.remove('линия связи')
|
||||
>>> mnoz1
|
||||
{'микропроцессор', 'реле', 'двигатель', 'датчик'}
|
||||
|
||||
>>> set1 = {1, 1, '1', "1", True, True, (1, '1')}
|
||||
>>> set1
|
||||
{1, '1', (1, '1')}
|
||||
>>> len(set1)
|
||||
3
|
||||
```
|
||||
|
||||
@ -0,0 +1,41 @@
|
||||
# Общее контрольное задание по теме 2
|
||||
|
||||
Коваленко Дмитрий, А-01-23
|
||||
|
||||
## Задание
|
||||
|
||||
• Создать переменную с именем `familia` и со значением - символьной строкой – своей фамилией в латинской транскрипции.
|
||||
• Создать переменную со значением, совпадающим с первой буквой из `familia`.
|
||||
• Создать переменную с именем `sp_kw` со значением – списком всей ключевых слов языка Python.
|
||||
• Удалите из списка `sp_kw` значение `'nonlocal'`. Выводом списка в командном окне IDLE убедитесь, что это значение удалено из списка.
|
||||
• Создайте кортеж `kort_nam` с именами: вашим и еще 3-х студентов из вашей группы. Напишите инструкцию, позволяющую убедиться, что тип переменной – это `tuple`.
|
||||
• Напишите инструкцию, добавляющую в `kort_nam` имена еще двух студентов.
|
||||
• Напишите инструкцию, позволяющую определить, сколько раз в кортеже присутствуют студенты с именем «Дима».
|
||||
• Создайте словарь `dict_bas`, в котором ключами являются русские названия типов переменных, использованных в предыдущих операторах, а значениями – ранее созданные переменные, соответствующие этим типам.
|
||||
|
||||
## Решение
|
||||
|
||||
```py
|
||||
import keyword
|
||||
|
||||
|
||||
familia = 'Kovalenko'
|
||||
withLetK = familia[0]
|
||||
sp_kw = keyword.kwlist
|
||||
sp_kw.remove('nonlocal')
|
||||
sp_kw
|
||||
|
||||
kort_nam = ('Дмитрий', 'Максим', 'Даниил', 'Дима')
|
||||
type(kort_nam)
|
||||
kort_nam = kort_nam+('Александр', 'Елизавета')
|
||||
kort_nam.count('Дима')
|
||||
dict_bas = {'строка': [familia, withLetK], 'Список': sp_kw, 'Кортеж': kort_nam}
|
||||
```
|
||||
|
||||
```
|
||||
['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']
|
||||
>>> type(kort_nam)
|
||||
<class 'tuple'>
|
||||
>>> kort_nam.count('Дима')
|
||||
1
|
||||
```
|
||||
Загрузка…
Ссылка в новой задаче