SneguraDS 1 месяц назад
Родитель fcc9cafd13
Сommit 3d18360860

@ -0,0 +1,82 @@
Python 3.13.7 (tags/v3.13.7:bcee1c3, Aug 14 2025, 14:15:11) [MSC v.1944 64 bit (AMD64)] on win32
Enter "help" below or click "Help" above for more information.
import os
os.chdir(r'C:\Users\User-PC\python-labs\TEMA1')
====================== RESTART: C:/Users/User-PC/python-labs/TEMA1/Pr0.py =====================
Hello
Your name=Dana
import Pr0
Hello
Your name=Dana
import prb1
Как Вас зовут? Dana
Привет, Dana
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)
>>>
===================== RESTART: C:\Users\User-PC\python-labs\TEMA1\prb1.py =====================
Как Вас зовут? Dana
Привет, Dana
>>> import tdemo_chaos.py
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
import tdemo_chaos.py
ModuleNotFoundError: No module named 'tdemo_chaos.py'; 'tdemo_chaos' is not a package
>>> import tdemo_chaos.py
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
import tdemo_chaos.py
ModuleNotFoundError: No module named 'tdemo_chaos.py'; 'tdemo_chaos' is not a package
>>> os
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
os
NameError: name 'os' is not defined. Did you forget to import 'os'?
>>> import os
>>> os.getcwd()
'C:\\Users\\User-PC\\python-labs\\TEMA1'
os.listdir()
['Pr0.py', 'prb1.py', 'protocol.py', 'report.md', 'tdemo_chaos.py', '__pycache__', '{1C1A6921-E5A2-429D-A13F-0ED490D361C8}.png', '{C055547F-8056-45D3-A1E5-C93FC85A9E16}.png']
import tdemo_chaos

@ -0,0 +1,7 @@
#Программа по Теме 1 <Снегура Даны Сергеевны>
print('Hello')
h=input('Your name=')
import os
os.chdir('C:\\Users\\User-PC\\python-labs\\TEMA1')

@ -0,0 +1,57 @@
#Протокол по теме 1 <Снегура Дана Сергеевна>
Hello
Your name=Dana
import Pr0
Hello
Your name=Dana
import prb1
Как Вас зовут? Dana
Привет, Dana
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)
===================== RESTART: C:\Users\User-PC\python-labs\TEMA1\prb1.py =====================
Как Вас зовут? Dana
Привет, Dana

@ -1 +1,103 @@
1
# Тема 1. Знакомство с интерпретатором и интерактивной оболочкой IDLE
## 1. Работала на своем ноутбуке, поэтому данный пункт не требовался к выполнению
## 2. Запустила на выполнение команду-интерпретатор
## 3. Открылось диалоговое окно интерпретатора, изучила его, ввела инструкцию
```py
>>> print('Hello')
Hello
##Убедилась, что интерпретатор выполнил введеную инструкцию и вывел Hello
```
## 4. Ввела еще одну инструкцию
```py
>>> h=input('Your name=')
##Увидела, что вывелось "Your name=" и ввела свое имя
Your name=Dana
```
## 5. Зевершила работу интерпретатора вводом инструкции
```py
>>> exit()
```
## 6. Запустила интерактивную графическую оболочку IDLE
## 7. Изучила устройство главного командного окна среды
## 8. В командном окне ввела инструкции настройки рабочего католога среды
```py
import os
os.chdir('C:\\Users\\User-PC\\python-labs\\TEMA1')
```
## 9. Изучила предлоожения главного и выпадающих меню. Установила в среде: шрифт типа Arial CYR, размер 11, размер начального окна - высота 50 символов, ширина 100 символов
## 10. Создала новый файл и ввела комментарии. Сохранила файл под именем Pr0.py в рабочем каталоге. Запустила на выполнение разными способами
```py
#Программа по Теме 1 <Снегура Даны Сергеевны>
print('Hello')
h=input('Your name=')
import os
os.chdir('C:\\Users\\User-PC\\python-labs\\TEMA1')
##Получила такой результат,ввела свое имя
Hello
Your name=Dana
```
## 11. Запустила на выполнение файл prb1.py, далее ввела свое имя и посмотрела на результат
```py
import prb1
Как Вас зовут?
Dana
Привет, Dana
```
## 12. Попробовала открыть файл Pr0.cpython-34.pyc в текстовом редакторе из каталога __pycache__ и получила ошибку, что файл не может быть отображен в текстовом редакторе, поскольку он либо двоичный, либо использует неподдерживаемую кодировку. Компиляция производится для того, чтобы компьютер мог понять и выполнить инструкции написанные программистом
![alt text]({C055547F-8056-45D3-A1E5-C93FC85A9E16}.png)
## 13. Создала новое окно, в первой строчке ввела #Протокол по Теме 1 <Снегура Даны Сергеевны>, внесла в него копию всех строк из командной строки. Сохранила этот файл и назвала protocol.py
## 14. Изучила раздел помощи help
```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)
## Попробовала повторить ранее введеные инструкции через Enter, через F1 получила ошибку 1155, что указанному файлу не сопосталено ни одно приложение для выполнения операции ![alt text]({1C1A6921-E5A2-429D-A13F-0ED490D361C8}.png)
```
## 15. Последовательно активировала необходимые окна. Запустила prb1.py на выполнение, получила вопрос об имени, ввела свое, получила приветствие. Выбрала предложения «Помощь (Help)» и «Демонстрации (Turtle Demo)». В появившемся новом окне в меню выбрала предложение «Примеры (Examples)» и из появляющегося списка примеров – «Часы (Clock)». Нажала кнопку «Запуск (Start)» в нижней части окна. Получила текст программы в левой части окна и её результат – в правой.
```py
Как Вас зовут? Dana
Привет, Dana
##Используя функцию import запустила программу на выполнение.
import tdemo_chaos
```
![alt text]({AA34A4E5-8338-47D4-887D-EA6FD3AADA6A}.png)
## 16. Завершила работу со средой

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

После

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

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

После

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

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

После

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

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

После

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

@ -0,0 +1,31 @@
## Общее контрольное задание
```py
familia='Snegura' #создание переменной с моей фамилией
first_letter = familia[0] #cоздание переменной со значением, совпадающим с первой буквой из familia
first_letter
'S'
import keyword
sp_kw = keyword.kwlist.copy() #cоздание переменной с именем sp_kw со значением – списком всей ключевых слов языка Python.
if 'nonlocal' in sp_kw:
sp_kw.remove('nonlocal') #удаление из списка sp_kw значение 'nonlocal'
sp_kw #убедимся, что его нет
['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', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
kort_nam = ('Дана', 'Женя', 'Стас', 'Дима') #создание кортежа kort_nam с мои именем и именами одногруппников
kort_nam
('Дана', 'Женя', 'Стас', 'Дима')
assert isinstance(kort_nam, tuple) #убедимся, что тип переменной – это tuple, если ничего не вывелось, то это нужный тип
kort_nam = kort_nam + ('Настя', 'Лена') #добавим в kort_nam имена еще двух студентов
kort_nam
('Дана', 'Женя', 'Стас', 'Дима', 'Настя', 'Лена')
dima_count = kort_nam.count('Дима') #опредилим сколько раз встречается 'Дима' в кортеже
dima_count
1
dict_bas = {
'строка': familia,
'символ': first_letter,
'список': sp_kw,
'кортеж': kort_nam
} #создадим словарь dict_bas, в котором ключами являются русские названия типов перемен-ных, использованных в предыдущих операторах, а значениями – ранее созданные перемен-ные, соответствующие этим типам
dict_bas
{'строка': 'Snegura', 'символ': 'S', 'список': ['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', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'], 'кортеж': ('Дана', 'Женя', 'Стас', 'Дима', 'Настя', 'Лена')}
```

@ -0,0 +1,56 @@
Python 3.13.7 (tags/v3.13.7:bcee1c3, Aug 14 2025, 14:15:11) [MSC v.1944 64 bit (AMD64)] on win32
Enter "help" below or click "Help" above for more information.
>>> familia='Snegura'
>>> S='S'
>>> ldel S
SyntaxError: invalid syntax
>>> Del S
SyntaxError: invalid syntax
>>> del S
>>> first_letter = familia[0]
>>> first_letter
'S'
>>> sp_kw = keyword.kwlist.copy()
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
sp_kw = keyword.kwlist.copy()
NameError: name 'keyword' is not defined. Did you forget to import 'keyword'?
>>> import keyword
>>> sp_kw = keyword.kwlist.copy()
>>> if 'nonlocal' in sp_kw:
... sp_kw.remove('nonlocal')
...
...
>>> sp_kw
['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', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
kort_nam = ('Snegura', 'Turovets', 'Yefremov', "Khatyukhin')
SyntaxError: unterminated string literal (detected at line 1)
kort_nam = ('Snegura', 'Turovets', 'Yefremov', 'Khatyukhin')
kort_nam
('Snegura', 'Turovets', 'Yefremov', 'Khatyukhin')
assert isinstance(kort_nam, tuple)
del kort_nam
kort_nam = ('Дана', 'Женя', 'Стас', 'Дима')
kort_nam
('Дана', 'Женя', 'Стас', 'Дима')
assert isinstance(kort_nam, tuple)
kort_nam = kort_nam + ('Настя', 'Лена')
kort_nam
('Дана', 'Женя', 'Стас', 'Дима', 'Настя', 'Лена')
dima_count = kort_nam.count('Dima')
dima_count
0
dima_count = kort_nam.count('Дима')
dima_count
1
dict_bas = {
'строка': familia,
'символ': first_letter,
'список': sp_kw,
'кортеж': kort_nam
}
dict_bas
{'строка': 'Snegura', 'символ': 'S', 'список': ['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', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield'], 'кортеж': ('Дана', 'Женя', 'Стас', 'Дима', 'Настя', 'Лена')}

@ -0,0 +1,573 @@
### Протокол по Теме 2 <Снегура Даны Сергеевны>
## 1. Запустила IDLE, создала протокол
## 2. Присвоила значения объектам f1; f2. Попробовала унать значения объектов перечислением в строке через "," и ";". Использовала функцию dir для того, чтобы узнать какие объекты на данный момент существуют в среде Python. Далее получила атрибуты объекта f1 и определила классовую принадлежность f2 - <class 'int'>. Удалила из оперативной памяти f1; f2 и проверила остались ли эти объекты. Получила ответ, что эти объекты отсутствуют.
```py
f1=16; f2=3
f1,f2
(16, 3)
f1;f2
16
3
dir()
['__annotations__', '__builtins__', '__doc__', '__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__', '__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__']
```
## 3. Изучила правила именования объектов, попробовала корректно задать значение в виде вещественного числа и значение в виде симвльной строки. Некорректно начала название с цифры и ввела название, совпадающее с ключевым словом.
```py
gg1=1.6
hh1='Строка'
73sr=3
SyntaxError: invalid decimal literal
and=7
SyntaxError: invalid syntax
gg1;hh1
1.6
'Строка'
```
## 4. Вывела список ключевых слов и сохранила его в переменной kluchevye_slova
```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']
kluchevye_slova= keyword.kwlist
type(kluchevye_slova)
<class 'list'>
```
## 5. Вывела список встроенных идентификаторов, изучила назначение таких функций как abs, len, max, min, pow, round, sorted, sum, zip и применила их
```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']
```
```py
##Получила модуль от "-5"
help(abs)
Help on built-in function abs in module builtins:
abs(x, /)
Return the absolute value of the argument.
abs(-5)
5
```
```py
##Получила длину строки 'Длина строки'
help(len)
Help on built-in function len in module builtins:
len(obj, /)
Return the number of items in a container.
len('Длина строки')
12
```
```py
##Получила максимальное число из (2,3,4)
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 positional arguments, return the largest argument.
max(2,3,4)
4
```
```py
##Получила минимальное число из (2,3,4)
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 positional arguments, return the smallest argument.
min(2,3,4)
2
```
```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
```
```py
##Получила число 1.2345 округленное до 3 знаков после запятой и число 1.2346 округленное до 3 знаков после запятой
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.2345, 3)
1.234
round(1.2346, 3)
1.235
```
```py
##Получила отсортированный a по возрастанию и убыванию
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.
a=(5,3,4,2,1,7)
sorted(a)
[1, 2, 3, 4, 5, 7]
sorted(a, reverse=True)
[7, 5, 4, 3, 2, 1]
```
```py
##Получила сумму элементов a
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(a)
22
```
```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
| shortest argument is exhausted.
|
| If strict is true and one of the arguments is exhausted before the others,
| raise a ValueError.
|
| >>> list(zip('abcdefg', range(3), range(4)))
| [('a', 0, 0), ('b', 1, 1), ('c', 2, 2)]
|
| Methods defined here:
|
| __getattribute__(self, name, /)
| Return getattr(self, name).
|
| __iter__(self, /)
| Implement iter(self).
|
| __next__(self, /)
| Implement next(self).
|
| __reduce__(self, /)
| Return state information for pickling.
|
| __setstate__(self, object, /)
| Set state information for unpickling.
|
| ----------------------------------------------------------------------
| Static methods defined here:
|
| __new__(*args, **kwargs)
| Create and return a new object. See help(type) for accurate signature.
name=["Dana", "Dan", "Da", "D"]; num=[1,2,3,4]
for name, num in zip(name, num): print(f"{name} - {num}")
Dana - 1
Dan - 2
Da - 3
D - 4
```
## 6. Убедилась, что питон чувствителен к регистру
```py
Gg1=45
gg1
1.6
Gg1
45
```
## 7. Изучила базовые типы объектов : логический (bool), целый (int), вещественный (float), комплексный (complex), строка символов (str)
## 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'>
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(a)
<class 'float'>
type(b)
<class 'float'>
type(cc2)
<class 'complex'>
```
## 7.3. Строковый тип
```py
ss1='Это - строка символов'
ss1="Это - строка символов"
ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"
print(ss1a)
Это - " строка символов ",
выводимая на двух строках
ss1b= 'Меня зовут: \n Снегура Д.С.'
print(ss1b)
Меня зовут:
Снегура Д.С.
mnogo="""Нетрудно заметить , что в результате операции
над числами разных типов получается число,
имеющее более сложный тип из тех, которые участвуют в операции."""
print(mnogo)
Нетрудно заметить , что в результате операции
над числами разных типов получается число,
имеющее более сложный тип из тех, которые участвуют в операции.
ss1
'Это - строка символов'
ss1[0]
'Э'
ss1[8]
'р'
ss1[-2]
'о'
ss1[6:9] #с 6 по 8
'стр'
ss1[13:] #с 13
'символов'
ss1[:13] #с 1 по 12
'Это - строка '
ss1[5:-8] #с 5 до 8 с конца
' строка '
ss1[3:17:2] #с 3 по 16 с шагом 2
' тоасм'
ss1[17:3:-2] #с 17 по 2 с шагом 2 в обратном направлении
'омсаот '
ss1[-4:3:-2] #с 4 с конца по 2 с шагом 2 в обратном направлении
'омсаот '
ss1[4]='='
Traceback (most recent call last):
File "<pyshell#105>", line 1, in <module>
ss1[4]='='
TypeError: 'str' object does not support item assignment
ss1=ss1[:4]+'='+ss1[5:]
ss1
'Это = строка символов'
ss1b
'Меня зовут: \n Снегура Д.С.'
print(ss1b)
Меня зовут:
Снегура Д.С.
print(ss1b[5])
з
print(ss1b[11])
print(ss1b[8:15])
ут:
С
print(ss1b[8:-1])
ут:
Снегура Д.С
print(ss1b[8:-4:2])
у:
Сеуа
```
## 8. Работа со списками, кортежами, словарями, множествами
## 8.1. Работа со списками.
```py
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]
spis
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
spis1
[111, 'Spisok', (5-9j)]
stup
[0, 0, 1, 1, 1, 1, 1, 1, 1]
spis1[-1]
(5-9j)
stup[-8::2]
[0, 1, 1, 1] #вошло 4 элемента с 8 с конца до конца с шагом 2, в исходном списке они имели индексы 1, 3, 5, 7
spis[-8::2]
[3, 5, 7, 9]
spis
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
spis[-8::-2]
[3, 1]
spis1[1]='Список'
spis1
[111, 'Список', (5-9j)]
len(spis1)
3
##методы объекта
dir(spis1)
['__add__', '__class__', '__class_getitem__', '__contains__', '__delattr__', '__delitem__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getstate__', '__gt__', '__hash__', '__iadd__', '__imul__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__reversed__', '__rmul__', '__setattr__', '__setitem__', '__sizeof__', '__str__', '__subclasshook__', 'append', 'clear', 'copy', 'count', 'extend', 'index', 'insert', 'pop', 'remove', 'reverse', 'sort']
##описание метода
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+['New item']
[111, 'Список', (5-9j), 'New item', 'New item']
spis1
[111, 'Список', (5-9j), 'New item']
spis1.append(ss1b)
spis1
[111, 'Список', (5-9j), 'New item', 'Меня зовут: \n Снегура Д.С.']
##удаление элемента с индексом 1
spis1.pop(1)
'Список'
spis1
[111, (5-9j), 'New item', 'Меня зовут: \n Снегура Д.С.']
##добавим на место индекса 2 элемент 'A'
spis1.insert(2, 'A')
spis1
[111, (5-9j), 'A', 'New item', 'Меня зовут: \n Снегура Д.С.']
##удалим элемент 'A'
spis1.remove('A')
spis1
[111, (5-9j), 'New item', 'Меня зовут: \n Снегура Д.С.']
##добавим список spis к spis1
spis1.extend(spis)
spis1
[111, (5-9j), 'New item', 'Меня зовут: \n Снегура Д.С.', 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
##очистим список
spis1.clear()
spis1
[]
spis3=[1,3,2]
##отсортируем список
spis3.sort()
spis3
[1, 2, 3]
##развернем список
spis3.reverse()
spis3
[3, 2, 1]
##создадим копию
spis4=spis3.copy()
spis4
[3, 2, 1]
##количество символов двоек
spis4.count(2)
1
##элемент с индексом
spis4.index(2)
1
spis1
['a', 'aa', 'aaa']
spis2=[spis1,[4,5,6,7]]
spis2
[['a', 'aa', 'aaa'], [4, 5, 6, 7]]
##обращение к элементу списка spis1
spis2[0][1]
'aa'
##замена элемента на 78
spis2[0][1]=78
spis2
[['a', 78, 'aaa'], [4, 5, 6, 7]]
spis1
['a', 78, 'aaa']
spis4=[1, 'A', True, [spis1]]
spis4
[1, 'A', True, [['a', 78, 'aaa']]]
```
## 8.2. Работа с кортежем
```py
kort1=(222,'Kortezh',77+8j)
kort1
(222, 'Kortezh', (77+8j))
kort1= kort1+(1,2)
kort1
(222, 'Kortezh', (77+8j), 1, 2)
ss1b= 'Меня зовут: \n Снегура Д. С.'
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#13>", line 1, in <module>
kort1[2]=90
TypeError: 'tuple' object does not support item assignment
kort3=(2,'Stroka', [1,2])+kort1
kort3
(2, 'Stroka', [1, 2], 222, 'Kortezh', (77+8j), 1, 2, 'Меня зовут: \n Снегура Д. С.')
```
## 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'}
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'
##создадим более сложный словарь из списка с элементами-кортежами
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 элементами. Создадим из них словарь. Получим 5 элементов, по количеству элементов меньшего объекта
tuple_obj = (1, 2, 3, 4, 5, 6, 7)
list_obj = ['a', 'b', 'c', 'd', 'e']
result_dict = dict(zip(tuple_obj, list_obj))
result_dict
{1: 'a', 2: 'b', 3: 'c', 4: 'd', 5: 'e'}
##создадим словарь с описанием состава студентов, обучающихся на АВТИ
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
{'двигатель', 'реле', 'датчик', 'микропроцессор', 'линия связи'}
#удаление элемента
mnoz1.remove('линия связи')
mnoz1
{'двигатель', 'реле', 'датчик', 'микропроцессор'}
```
```py
x={1,'строка1',2,'строка2'}
x
{1, 2, 'строка2', 'строка1'}
len(x)
4
x.add(3)
x
{1, 2, 3, 'строка2', 'строка1'}
x.remove(1)
x
{2, 3, 'строка2', 'строка1'}
```
Загрузка…
Отмена
Сохранить