Сравнить коммиты

...

4 Коммитов
main ... main

Автор SHA1 Сообщение Дата
byvs 0044ff1e80 topic 2 is done
1 день назад
StepanishchevVR aba93a781b Загрузил файлы test.md
1 неделю назад
StepanishchevVR 5e4f8c6e82 Изменил(а) на 'TEMA1/report.md'
1 неделю назад
byvs 2b2ffe1470 first commit
1 неделю назад

@ -0,0 +1,5 @@
#Программа по Теме 1 Степанищев Виктор Романович
print('Hello')
h=input('Your name=')
import os
os.chdir(r"/home/byvs/MPEI/Programming Python/Stepanishchev/TEMA1/")

Двоичные данные
TEMA1/figure0.png

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 18 KiB

Двоичные данные
TEMA1/figure1.png

Двоичный файл не отображается.

После

Ширина:  |  Высота:  |  Размер: 14 KiB

@ -0,0 +1,96 @@
# Отчёт по теме 1
Степанищев Виктор, А-03-23
## 1 Знакомство с интерпретатором
Введение инструкций в окно интерпретатора
```py
>>>print('Hello')
Hello
>>>h=input('Your name=')
Your name=Viktor
>>>exit()
```
## 2 Знакомство с интерактивной оболочкой IDLE
Настройка текущего каталога
```py
import os
os.chdir(r"/home/byvs/MPEI/Programming Python/python-labs/TEMA1/")
```
Создание Pr0.py в рабочем каталоге и его запуск тремя способами: import Pr0, F5, 'Запустить модуль'
```py
#Программа по Теме 1 Степанищев Виктор Романович
print('Hello')
h=input('Your name=')
import os
os.chdir(r"/home/byvs/MPEI/Programming Python/Stepanishchev/TEMA1/")
```
Запуск prb1.py
```py
>>> import prb1
Как Вас зовут? Viktor
Привет, Viktor
```
В папке _pycache_ хранится двоичный скомпилированный код, который нужен для оптимизации загрузки и запуска программы
Раздел помощи help в главном меню IDLE предлагает следующие виды помощи: документацию по IDLE, доку по Python
и наглядную демонстрацию работы модуля Turtle
```py
>>>help(print)
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
>>>help(print), help(input)
Help on built-in function print in module builtins:
print(*args, sep=' ', end='\n', file=None, flush=False)
Prints the values to a stream, or to sys.stdout by default.
sep
string inserted between values, default a space.
end
string appended after the last value, default a newline.
file
a file-like object (stream); defaults to the current sys.stdout.
flush
whether to forcibly flush the stream.
Help on built-in function input in module builtins:
input(prompt='', /)
Read a string from standard input. The trailing newline is stripped.
The prompt string, if given, is printed to standard output without a
trailing newline before reading input.
If the user hits EOF (*nix: Ctrl-D, Windows: Ctrl-Z+Return), raise EOFError.
On *nix systems, readline is used if available.
(None, None)
```
Результат работы программы tdemo_chaos.py :
<image src="figure0.png">
Демонстрация работы модуля Turtle на примере clock из Turtle Demo в выпадающем меню help:
<image src="figure1.png">

@ -0,0 +1,492 @@
# Отчёт по теме 2
Выполнил Степанищев Виктор, А-03-23
# 1. Начало работы
Запуск IDLE, установление рабочего каталога
# 2. Изучение простых объектов
```py
>>f1=16; f2=3
>>f1,f2
(16, 3)
>>f1;f2
16
3
>>dir()
['__annotations__', '__builtins__', '__doc__', '__file__', '__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_count', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>type(f2)
<class 'int'>
>>del f1,f2
>>dir(f1)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
dir(f1)
NameError: name 'f1' is not defined
#Объектов не осталось после del
```
# 3. Изучение правил именования объектов
```py
>>gg1=1.6
>>hh1='Строка'
>>73sr=3
SyntaxError: invalid decimal literal
>>and=7
SyntaxError: invalid syntax
```
# 4. Просмотр ключевых слов в Python
```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']
>>list_keyword = keyword.kwlist
```
# 5. Просмотр встроенных идентификаторов
```py
>>import builtins
>>dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EncodingWarning', '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', 'WindowsError', 'ZeroDivisionError', '_', '__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']
```
Изучение функций **abs**, **len**, **max**, **min**, **pow**, **round**, **sorted**, **sum**, **zip**
1) abs - возвращает абсолютное значение передаваемого числа
```py
>>help(abs)
Help on built-in function abs in module builtins:
abs(x, /)
Return the absolute value of the argument.
>>abs(-4.5)
4.5
```
2) len - возвращает длину (количество элементов) объекта
```py
>>help(len)
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
>>len([1, 2, 3])
3
```
3) max - возвращает наибольший элемент в итерируемом объекте или из нескольких аргументов
```py
>>help(max)
Help on built-in function max in module builtins:
max(...)
max(iterable, *[, default=obj, key=func]) -> value
max(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its biggest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the largest argument.
>>max([1, 2, 3])
3
```
4) min - возвращает наименьший элемент в итерируемом объекте или из нескольких аргументов
```py
>>help(min)
Help on built-in function min in module builtins:
min(...)
min(iterable, *[, default=obj, key=func]) -> value
min(arg1, arg2, *args, *[, key=func]) -> value
With a single iterable argument, return its smallest item. The
default keyword-only argument specifies an object to return if
the provided iterable is empty.
With two or more arguments, return the smallest argument.
>>min([1, 2, 3])
1
```
5) pow - возвращает x в степени y, если указан z, возвращает результат по модулю z
```py
>>help(pow)
Help on built-in function pow in module builtins:
pow(base, exp, mod=None)
Equivalent to base**exp with 2 arguments or base**exp % mod with 3 arguments
Some types, such as ints, are able to use a more efficient algorithm when
invoked using the three argument form.
>>pow(2, 3)
8
>>pow(2, 3, 3)
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(14.0214, 2)
14.02
```
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.
>>sorted([3, 2, 1])
[1, 2, 3]
```
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([1, 2, 3])
6
```
9) zip - объединяет элементы из нескольких итерируемых объектов в кортежи
```py
>>help(zip)
Help on class zip in module builtins:
class zip(object)
| zip(*iterables, strict=False) --> Yield 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.
|
| If strict is true and one of the arguments is exhausted before the others,
| raise a ValueError.
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(...)
| Return state information for pickling.
|
| __setstate__(...)
| Set state information for unpickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs) from builtins.type
| Create and return a new object. See help(type) for accurate signature.
>>students = ['Viktor', 'Alexandr']
>>ages = [20, 20]
>>list(zip(students, ages))
[('Viktor', 20), ('Alexandr', 20)]
```
# 6. Малые и большие буквы различаются
```py
>>Gg1=45
>>gg1
1.6
>>Gg1
45
```
# 7. Изучение базовых типов объектов
## 7.1 Логический тип
```py
>>bb1=True; bb2=False
>>bb1;bb2
True
False
>>type(bb1)
<class 'bool'>
```
## 7.2 Другие простые типы
```py
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)
```
## 7.3 Строка символов
```py
ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"
print(ss1a)
```
```py
ss1b= 'Меня зовут: \n Степанищев В.Р.'
print(ss1b)
```
```py
mnogo="""Нетрудно заметить , что в результате операции
над числами разных типов получается число,
имеющее более сложный тип из тех, которые участвуют в операции."""
print(mnogo)
```
```py
>>ss1[17:3:-2]
'омсаот '
>>ss1[-4:3:-2]
'омсаот '
```
```py
>>ss1[4]='='
Traceback (most recent call last):
File "<pyshell#95>", line 1, in <module>
ss1[4]='='
TypeError: 'str' object does not support item assignment
>>ss1=ss1[:4]+'='+ss1[5:]
>>ss1
'Это = строка символов'
```
```py
>>ss1b
'Меня зовут:
Степанищев В.Р.'
>>ss1b[:3]
'Мен'
>>ss1b[::-1]
'.Р.В вещинапетС
:тувоз янеМ'
```
Самостоятельно придумал значения и создал объекты разных типов
```py
my_int = 42
my_float = 3.14159
my_complex = 2 + 3j
my_string = "Hello, Python!"
my_list = [1, 2, "три", 4.0]
my_tuple = (10, 20, "тридцать")
my_set = {1, 2, 3, 2, 1}
my_dict = {"имя": "Виктор", "возраст": 20, "город": "Москва"}
my_bool = True
my_bytes = b"hello"
my_range = range(5)
```
# 8. Типы объектов: списки, кортежи, словари, множества
```py
>>spis1=[111,'Spisok',5-9j]
>>stup=[0,0,1,1,1,1,1,1,1]
>>spis1[-1]
(5-9j)
```
```py
>>stup[-8::2]
[0, 1, 1, 1]
>>stup
[0, 0, 1, 1, 1, 1, 1, 1, 1]
```
*Сколько элементов вошло в этот новый список и какие индексы они имели в исходном списке?*
Ответ: количество эл-ов в новом списке 4, индексы в исходном списке 1, 3, 5, 7
```py
>>spis1[1]='Список'
>>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.append('New item')
>>spis1
[111, 'Список', (5-9j), 'New item']
>>spis1.append(ss1b)
>>spis1
[111, 'Список', (5-9j), 'New item', 'Меня зовут: \n Степанищев В.Р.']
>>spis1.pop(1)
'Список'
>>spis1
[111, (5-9j), 'New item', 'Меня зовут: \n Степанищев В.Р.']
```
*Использование insert, remove, extend, clear, sort, reverse, copy, count, index*
```py
>>spis1.insert(1, 'string')
>>spis1
[111, 'string', (5-9j), 'New item', 'Меня зовут: \n Степанищев В.Р.']
>>spis1.remove(111)
>>spis1
['string', (5-9j), 'New item', 'Меня зовут: \n Степанищев В.Р.']
>>new_list = [1, 2, 3]
>>spis1.extend(new_list)
>>spis1
['string', (5-9j), 'New item', 'Меня зовут: \n Степанищев В.Р.', 1, 2, 3]
>>new_list.clear()
>>new_list
[]
>>new_list = [3, 1, 2]
>>new_list.sort()
>>new_list
[1, 2, 3]
>>new_list.reverse()
>>new_list
[3, 2, 1]
>>new_list2 = new_list.copy()
>>new_list2
[1, 2, 3]
>>new_list = [1, 2, 2, 2, 3, 3]
>>new_list.count(2)
3
>>new_list = ['one', 'two', 'three']
>>new_list.index('three')
2
```
```py
>>spis1
['string', (5-9j), 'New item', 'Меня зовут: \n Степанищев В.Р.', 1, 2, 3]
>>spis2=[spis1,[4,5,6,7]]
>>spis2[0][1]
(5-9j)
>>spis2[0][1]=78
>>spis2
[['string', 78, 'New item', 'Меня зовут: \n Степанищев В.Р.', 1, 2, 3], [4, 5, 6, 7]]
>>spis1
['string', 78, 'New item', 'Меня зовут: \n Степанищев В.Р.', 1, 2, 3]
```
*Почему spis1 отличается от изначально заданного?*
Ответ: spis1 претерпел изменения потому что spis2[0] не является копией spis1, а представляет
собой ссылку на тот же самый объект в памяти
Придумал и создал свой объект-список, элементами которого объекты разных типов:
число, строка, логическое значение, список.
```py
my_list = [12, 'str', True, [1, 2, 3]]
my_list
[12, 'str', True, [1, 2, 3]]
```
## 8.2 Кортежи
```py
>>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:]
>>kort2
(222, 'Kortezh', 1, 2, 'Меня зовут: \n Степанищев В.Р.')
>>kort1.index(2)
4
>>kort1.count(222)
1
>>kort1[2]=90
Traceback (most recent call last):
File "<pyshell#264>", line 1, in <module>
kort1[2]=90
TypeError: 'tuple' object does not support item assignment
>>my_kort = (12, 'str', [1, 2, 3], (222, 'str'))
>>my_kort
(12, 'str', [1, 2, 3], (222, 'str'))
```
## 8.3 Словари
```py
>>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)])
>>dic4
{1: ['A', 'B', 'C'], 2: [4, 5], 'Q': 'Prim', 'Stroka': 'Меня зовут: \n Степанищев В.Р.'}
>>dic5=dict(zip(['A','B','C','Stroka'],[16,-3,9,ss1b]))
>>dic5
{'A': 16, 'B': -3, 'C': 9, 'Stroka': 'Меня зовут: \n Степанищев В.Р.'}
```
*Создал объект-кортеж с 7 элементами и объект-список с 5 элементами, также из них словарь с помощью функций dict и zip*
```py
>>t = ("a", "b", "c", "d", "e", "f", "g")
>>l = [1, 2, 3, 4, 5]
>>d = dict(zip(t, l))
>>d
{'a': 1, 'b': 2, 'c': 3, 'd': 4, 'e': 5}
```
Элементов в получившимся словаре - 5, т.к. zip() работает до конца самого короткого объекта (в нашем случае этот объект l)
```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={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}
>>mnoz1
{'датчик', 'микропроцессор', 'двигатель', 'линия связи'}
>>len(mnoz1)
4
>>'датчик' in mnoz1
True
>>mnoz1.add('реле')
>>mnoz1.remove('линия связи')
```
```py
>>s = {1, "hello", True, 3.14, (2, 5)}
>>s.add("Python")
>>s
{1, 3.14, 'hello', (2, 5), 'Python'}
>>s.remove(3.14)
>>s
{1, 'hello', (2, 5), 'Python'}
```

@ -0,0 +1,24 @@
# Общее контрольное задание по теме 2
Степанищев Виктор, А-03-23
## Задание
Реализовать, записать в текстовый файл и проанализировать результаты последовательности инструкции
## Решение
```py
import keyword
familia = 'Stepanishchev'
first_word = familia[0]
sp_kw = keyword.kwlist
print('nonlocal' in sp_kw)
sp_kw.remove('nonlocal')
print('nonlocal' in sp_kw)
kort_nam = ('Viktor', 'Alexander', 'Ilya', 'Nikita')
print(type(kort_nam))
kort_nam += ('Emil', 'Zahar')
print(kort_nam)
print(kort_nam.count('Дима'))
dict_bas = {'Список':[1,2,4], 'Множество':{1,2,3,4},'Словарь':{'key':'value'}}
print(dict_bas)
```

@ -0,0 +1,11 @@
# Общее контрольное задание по теме 1
Степанищев Виктор, А-03-23
## Вопрос
Что означает название интерактивной оболочки IDLE?
## Ответ
IDLE - Integrated Development and Learning Environment (интегрированная среда для разработки и обучения на ЯП python)
Загрузка…
Отмена
Сохранить