Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

16 KiB

Отчет по теме 2

Похил Анастасия, А-02-23

1. Настройка текущего каталога

import os
os.chdir('C://Users//Настя//Desktop//python-labs//TEMA2//')

2.Изучение простых объектов

f1=16;f2=3
f1,f2
(16, 3)
f1;f2
16
3
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'f1', 'f2', 'os']
  • Получение атрибутов и определение классовой принадлежности объекта 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']
type(f2)
<class 'int'>
  • Удаление созданных переменных
del f1,f2
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os']

3. Изучение правил именования объектов в Python.

Примеры правильных и неправильных имён:

gg = 1.6
hh1 = 'строка'
73sr=3
SyntaxError: invalid decimal literal
and=7
SyntaxError: invalid syntax

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']
keywords = keyword.kwlist

5.Встроенные функции

  • Cписок встроенных идентификаторов
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', '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']
  • Получение помощи по функциям и их применение
help(abs)
Help on built-in function abs in module builtins:

abs(x, /)
    Return the absolute value of the argument.

В дальнейшем получение помощи не будет вставлено в отчёт.

  • Функции abs и len
abs(-12)
12
len("Hello, World!")
13
list1=(12,14,63,24,32,52)
len(list1)
6
  • Функции min и max
max(12,14,63,24,32,52)
63
min(12,14,63,24,32,52)
12
max("Москва", "Санкт-Петербург", "Владивосток")
'Санкт-Петербург'
min("Москва", "Санкт-Петербург", "Владивосток")
'Владивосток'
  • Функции pow и round
pow(12, 2)
144
pow(25, -2)
0.0016
pow(5, 2, 7)
4
round(3.14)
3
round(3.14135413, 1)
3.1
round(123.45, -1)
120.0
  • Функция сортировки и суммы
sorted({12,-32,42,11,-2,7,-42,63})
[-42, -32, -2, 7, 11, 12, 42, 63]
sorted({12,-32,42,11,-2,7,-42,63}, reverse=True)
[63, 42, 12, 11, 7, -2, -32, -42]
sorted(["Москва","Санкт-Петербург","Сочи","Владивосток","Архангельск"],key=len)
['Сочи', 'Москва', 'Владивосток', 'Архангельск', 'Санкт-Петербург']
sorted(["Москва","Санкт-Петербург","Сочи","Владивосток","Архангельск"])
['Архангельск', 'Владивосток', 'Москва', 'Санкт-Петербург', 'Сочи']
sum([10,41,11,3,8])
73
sum([10,41,11,3,8],12)
85
sum(x for x in range(3, 12))
63
  • Функция zip
names = ["Анна", "Иван", "Мария"]
ages = [25, 30, 28]
cities = ["Москва", "Сочи", "Казань"]
zip1 = list(zip(names, ages, cities))
zip1
[('Анна', 25, 'Москва'), ('Иван', 30, 'Сочи'), ('Мария', 28, 'Казань')]
names.pop(1)
'Иван'
zip1
[('Анна', 25, 'Москва'), ('Мария', 30, 'Сочи')]

6.Влияние регистра

Gg1=45
Gg1
45
gg1
1.6

7.Простые базовые типы объекто

7.1 Логический тип

bb1=True; bb2=False
bb1;bb2
True
False
type(bb1)
<class 'bool'>

7.2 Другие простые типы

ii1=-1234567890
ff1=-8.9876e-12
dv1=0b1101010
type(dv1)
<class 'int'>
vsm1=0o52765
shest1=0x7109af6
cc1=2-3j
a=3.67; b=-0.45
cc2=complex(a,b)
cc2
(3.67-0.45j

7.3 Изучение строк

ss1='Это - строка символов'
ss1="Это - строка символов"
ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"
print(ss1a)
Это - " строка символов ", 
 	 выводимая на двух строках
ss1b= 'Меня зовут: \n <Похил А.А>'
print(ss1b)
Меня зовут: 
 <Похил А.А>
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]='='
Traceback (most recent call last):
  File "<pyshell#86>", line 1, in <module>
    ss1[4]='='
TypeError: 'str' object does not support item assignment
ss1=ss1[:4]+'='+ss1[5:]
print(ss1)
Это = строка символов

-Создание объектов с разными срезами

ss1b[0]
'М'
ss1b[7]
'в'
ss1b[-3]
'.'
ss1b[6:10]
'овут'
ss1b[12:]
'\n <Похил А.А>'
ss1b[:12]
'Меня зовут: '
ss1b[6:-2]
'овут: \n <Похил А.'
ss1b[2:16:2]
'н оу:\n<'
ss1b[16:2:-2]
'о<\n:уо '
ss1b[-2:4:-2]
'ААлхП  твз'
ss1b=ss1b[:10]+'-'+ss1b[12:]
print(ss1b)
Меня зовут-
 <Похил А.А>

7.4 Создание объектов и проверка их типов

a = 52
type(a)
<class 'int'>
b = 32.947
type(b)
<class 'float'>
c = 4 + 5j
type(c)
<class 'complex'>
d = 'hi'
type(d)
<class 'str'>
e = False
type(e)
<class 'bool'>
j = None
type(j)
<class 'NoneType'>

8. Сложные типы объектов

8.1 Списки

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
  • Методы объекта находятся в списке его атрибутов
dir()
['Gg1', '__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'a', 'b', 'bb1', 'bb2', 'builtins', 'c', 'cc1', 'cc2', 'd', 'dv1', 'e', 'ff1', 'gg1', 'hh1', 'i', 'ii1', 'j', 'keyword', 'keywords', 'list1', 'mnogo', 'os', 'shest1', 'spis', 'spis1', 'ss1', 'ss1a', 'ss1b', 'stup', 'vsm1']
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']
print(spis1)
[111, 'Список', (5-9j), 'New item']
spis1.append(ss1b)
print(spis1)
[111, 'Список', (5-9j), 'New item', 'Меня зовут-\n <Похил А.А>']
spis1.pop(1)
'Список'
print(spis1)
[111, (5-9j), 'New item', 'Меня зовут-\n <Похил А.А>']
  • Изучение методов insert и remove
spis1.insert(1,"ПОАС")
spis1.insert(3, 999)
spis1.pop(2)
(5-9j)
print(spis1)
[111, 'ПОАС', 999, 'New item', 'Меня зовут-\n <Похил А.А>']
spis1.remove(111)
print(spis1)
['ПОАС', 999, 'New item', 'Меня зовут-\n <Похил А.А>']
  • extend и clear
spis1.extend([100, 200])
spis2 =['xx', 'a', 'apple']
spis1.extend(spis2)
print(spis1)
['ПОАС', 999, 'New item', 'Меня зовут-\n <Похил А.А>', 100, 200, 'xx', 'a', 'apple']
spis2.clear()
print(spis2)   
[]
  • Метод sort
spis2 = [5, 2, 8, 1, 9]
spis2.sort()
print(spis2)
[1, 2, 5, 8, 9]
spis2.sort(reverse=True)
print(spis2)
[9, 8, 5, 2, 1]
spis2.clear()
spis2 = ['a', 'b', 'C', 'd']
spis2.sort()
print(spis2)
['C', 'a', 'b', 'd']
  • Методы reverse, count и copy
spis2.reverse()
print(spis2)
['d', 'b', 'a', 'C']
spis1.reverse()
print(spis1)
['apple', 'a', 'xx', 200, 100, 'Меня зовут-\n <Похил А.А>', 'New item', 999, 'ПОАС']
copy1 = spis1.copy()
copy2 = spis2.copy()
print(copy1, copy2)
['apple', 'a', 'xx', 200, 100, 'Меня зовут-\n <Похил А.А>', 'New item', 999, 'ПОАС'] ['d', 'b', 'a', 'C']
spis1.count('a')
1
spis2.count('a')
1
spis1.count(100)
1
spis2.count(100)
0
spis1.index('New item')
6
spis2.index('b')
1
spis1.index(100)
4
  • Вложенные списки и обращение к элементам в них
spis2=[spis1,[4,5,6,7]]
print(spis2)
[['apple', 'a', 'xx', 200, 100, 'Меня зовут-\n <Похил А.А>', 'New item', 999, 'ПОАС'], [4, 5, 6, 7]]
spis2[0][1]
'a'
spis2[0][1]=78
print(spis2)
[['apple', 78, 'xx', 200, 100, 'Меня зовут-\n <Похил А.А>', 'New item', 999, 'ПОАС'], [4, 5, 6, 7]]
print(spis1)
['apple', 78, 'xx', 200, 100, 'Меня зовут-\n <Похил А.А>', 'New item', 999, 'ПОАС']
#Когда мы изменяем spis2[0][1], мы фактически изменяем второй элемент оригинального списка spis1, так как spis2[0] и spis1 - это один и тот же объект в памяти.
my_list = [42, 3.14, "Hello", True, [1, 2, 3], (5-2j), spis1.copy()]
my_list[2][0] = 123
print(my_list)
[42, 123, 'Hello', True, [1, 2, 3], (5-2j), ['apple', 78, 'xx', 200, 100, 'Меня зовут-\n <Похил А.А>', 'New item', 999, 'ПОАС']]

#### 8.2 Объект-кортеж 
- Создание кортежа, переопределение и методы
```py
kort1=(222,'Kortezh',77+8j)
print(kort1)
(222, 'Kortezh', (77+8j))
kort1= kort1+(1,2)
print(kort1)
(222, 'Kortezh', (77+8j), 1, 2)
kort1= kort1+(ss1b,)
print(kort1)
(222, 'Kortezh', (77+8j), 1, 2, 'Меня зовут-\n <Похил А.А>')
kort2=kort1[:2]+kort1[3:]
print(kort2)
(222, 'Kortezh', 1, 2, 'Меня зовут-\n <Похил А.А>')
kort1.index(2)
4
kort1.count(222)
1
kort1[2]=90
Traceback (most recent call last):
  File "<pyshell#201>", line 1, in <module>
    kort1[2]=90
TypeError: 'tuple' object does not support item assignment
  • Создание кортежа №2
my_tuple = (42, "hello", [1, 2, 3], (4, 5, 6))
print(my_tuple)
(42, 'hello', [1, 2, 3], (4, 5, 6))
my_tuple[2]
[1, 2, 3]
my_tuple.index(42)
0

8.3 Объект-словарь

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'
  • Создание словарей с помощью функций dict и zip
dic4=dict([(1,['A','B','C']),(2,[4,5]),('Q','Prim'),('Stroka',ss1b)])
dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b]))
dic4
{1: ['A', 'B', 'C'], 2: [4, 5], 'Q': 'Prim', 'Stroka': 'Меня зовут-\n <Похил А.А>'}
dic5
{'A': 16, 'B': -3, 'C': 9, 'Stroka': 'Меня зовут-\n <Похил А.А>'}
  • Создание своего словаря
kortezh = (1, 'a', 3.14, True, 12, (5,6), 'end')
spisok = [10, 'b', 2.71, False, 'finish']
slovar = dict(zip(kortezh, spisok))
slovar
{1: False, 'a': 'b', 3.14: 2.71, 12: 'finish'}

Длина словаря равна 5, потому что функция zip() создает пары только до длины более короткой коллекции (списка из 5 элементов)

  • Пример словаря:
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 Объект-множество

mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}
mnoz1
{'датчик', 'двигатель', 'микропроцессор', 'линия связи'}
  • Некоторые операции с множеством
len(mnoz1)
4
'датчик' in mnoz1
True
mnoz1.add('реле')
mnoz1.remove('линия связи')
mnoz1
{'реле', 'датчик', 'двигатель', 'микропроцессор'}
  • Создание своего объекта s1 = {1, 2.5, "hello", True, (1, 2)} len(s1) 4 s1 {2.5, 1, 'hello', (1, 2)} 1 in s1 True s1.add('11') s1.remove(1) s1 {2.5, 'hello', (1, 2), '11'}