форкнуто от main/python-labs
Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
203 строки
8.1 KiB
Markdown
203 строки
8.1 KiB
Markdown
# Отчет по Теме 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(f1)
|
|
<class 'int'>
|
|
>>> type(f2)
|
|
<class 'int'>
|
|
>>> 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 Ключевые слова
|
|
```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']
|
|
>>> ls = 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(-123)
|
|
123
|
|
>>> len(dir(builtins))
|
|
161
|
|
>>> max(1,2,3,4,-1,-5)
|
|
4
|
|
>>> min(-1,-2,-5,1,6,3)
|
|
-5
|
|
>>> pow(2,3)
|
|
8
|
|
>>> 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(3.14129,2)
|
|
3.14
|
|
>>> round(1.5); round(2.5)
|
|
2
|
|
2
|
|
>>> sorted([1,5,3,7,6,0,3])
|
|
[0, 1, 3, 3, 5, 6, 7]
|
|
>>> sorted(['Artem', 'Ann', 'Kate', 'Mike'])
|
|
['Ann', 'Artem', 'Kate', 'Mike']
|
|
>>> sorted(['Artem', 'Ann', 'Kate', 'Mike'], key = len)
|
|
['Ann', 'Kate', 'Mike', 'Artem']
|
|
>>> sum([1,2,3,4,5,6,7,8,9])
|
|
45
|
|
>>> sum([1,2,3,4,5,6,7,8,9], 10)
|
|
55
|
|
>>> firstNames = ['Artem', 'Kate', 'Ann']
|
|
>>> lastNames = ['Sidorov', 'Ivanova', 'Petrova']
|
|
>>> birthYears = [2005, 2004, 1995]
|
|
>>> data = zip(firstNames, lastNames, birthYears)
|
|
>>> list(data)
|
|
[('Artem', 'Sidorov', 2005), ('Kate', 'Ivanova', 2004), ('Ann', 'Petrova', 1995)]
|
|
```
|
|
|
|
## 6 Важность регистра
|
|
```py
|
|
>>> Gg1=45
|
|
>>> gg1; Gg1
|
|
1.6
|
|
45
|
|
```
|
|
|
|
## 7 Базовые типы объектов
|
|
```py
|
|
>>> bb1 = True; bb2 = False
|
|
>>> bb1; bb2
|
|
True
|
|
False
|
|
>>> type(bb1)
|
|
<class 'bool'>
|
|
>>> ii1 = -123456789
|
|
>>> type(ii1)
|
|
<class 'int'>
|
|
>>> ff1=-8.9876e-12
|
|
>>> type(ff1)
|
|
<class 'float'>
|
|
>>> dv1=0b1101010
|
|
>>> type(dv1)
|
|
<class 'int'>
|
|
>>> vsm1=0o52765
|
|
>>> type(vsm1)
|
|
<class 'int'>
|
|
>>> shest1=0x7109af6
|
|
>>> type(shest1)
|
|
<class 'int'>
|
|
>>> cc1=2-3j
|
|
>>> type(cc1)
|
|
<class 'complex'>
|
|
>>> a=3.67; b=-0.45
|
|
>>> cc2=complex(a,b)
|
|
>>> type(cc2)
|
|
<class 'complex'>
|
|
>>> cc2
|
|
(3.67-0.45j)
|
|
```
|
|
## 7.1 Строка символов
|
|
```py
|
|
>>> ss1='Это - строка символов'
|
|
>>> ss1; type(ss1)
|
|
'Это - строка символов'
|
|
<class 'str'>
|
|
>>> 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]
|
|
'омсаот '
|
|
```
|
|
Так как индекс 17 и -4 (4-й символ с конца строки) - одно и то же при 21-ом элементе, то получится то же самое, что и выше:
|
|
```py
|
|
>>> ss1[-4:3:-2]
|
|
'омсаот '
|
|
```
|
|
Стротка - неизменяемый объект
|
|
```py
|
|
>>> ss1[4]='='
|
|
Traceback (most recent call last):
|
|
File "<pyshell#114>", line 1, in <module>
|
|
ss1[4]='='
|
|
TypeError: 'str' object does not support item assignment
|
|
``` |