17 KiB
Отчет по теме 2
Ефремов Станислав, А-02-23
1. Запуск.
1.1 Запуск оболочки IDLE и установка рабочего каталога.
import os
os.chdir('C:\Program Files (x86)\учёха 3 курс\pythonsky\python-labs\TEMA2')
2. Изучение простых объектов.
2.1 Операции присваивания
f1=16; f2=3
f1,f2
(16, 3)
f1;f2
16
3
2.2 Функционал команд dir(), type() и del:
Был получен список атрибутов объекта f1:
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:
type(f2)
<class 'int'>
Команда del отвечает за удаление объекта или его части из ОП.
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. Правила именования и сохранение списка под именем:
Были введены некоторые предложенные команды, две из которых не соответствовали правилам именования:
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']
В данном случае полученному списку было присвоено следующее имя:
ara = keyword.kwlist
ara
['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 Вывод списка встроенных идентификаторов:
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 Изучение назначения функций:
5.2.1 Функция ABS:
5.2.2 Функция len:
5.2.3 Функция max
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
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
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
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
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
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
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. Проверка влияния больших и маленьких букв в имени переменных:
Gg1=45
gg1
1.6
Gg1
45
7. Изучение базовых типов объектов:
int — целые числа (положительные, отрицательные или нуль). float — числа с плавающей точкой (дробные числа). complex — комплексные числа (имеют действительную и мнимую части). str — строковый тип данных для хранения текстовой информации. Строка может содержать буквы, цифры, пробелы, символы. bool в Python — это логический тип, принимать только два значения: True и False.
7.1 Логический тип:
bb1 = True
bb2 = False
bb1;bb2
True
False
type(bb1)
<class 'bool'>
7.2 Иные простые типы:
ii1=-1234567890
type(ii1)
<class 'int'>
ff1=-8.9876e-12
type(ff1)
<class 'float'>
dv1=0b1101010
type(dv1)
<class 'int'>
Как можем заметить - двоичное число 0b1101010 в Python сохраняется в объекте класса 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'>
7.3 Строка символом:
Строки выделяются как и апострофами, так и двойными кавычками, продемонстрируем:
ss1='Это - строка символов'
ss1="Это - строка символов"
Экранированные последовательности:
ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"
print(ss1a)
Создадим строку по шаблону:
ss1b= 'Меня зовут: \n Ефремов С.И.'
print(ss1b)
Меня зовут:
Ефремов С.И.
Создадим строку со значением объекта при помощи тройных кавычек:
mnogo="""Нетрудно заметить , что в результате операции
над числами разных типов получается число,
имеющее более сложный тип из тех, которые участвуют в операции."""
print(mnogo)
Нетрудно заметить , что в результате операции
над числами разных типов получается число,
имеющее более сложный тип из тех, которые участвуют в операции.
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' здесь отвечает за шаг.
ss1[17:3:-2]
'омсаот '
Здесь, подобно примеру выше, мы перечислили элементы с индексами от 3 до 17, но в обратном порядке (с положительным шагом перечисление элементов в обратную сторону работать не будет).
ss1[-4:3:-2]
'омсаот '
Изменив '17' на '-4' мы получим тот же результат, ведь два этих индекса соответствуют одному и тому же элементу строки.
ss1=ss1[:4]+'='+ss1[5:]
ss1
'Это = строка символов'
Таким образом, мы переопределили элемент под индексом 4.
ss1b1 = ss1b[:3]; print(ss1b1)
Мен
ss1b2 = ss1b[:10]+' - \n'+ss1bpetr
print(ss1b2)
Меня зовут -
Петр Мамонов
8. Списки, кортежи, словари и множества.
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 Работа со списками.
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]
Ввод можно производить в разных строках, пока не будет введена квадратная скобка.
spis1[-1]
(5-9j)
stup[-8::2]
[0, 1, 1, 1]
'-8' - есть элемент под индексом 1 в исходном списке, между :: ничего нет, значит срез произойдёт до самого последнего элемента, а '2' - есть шаг пересчёта элементов.
spis1[1]='Список'
spis1
[111, 'Список', (5-9j)]
len(spis1)
3
spis1.append('компиш')
spis1
[111, 'Список', (5-9j), 'компиш']
spis1.append(ss1b)
spis1
[111, 'Spisok', (5-9j), 'компиш', 'Меня зовут: \n Ефремов С.И.']
spis1.pop(1)
'Spisok'
spis1
[111, (5-9j), 'компиш', 'Меня зовут: \n Ефремов С.И.']
С помощью '.append' можно добавить какой-либо элемент в список, а '.pop' - удалить.
spis1.insert(1, 'пицца') вставит второй аргумент под номер индекса элемента.
spis1
[111, 'пицца', (5-9j), 'компиш', 'Меня зовут: \n Ефремов С.И.']
spis1.remove('пицца') - удалит тот элемент, который полностью соответствует указанному в команде аргументу.
spis1
[111, (5-9j), 'компиш', 'Меня зовут: \n Ефремов С.И.']
spis1.extend('5-9') - добавит каждый элемент аргумента в конце списка.
spis1
[111, (5-9j), 'компиш', 'Меня зовут: \n Ефремов С.И.', 'к', 'о', 'м', 'п', 'и', 'ш', '5', '-', '9']
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
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] - был видоизменен, ведь является элементом другого списка, к которому мы обратились и изменили соответственно.