форкнуто от main/python-labs
Родитель
0464627b18
Сommit
50780de001
|
После Ширина: | Высота: | Размер: 107 KiB |
@ -0,0 +1,287 @@
|
||||
#Протокол по Теме 2 Анисенков Павел Дмитриевич
|
||||
import os
|
||||
os.chdir('C:\\Users\\Professional\\Desktop\\python-labs\\Tema2')
|
||||
|
||||
f1=16; f2=3
|
||||
f1,f2
|
||||
(16, 3)
|
||||
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)
|
||||
<class 'int'>
|
||||
del f1,f2
|
||||
f1,f2
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#8>", line 1, in <module>
|
||||
f1,f2
|
||||
NameError: name 'f1' is not defined
|
||||
gg1=1.6
|
||||
hh1='Строка'
|
||||
73sr=3
|
||||
SyntaxError: invalid decimal literal
|
||||
and=7
|
||||
SyntaxError: invalid syntax
|
||||
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']
|
||||
spis='['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']'
|
||||
SyntaxError: invalid syntax
|
||||
spis=['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']
|
||||
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']
|
||||
print(abs(-5))
|
||||
5
|
||||
print(len("Hello"))
|
||||
5
|
||||
print(len([1, 2, 3]))
|
||||
3
|
||||
print(max(1, 5, 3))
|
||||
5
|
||||
print(min([10, 20, 5]))
|
||||
5
|
||||
print(pow(5, 2))
|
||||
25
|
||||
print(pow(4, 0.5))
|
||||
2.0
|
||||
print(round(3.14159))
|
||||
3
|
||||
print(round(2.675, 2))
|
||||
2.67
|
||||
print(sorted("hello"))
|
||||
['e', 'h', 'l', 'l', 'o']
|
||||
2
|
||||
print(sorted(numbers))
|
||||
[1, 2, 3, 4]
|
||||
print(sorted(numbers, reverse=True))
|
||||
[4, 3, 2, 1]
|
||||
names = ["Alice", "Bob"]
|
||||
ages = [25, 30]
|
||||
pop = zip(names, ages)
|
||||
print(list(pop))
|
||||
[('Alice', 25), ('Bob', 30)]
|
||||
print(type(5))
|
||||
<class 'int'>
|
||||
print(type("hello"))
|
||||
<class 'str'>
|
||||
print(type([1, 2, 3]))
|
||||
<class 'list'>
|
||||
print(dir("hello"))
|
||||
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getstate__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'removeprefix', 'removesuffix', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
|
||||
Gg1=45
|
||||
print(gg1,Gg1)
|
||||
1.6 45
|
||||
bb1 = True; bb2 = False
|
||||
bb1,bb2
|
||||
(True, False)
|
||||
type(bb1)
|
||||
<class 'bool'>
|
||||
ii1=-1234567890
|
||||
ff1=-8.9876e-12
|
||||
dv1=0b1101010
|
||||
vsm1-0o52765
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#48>", line 1, in <module>
|
||||
vsm1-0o52765
|
||||
NameError: name 'vsm1' is not defined
|
||||
vsm1=0o52765
|
||||
shest1=0x7109af6
|
||||
cc1=2-3j
|
||||
a=3.67;b=-0.45
|
||||
cc2=complex(a,b)
|
||||
ss1
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#54>", line 1, in <module>
|
||||
ss1
|
||||
NameError: name 'ss1' is not defined
|
||||
ss1='Это - строка символов'
|
||||
ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"
|
||||
ss1a
|
||||
'Это - " строка символов ", \n \t выводимая на двух строках'
|
||||
ss1b= 'Меня зовут: \n Анисенков П. Д.'
|
||||
ыы1и
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#59>", line 1, in <module>
|
||||
ыы1и
|
||||
NameError: name 'ыы1и' is not defined
|
||||
ss1b
|
||||
'Меня зовут: \n Анисенков П. Д.'
|
||||
print(ss1b)
|
||||
Меня зовут:
|
||||
Анисенков П. Д.
|
||||
print(ss1a)
|
||||
Это - " строка символов ",
|
||||
выводимая на двух строках
|
||||
mnogo="""Нетрудно заметить , что в результате операции
|
||||
над числами разных типов получается число,
|
||||
имеющее более сложный тип из тех, которые участвуют в операции."""
|
||||
print(mnogo)
|
||||
Нетрудно заметить , что в результате операции
|
||||
над числами разных типов получается число,
|
||||
имеющее более сложный тип из тех, которые участвуют в операции.
|
||||
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[-4:3:-2]
|
||||
'омсаот '
|
||||
ss1[4]
|
||||
'-'
|
||||
ss1=ss1[:4]+'='+ss1[5:]
|
||||
slice1 = ss1b[:10]
|
||||
slice1
|
||||
'Меня зовут'
|
||||
slice2 = ss1b[12:]
|
||||
slice2
|
||||
'\n Анисенков П. Д.'
|
||||
slice5 = ss1b[::2]
|
||||
slice5
|
||||
'Мн оу:\nАиеквП .'
|
||||
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,10]
|
||||
spis1[-1]
|
||||
(5-9j)
|
||||
stup[-8::2]
|
||||
[0, 1, 1, 1]
|
||||
spis1[1]='Список'
|
||||
print(spis1)
|
||||
[111, 'Список', (5-9j)]
|
||||
len(spis1)
|
||||
3
|
||||
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+['New item']
|
||||
[111, 'Список', (5-9j), 'New item']
|
||||
spis1+'ss1b'
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#95>", line 1, in <module>
|
||||
spis1+'ss1b'
|
||||
TypeError: can only concatenate list (not "str") to list
|
||||
spis1+['ss1b']
|
||||
[111, 'Список', (5-9j), 'ss1b']
|
||||
spis1+ss1b
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#97>", line 1, in <module>
|
||||
spis1+ss1b
|
||||
TypeError: can only concatenate list (not "str") to list
|
||||
spis1.pop(1)
|
||||
'Список'
|
||||
spis1
|
||||
[111, (5-9j)]
|
||||
spis2=[spis1,[4,5,6,7]]
|
||||
spis2[0][1]
|
||||
(5-9j)
|
||||
spis2[0][1]=78
|
||||
spis1
|
||||
[111, 78]
|
||||
spisk=[20,'Pavel',0.4532]
|
||||
spisk+ [1,2,3,4,5],{"имя":"Павел", "возраст": 20}
|
||||
([20, 'Pavel', 0.4532, 1, 2, 3, 4, 5], {'имя': 'Павел', 'возраст': 20})
|
||||
kort1=(222,'Kortezh',77+8j)
|
||||
kort1= kort1+(1,2)
|
||||
kort1
|
||||
(222, 'Kortezh', (77+8j), 1, 2)
|
||||
kort1= kort1+(ss1b,)
|
||||
kort1
|
||||
(222, 'Kortezh', (77+8j), 1, 2, 'Меня зовут: \n Анисенков П. Д.')
|
||||
kort2=kort1[:2]+kort1[3:]
|
||||
kort1.index(2)
|
||||
4
|
||||
kort1.count(222)
|
||||
1
|
||||
kort1[2]=90
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#114>", line 1, in <module>
|
||||
kort1[2]=90
|
||||
TypeError: 'tuple' object does not support item assignment
|
||||
my_tuple = (
|
||||
42, # целое число
|
||||
"Привет", # строка
|
||||
[1, 2, 3], # список
|
||||
(4, 5, 6) #кортеж
|
||||
)
|
||||
|
||||
dic1={'Saratov':145, 'Orel':56, 'Vologda':45}
|
||||
dic1['Orel']
|
||||
|
||||
56
|
||||
dic1['Pskov']=78
|
||||
вшс1
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#119>", line 1, in <module>
|
||||
вшс1
|
||||
NameError: name 'вшс1' is not defined
|
||||
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)])
|
||||
spska = ('яблоко', 'банан', 'апельсин', 'виноград', 'киви', 'манго', 'груша')
|
||||
spysk = [10, 20, 30, 40, 50]
|
||||
res = dict(zip(spska, spysk))
|
||||
res
|
||||
{'яблоко': 10, 'банан': 20, 'апельсин': 30, 'виноград': 40, 'киви': 50}
|
||||
mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}
|
||||
mnoz1
|
||||
{'линия связи', 'датчик', 'двигатель', 'микропроцессор'}
|
||||
len(mnoz1)
|
||||
4
|
||||
'датчик' in mnoz1
|
||||
True
|
||||
mnoz1.add('реле')
|
||||
mnoz1
|
||||
{'линия связи', 'датчик', 'двигатель', 'реле', 'микропроцессор'}
|
||||
mnoz1.remove('линия связи')
|
||||
mnoz1
|
||||
{'датчик', 'двигатель', 'реле', 'микропроцессор'}
|
||||
set123= {
|
||||
42, # целое число
|
||||
3.14, # число с плавающей точкой
|
||||
"Привет", # строка
|
||||
(1, 2, 3), # кортеж
|
||||
True, # логическое значение
|
||||
"Python", # еще строка
|
||||
frozenset([7, 8, 9]), # неизменяемое множество
|
||||
42 # дубликат (будет удален)
|
||||
}
|
||||
set123.add([7, 8, 9])
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#140>", line 1, in <module>
|
||||
set123.add([7, 8, 9])
|
||||
TypeError: unhashable type: 'list'
|
||||
my_set.remove("Привет")
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#141>", line 1, in <module>
|
||||
my_set.remove("Привет")
|
||||
NameError: name 'my_set' is not defined
|
||||
set123.remove("Привет")
|
||||
set123
|
||||
{True, 3.14, 42, (1, 2, 3), 'Python', frozenset({8, 9, 7})}
|
||||
|
||||
|
После Ширина: | Высота: | Размер: 36 KiB |
|
После Ширина: | Высота: | Размер: 19 KiB |
|
После Ширина: | Высота: | Размер: 28 KiB |
@ -0,0 +1,739 @@
|
||||
# Отчет по теме 2
|
||||
|
||||
Анисенков Павел, А-01-23
|
||||
|
||||
## 1. Запуск.
|
||||
|
||||
### 1.1 Запуск оболочки IDLE и установка рабочего каталога.
|
||||
|
||||
```py
|
||||
import os
|
||||
os.chdir('C:\\Users\\Professional\\Desktop\\python-labs\\TEMA1\\')
|
||||
```
|
||||
|
||||
|
||||
## 2. Изучение простых объектов.
|
||||
|
||||
### 2.1 Операции присваивания
|
||||
|
||||
```py
|
||||
f1=16; f2=3
|
||||
f1,f2
|
||||
(16, 3)
|
||||
f1;f2
|
||||
16
|
||||
3
|
||||
```
|
||||
### 2.2 Функционал команд dir(), type() и del:
|
||||
|
||||
Был получен список атрибутов объекта f1:
|
||||
|
||||
```py
|
||||
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']
|
||||
```
|
||||
|
||||
Также была определена классовая принадлежность объекта f2:
|
||||
|
||||
```py
|
||||
type(f2)
|
||||
<class 'int'>
|
||||
```
|
||||
|
||||
Команда del отвечает за удаление объекта или его части из ОП.
|
||||
|
||||
```py
|
||||
del f1, f2
|
||||
|
||||
f1, f2
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#9>", line 1, in <module>
|
||||
f1, f2
|
||||
NameError: name 'f1' is not defined
|
||||
```
|
||||
|
||||
## 3-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']
|
||||
```
|
||||
В данном случае полученному списку было присвоено следующее имя:
|
||||
|
||||
```py
|
||||
pisok = keyword.kwlist
|
||||
pisok
|
||||
['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. Встроенные идентификаторы.
|
||||
|
||||
### 5.1 Вывод списка встроенных идентификаторов:
|
||||
|
||||
```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.2 Изучение назначения функций:
|
||||
```py
|
||||
print(abs(-5))
|
||||
5
|
||||
print(len("Hello"))
|
||||
5
|
||||
print(len([1, 2, 3]))
|
||||
3
|
||||
print(max(1, 5, 3))
|
||||
5
|
||||
print(min([10, 20, 5]))
|
||||
5
|
||||
print(pow(5, 2))
|
||||
25
|
||||
print(pow(4, 0.5))
|
||||
2.0
|
||||
print(round(3.14159))
|
||||
3
|
||||
print(round(2.675, 2))
|
||||
2.67
|
||||
print(sorted("hello"))
|
||||
['e', 'h', 'l', 'l', 'o']
|
||||
numbers = [3, 1, 4, 2]
|
||||
print(sorted(numbers))
|
||||
[1, 2, 3, 4]
|
||||
print(sorted(numbers, reverse=True))
|
||||
[4, 3, 2, 1]
|
||||
names = ["Alice", "Bob"]
|
||||
ages = [25, 30]
|
||||
pop = zip(names, ages)
|
||||
print(list(pop))
|
||||
[('Alice', 25), ('Bob', 30)]
|
||||
```
|
||||
#### 5.2.1 Функция ABS:
|
||||
|
||||

|
||||
|
||||
#### 5.2.2 Функция len:
|
||||
|
||||

|
||||
|
||||
#### 5.2.3 Функция max
|
||||
|
||||
```py
|
||||
help(max)
|
||||
Help on built-in function max in module builtins:
|
||||
|
||||
max(...)
|
||||
max(iterable, *[, default=obj, key=func]) -> value
|
||||
.......
|
||||
With two or more positional arguments, return the largest argument.
|
||||
|
||||
max(numbers)
|
||||
3
|
||||
```
|
||||
|
||||
#### 5.2.4 Функция min
|
||||
|
||||
```py
|
||||
help(min)
|
||||
Help on built-in function min in module builtins:
|
||||
|
||||
min(...)
|
||||
min(iterable, *[, default=obj, key=func]) -> value
|
||||
............
|
||||
With two or more positional arguments, return the smallest argument.
|
||||
|
||||
min(numbers)
|
||||
1
|
||||
```
|
||||
|
||||
|
||||
#### 5.2.5 Функция pow
|
||||
|
||||
```py
|
||||
help(pow)
|
||||
Help on built-in function pow in module builtins:
|
||||
|
||||
pow(base, exp, mod=None)
|
||||
...........
|
||||
invoked using the three argument form.
|
||||
|
||||
pow(3, 2)
|
||||
9
|
||||
```
|
||||
|
||||
#### 5.2.6 Функция round
|
||||
|
||||
```py
|
||||
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.
|
||||
|
||||
round(1.5)
|
||||
2
|
||||
```
|
||||
|
||||
#### 5.2.7 Функция sorted
|
||||
|
||||
```py
|
||||
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.
|
||||
|
||||
num = [3, 1, 2]
|
||||
sorted(num)
|
||||
[1, 2, 3]
|
||||
```
|
||||
|
||||
|
||||
|
||||
#### 5.2.8 Функция sum
|
||||
|
||||
```py
|
||||
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.
|
||||
|
||||
sum(num)
|
||||
6
|
||||
```
|
||||
|
||||
#### 5.2.9 Функция zip
|
||||
|
||||
```py
|
||||
help(zip)
|
||||
Help on class zip in module builtins:
|
||||
|
||||
class zip(object)
|
||||
| zip(*iterables, strict=False)
|
||||
|
|
||||
| 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
|
||||
...........................................
|
||||
|
||||
num
|
||||
[3, 1, 2]
|
||||
numbers
|
||||
[1, 2, 3]
|
||||
j = zip(num, numbers)
|
||||
j
|
||||
<zip object at 0x000001E309D6DD00>
|
||||
zip_list = list(j)
|
||||
zip_list
|
||||
[(3, 1), (1, 2), (2, 3)]
|
||||
```
|
||||
|
||||
## 6-7. Типы объектов.
|
||||
|
||||
### 6. Проверка влияния больших и маленьких букв в имени переменных:
|
||||
|
||||
```py
|
||||
Gg1=45
|
||||
gg1
|
||||
1.6
|
||||
Gg1
|
||||
45
|
||||
```
|
||||
### 7. Изучение базовых типов объектов:
|
||||
|
||||
int — целые числа (положительные, отрицательные или нуль).
|
||||
float — числа с плавающей точкой (дробные числа).
|
||||
complex — комплексные числа (имеют действительную и мнимую части).
|
||||
str — строковый тип данных для хранения текстовой информации. Строка может содержать буквы, цифры, пробелы, символы.
|
||||
bool в Python — это логический тип, принимать только два значения: True и False.
|
||||
|
||||
|
||||
#### 7.1 Логический тип:
|
||||
|
||||
```py
|
||||
bb1 = True
|
||||
bb2 = False
|
||||
bb1;bb2
|
||||
True
|
||||
False
|
||||
type(bb1)
|
||||
<class 'bool'>
|
||||
```
|
||||
|
||||
#### 7.2 Иные простые типы:
|
||||
|
||||
```py
|
||||
ii1=-1234567890
|
||||
type(ii1)
|
||||
<class 'int'>
|
||||
|
||||
ff1=-8.9876e-12
|
||||
type(ff1)
|
||||
|
||||
<class 'float'>
|
||||
|
||||
dv1=0b1101010
|
||||
|
||||
type(dv1)
|
||||
|
||||
<class 'int'>
|
||||
```
|
||||
|
||||
Как можем заметить - двоичное число 0b1101010 в Python сохраняется в объекте класса int.
|
||||
|
||||
```py
|
||||
vsm1=0o52765
|
||||
type(vsm1)
|
||||
<class 'int'>
|
||||
```
|
||||
|
||||
```py
|
||||
shest1=0x7109af6
|
||||
type(shest1)
|
||||
<class 'int'>
|
||||
cc1=2-3j
|
||||
type(cc1)
|
||||
<class 'complex'>
|
||||
```
|
||||
|
||||
Ниже представлен иной способ создания комплексного числа:
|
||||
|
||||
```py
|
||||
a=3.67; b=-0.45
|
||||
cc2=complex(a,b)
|
||||
type(cc2)
|
||||
<class 'complex'>
|
||||
```
|
||||
|
||||
#### 7.3 Строка символом:
|
||||
|
||||
Строки выделяются как и апострофами, так и двойными кавычками, продемонстрируем:
|
||||
|
||||
```py
|
||||
ss1='Это - строка символов'
|
||||
ss1="Это - строка символов"
|
||||
```
|
||||
|
||||
##### Экранированные последовательности:
|
||||
```py
|
||||
ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"
|
||||
print(ss1a)
|
||||
```
|
||||
|
||||
Создадим строку по шаблону:
|
||||
|
||||
```py
|
||||
ss1b= 'Меня зовут: \n Анисенков П.Д.'
|
||||
print(ss1b)
|
||||
Меня зовут:
|
||||
Анисенков П.Д.
|
||||
```
|
||||
|
||||
Создадим строку со значением объекта при помощи тройных кавычек:
|
||||
|
||||
```py
|
||||
mnogo="""Нетрудно заметить , что в результате операции
|
||||
над числами разных типов получается число,
|
||||
имеющее более сложный тип из тех, которые участвуют в операции."""
|
||||
|
||||
print(mnogo)
|
||||
Нетрудно заметить , что в результате операции
|
||||
над числами разных типов получается число,
|
||||
имеющее более сложный тип из тех, которые участвуют в операции.
|
||||
```
|
||||
|
||||
```py
|
||||
|
||||
ss1[0]
|
||||
'Э'
|
||||
ss1[8]
|
||||
'р'
|
||||
ss1[-2]
|
||||
'о'
|
||||
ss1[0]
|
||||
'Э'
|
||||
ss1[8]
|
||||
'р'
|
||||
ss1[-2]
|
||||
'о'
|
||||
ss1[6:9]
|
||||
'стр'
|
||||
ss1[13:]
|
||||
'символов'
|
||||
ss1[:13]
|
||||
'Это - строка '
|
||||
ss1[5:-8]
|
||||
' строка '
|
||||
ss1[3:17:2]
|
||||
' тоасм'
|
||||
```
|
||||
Важно заметить, что цифра '2' здесь отвечает за шаг.
|
||||
|
||||
|
||||
Здесь, подобно примеру выше, мы перечислили элементы с индексами от 3 до 17, но в обратном порядке (с положительным шагом перечисление элементов в обратную сторону работать не будет).
|
||||
```py
|
||||
ss1[17:3:-2]
|
||||
'омсаот '
|
||||
```
|
||||
|
||||
Изменив '17' на '-4' мы получим тот же результат, ведь два этих индекса соответствуют одному и тому же элементу строки.
|
||||
```py
|
||||
ss1[-4:3:-2]
|
||||
'омсаот '
|
||||
```
|
||||
|
||||
Таким образом, мы переопределили элемент под индексом 4.
|
||||
```py
|
||||
ss1=ss1[:4]+'='+ss1[5:]
|
||||
ss1
|
||||
'Это = строка символов'
|
||||
```
|
||||
|
||||
|
||||
```py
|
||||
slice1 = ss1b[:10]
|
||||
slice1
|
||||
'Меня зовут'
|
||||
slice2 = ss1b[12:]
|
||||
slice2
|
||||
'\n Анисенков П. Д.'
|
||||
slice5 = ss1b[::2]
|
||||
slice5
|
||||
'Мн оу:\nАиеквП .'
|
||||
|
||||
```
|
||||
|
||||
## 8. Списки, кортежи, словари и множества.
|
||||
|
||||
```py
|
||||
|
||||
help(list)
|
||||
Help on class list in module builtins:
|
||||
|
||||
class list(object)
|
||||
| list(iterable=(), /)
|
||||
|
|
||||
| Built-in mutable sequence.
|
||||
|
|
||||
| If no argument is given, the constructor creates a new empty list.
|
||||
| The argument must be an iterable if specified.
|
||||
|
||||
|
||||
help(tuple)
|
||||
Help on class tuple in module builtins:
|
||||
|
||||
class tuple(object)
|
||||
| tuple(iterable=(), /)
|
||||
|
|
||||
| Built-in immutable sequence.
|
||||
|
|
||||
| If no argument is given, the constructor returns an empty tuple.
|
||||
| If iterable is specified the tuple is initialized from iterable's items.
|
||||
|
|
||||
| If the argument is a tuple, the return value is the same object.
|
||||
|
|
||||
| Built-in subclasses:
|
||||
| asyncgen_hooks
|
||||
| UnraisableHookArgs
|
||||
|
||||
|
||||
help(dict)
|
||||
Help on class dict in module builtins:
|
||||
|
||||
class dict(object)
|
||||
| dict() -> new empty dictionary
|
||||
| dict(mapping) -> new dictionary initialized from a mapping object's
|
||||
| (key, value) pairs
|
||||
| dict(iterable) -> new dictionary initialized as if via:
|
||||
| d = {}
|
||||
| for k, v in iterable:
|
||||
| d[k] = v
|
||||
| dict(**kwargs) -> new dictionary initialized with the name=value pairs
|
||||
| in the keyword argument list. For example: dict(one=1, two=2)
|
||||
|
||||
help(set)
|
||||
Help on class set in module builtins:
|
||||
|
||||
class set(object)
|
||||
| set(iterable=(), /)
|
||||
|
|
||||
| Build an unordered collection of unique elements.
|
||||
|
||||
```
|
||||
### 8.1 Работа со списками.
|
||||
|
||||
Список может содержать в себе элементы разных типов.
|
||||
```py
|
||||
spis1=[111,'Spisok',5-9j]
|
||||
spis1
|
||||
[111, 'Spisok', (5-9j)]
|
||||
```
|
||||
|
||||
Ввод можно производить в разных строках, пока не будет введена квадратная скобка.
|
||||
```py
|
||||
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]
|
||||
```
|
||||
|
||||
|
||||
'-8' - есть элемент под индексом 1 в исходном списке, между :: ничего нет, значит срез произойдёт до самого последнего элемента, а '2' - есть шаг пересчёта элементов.
|
||||
```py
|
||||
|
||||
spis1[-1]
|
||||
(5-9j)
|
||||
stup[-8::2]
|
||||
[0, 1, 1, 1]
|
||||
```
|
||||
|
||||
```py
|
||||
spis1[1]='Список'
|
||||
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] - был видоизменен, ведь является элементом другого списка, к которому мы обратились и изменили соответственно.
|
||||
```
|
||||
#### Был придуман список, содержащий в себе 4 элемента разных типов: число, строка, логическое значение и список.
|
||||
|
||||
```py
|
||||
list = ['glad', 18, True, ['a','b','c','d']]
|
||||
list
|
||||
['glad', 18, True, ['a', 'b', 'c', 'd']]
|
||||
type(list)
|
||||
<class 'list'>
|
||||
```
|
||||
|
||||
### 8.2 Кортеж.
|
||||
|
||||
*Похож на список, но изменить его нельзя
|
||||
```py
|
||||
kort1=(222,'Kortezh',77+8j)
|
||||
type(kort1)
|
||||
<class 'tuple'>
|
||||
kort1[2] = 90
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#22>", line 1, in <module>
|
||||
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', 'черный'}
|
||||
```
|
||||
## 9.
|
||||
|
||||
exit()
|
||||
|
||||
Загрузка…
Ссылка в новой задаче