Сравнить коммиты
14 Коммитов
Автор | SHA1 | Дата |
---|---|---|
![]() |
c9fbe87501 | 1 неделю назад |
![]() |
21374ae0c8 | 1 неделю назад |
|
937634dba1 | 1 неделю назад |
![]() |
e0cb7d48e1 | 1 неделю назад |
![]() |
2133c6037e | 1 неделю назад |
![]() |
9e0f14c49b | 1 неделю назад |
![]() |
bae1f50817 | 1 неделю назад |
![]() |
1a93a3560b | 1 неделю назад |
![]() |
e047de5b42 | 1 неделю назад |
![]() |
4f9d91440e | 1 неделю назад |
![]() |
8c3c68e028 | 1 неделю назад |
![]() |
e1eb93a01f | 1 неделю назад |
![]() |
056d7d0c95 | 1 неделю назад |
![]() |
6f25b2d850 | 1 неделю назад |
@ -0,0 +1,5 @@
|
||||
#Программа по Теме 1 <Корнеев Максим Александрович>
|
||||
print('Hello')
|
||||
h=input('Your name=')
|
||||
import os
|
||||
os.chdir('C:\\Users\\u111-04\\Desktop\\python-labs\\TEMA1')
|
После Ширина: | Высота: | Размер: 2.4 KiB |
После Ширина: | Высота: | Размер: 29 KiB |
После Ширина: | Высота: | Размер: 15 KiB |
После Ширина: | Высота: | Размер: 8.5 KiB |
После Ширина: | Высота: | Размер: 47 KiB |
После Ширина: | Высота: | Размер: 45 KiB |
@ -0,0 +1,108 @@
|
||||
# Отчет по теме 1
|
||||
|
||||
Корнеев Максим, А-01-23
|
||||
|
||||
## 1 Изучение среды IDLE
|
||||
|
||||
## 1.1 Изучение программы-интерпретатора «Python 3.4 (command line)»
|
||||
|
||||
```py
|
||||
>>> print('Hello')
|
||||
'Hello'
|
||||
>>> h=input('Your name=')
|
||||
'Your name=Maxim'
|
||||
>>> exit()
|
||||
```
|
||||
|
||||
## 1.2 Настройка текущего каталога
|
||||
|
||||
```py
|
||||
>>> import os
|
||||
>>> os.chdir('C:\\Users\\u111-04\\Desktop\\python-labs\\TEMA1')
|
||||
```
|
||||
|
||||
## 1.3 Настройка шрифта и размера начального окна
|
||||
|
||||
Скриншот настройки шрифта:
|
||||
|
||||

|
||||
|
||||
Скриншот настройки начального окна:
|
||||
|
||||

|
||||
|
||||
## 1.4 Объединение инструкций используемых выше в одну программу
|
||||
|
||||
Программа в файле pr0
|
||||
|
||||
## 1.5 Изучение содержимого файла Pr0.cpython-311.pyc
|
||||
|
||||
Скриншот части содержимого файла:
|
||||
|
||||

|
||||
|
||||
В файле содержится кэш выполнения программы Pr0 в машинном коде
|
||||
|
||||
## 1.6 Изучение раздела 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 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)
|
||||
```
|
||||
|
||||
## 1.6 Выполнение пункта 15
|
||||
|
||||
```py
|
||||
==================== RESTART: C:\Users\u111-04\Desktop\python-labs\TEMA1\prb1.py ===================
|
||||
Как Вас зовут? Maxim
|
||||
Привет, Maxim
|
||||
|
||||
>>> import tdemo_chaos
|
||||
================ RESTART: C:\Users\u111-04\Desktop\python-labs\TEMA1\tdemo_chaos.py ================
|
||||
```
|
||||
Скриншот вывода программы tdemo_chaos:
|
||||
|
||||

|
||||
|
||||
Скриншот окна с примером "Часы":
|
||||
|
||||

|
@ -0,0 +1,11 @@
|
||||
# Индивидуальное контрольное задание по теме 1
|
||||
|
||||
Корнеев Максим, А-03-23
|
||||
|
||||
## Задание
|
||||
|
||||
Можно ли создавать программы для среды Python с помощью других текстовых редакторов?
|
||||
|
||||
## Решение
|
||||
|
||||
Можно, если использовать синтаксис языка Python. Можно сохранить файл с расширением *.py.
|
@ -0,0 +1,379 @@
|
||||
# Отчет по теме 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(f2)
|
||||
<class 'int'>
|
||||
>>> del f1,f2
|
||||
>>> dir()
|
||||
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os']
|
||||
```
|
||||
|
||||
## 2 Изучение правил именования переменных
|
||||
|
||||
```py
|
||||
>>> gg1=1.6
|
||||
>>> hh1='Строка'
|
||||
>>> 73sr=3
|
||||
SyntaxError: invalid decimal literal
|
||||
>>> and=7
|
||||
SyntaxError: invalid syntax
|
||||
>>> 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']
|
||||
>>> kw_list=keyword.kwlist
|
||||
>>> kw_list
|
||||
['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']
|
||||
>>> Gg1=45
|
||||
>>> gg1
|
||||
1.6
|
||||
>>> Gg1
|
||||
45
|
||||
```
|
||||
|
||||
## 3 Изучение встроенных функций
|
||||
|
||||
```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', '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']
|
||||
>>> abs(-10)
|
||||
10
|
||||
>>> x=[2,4,9,7]
|
||||
>>> len(x)
|
||||
4
|
||||
>>> max(x)
|
||||
9
|
||||
>>> max(3,10)
|
||||
10
|
||||
>>> min(x)
|
||||
2
|
||||
>>> min(3,10)
|
||||
3
|
||||
>>> pow(3,4)
|
||||
81
|
||||
>>> pow(3,4,5)
|
||||
1
|
||||
>>> round(3.284)
|
||||
3
|
||||
>>> round(3.284, 2)
|
||||
3.28
|
||||
>>> animal = ['elephant', 'dog', 'crocodile', 'cat', 'kangaroo']
|
||||
>>> sorted(animal)
|
||||
['cat', 'crocodile', 'dog', 'elephant', 'kangaroo']
|
||||
>>> sorted(animal, reverse=True)
|
||||
['kangaroo', 'elephant', 'dog', 'crocodile', 'cat']
|
||||
>>> sorted(animal, key=len)
|
||||
['dog', 'cat', 'elephant', 'kangaroo', 'crocodile']
|
||||
>>> sum(x)
|
||||
22
|
||||
>>> sum(x, start=10)
|
||||
32
|
||||
>>> list1 = [1, 2, 4, 5]
|
||||
>>> list2 = ['apple', 'banana', 'orange']
|
||||
>>> list3 = list(zip(list1, list2))
|
||||
>>> list3
|
||||
[(1, 'apple'), (2, 'banana'), (4, 'orange')]
|
||||
```
|
||||
|
||||
## 4 Изучение простых базовых типов объектов
|
||||
|
||||
### 4.1 Логический тип
|
||||
```py
|
||||
>>> bb1=True; bb2=False
|
||||
>>> bb1;bb2
|
||||
True
|
||||
False
|
||||
>>> type(bb1); type(bb2)
|
||||
<class 'bool'>
|
||||
<class 'bool'>
|
||||
```
|
||||
|
||||
### 4.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
|
||||
>>> ype(cc1)
|
||||
<class 'complex'>
|
||||
>>> a=3.67; b=-0.45
|
||||
>>> cc2=complex(a,b)
|
||||
>>> cc2
|
||||
(3.67-0.45j)
|
||||
>>> type(a); type(b)
|
||||
<class 'float'>
|
||||
<class 'float'>
|
||||
>>> type(cc2)
|
||||
<class 'complex'>
|
||||
```
|
||||
|
||||
### 4.3 Строка символов
|
||||
```py
|
||||
>>> ss1='Это - строка символов'
|
||||
>>> ss1
|
||||
'Это - строка символов'
|
||||
>>> 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] #Часть строки – с 17-го по 3-й индексы с шагом 2
|
||||
'омсаот '
|
||||
>>> ss1[-4:3:-2]
|
||||
'омсаот '
|
||||
>>> ss1[4]='='
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#106>", line 1, in <module>
|
||||
ss1[4]='='
|
||||
TypeError: 'str' object does not support item assignment
|
||||
>>> ss1=ss1[:4]+'='+ss1[5:]
|
||||
>>> ss1
|
||||
'Это = строка символов'
|
||||
>>> print(ss1b[8:-5])
|
||||
>>> ут:
|
||||
Корн
|
||||
>>> ss1b[-3:4:-3]
|
||||
'внК уз'
|
||||
>>> ss1b[0:7:2]
|
||||
'Мн о'
|
||||
```
|
||||
|
||||
### 4.4 Обобщение
|
||||
```py
|
||||
>>> dd1=True
|
||||
>>> type(dd1), dd1
|
||||
(<class 'bool'>, True)
|
||||
>>> dd2=473
|
||||
>>> type(dd2), dd2
|
||||
(<class 'int'>, 473)
|
||||
>>> dd3=-34.562
|
||||
>>> type(dd3), dd3
|
||||
(<class 'float'>, -34.562)
|
||||
>>> dd4=7.3-4.2j
|
||||
>>> type(dd4), dd4
|
||||
(<class 'complex'>, (7.3-4.2j))
|
||||
>>> dd5='киси-киси мяу-мяу, киси-киси мя-мя-мяу'
|
||||
>>> type(dd5), dd5
|
||||
(<class 'str'>, 'киси-киси мяу-мяу, киси-киси мя-мя-мяу')
|
||||
```
|
||||
|
||||
## 5 Более сложные типы объектов
|
||||
|
||||
### 5.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]
|
||||
>>> spis1[-1]
|
||||
(5-9j)
|
||||
>>> stup[-8::2]
|
||||
[0, 1, 1, 1]
|
||||
```
|
||||
В полученный список вошли элементы из списка stup с индексами 1, 3, 5, 7.
|
||||
|
||||
```py
|
||||
>>> 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']
|
||||
>>> spis1.append('New item')
|
||||
>>> spis1+['New item']
|
||||
[111, 'Список', (5-9j), 'New item', 'New item']
|
||||
>>> spis1.append(ss1b)
|
||||
>>> spis1
|
||||
[111, 'Список', (5-9j), 'New item', 'Меня зовут: \n КорнеевМА']
|
||||
>>> spis1.pop(1)
|
||||
'Список'
|
||||
>>> spis1.insert(1, 'Hello')
|
||||
>>> spis1
|
||||
[111, 'Hello', (5-9j), 'New item', 'Меня зовут: \n КорнеевМА']
|
||||
>>> spis1.remove('Hello')
|
||||
>>> spis1
|
||||
[111, (5-9j), 'New item', 'Меня зовут: \n КорнеевМА']
|
||||
>>> spis1.extend(stup)
|
||||
>>> spis1
|
||||
[111, (5-9j), 'New item', 'Меня зовут: \n КорнеевМА', 0, 0, 1, 1, 1, 1, 1, 1, 1]
|
||||
>>> clspis=[123, (2-4j), 'Raq1']
|
||||
>>> clspis.clear()
|
||||
>>> clspis
|
||||
[]
|
||||
>>> new_list = [3, 1, 4, 1, 5, 9]
|
||||
>>> new_list.sort()
|
||||
>>> new_list
|
||||
[1, 1, 3, 4, 5, 9]
|
||||
>>> new_list.reverse()
|
||||
>>> new_list
|
||||
[9, 5, 4, 3, 1, 1]
|
||||
>>> copy_list = new_list.copy()
|
||||
>>> copy_list
|
||||
[9, 5, 4, 3, 1, 1]
|
||||
>>> new_list.count(1)
|
||||
2
|
||||
>>> new_list.index(3)
|
||||
3
|
||||
>>> spis2=[spis1,[4,5,6,7]]
|
||||
>>> spis2
|
||||
[[111, (5-9j), 'New item', 'Меня зовут: \n КорнеевМА', 0, 0, 1, 1, 1, 1, 1, 1, 1], [4, 5, 6, 7]]
|
||||
>>> spis2[0][1]
|
||||
(5-9j)
|
||||
>>> spis2[0][1]=78
|
||||
>>> spis2
|
||||
[[111, 78, 'New item', 'Меня зовут: \n КорнеевМА', 0, 0, 1, 1, 1, 1, 1, 1, 1], [4, 5, 6, 7]]
|
||||
>>> spis1
|
||||
[111, 78, 'New item', 'Меня зовут: \n КорнеевМА', 0, 0, 1, 1, 1, 1, 1, 1, 1]
|
||||
```
|
||||
spis1 изменился так как в spis2[0] хранится не копия spis1, а ссылка на него.
|
||||
|
||||
```py
|
||||
>>> my_list=[23, 'stroka', False, [2, 3]]
|
||||
```
|
||||
|
||||
### 5.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#210>", line 1, in <module>
|
||||
kort1[2]=90
|
||||
TypeError: 'tuple' object does not support item assignment
|
||||
>>> kort3=(24, 'well', [True, False], (2+3j, 'od'))
|
||||
```
|
||||
|
||||
### 5.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': {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 КорнеевМА'}
|
||||
>>> kort3=(4, 5, 'ara', 2, 'sorc', 19, 3)
|
||||
>>> list4=['wet', '>_<',423,0,52]
|
||||
>>> dic6=dict(zip(kort3,list4))
|
||||
>>> dic6
|
||||
{4: 'wet', 5: '>_<', 'ara': 423, 2: 0, 'sorc': 52}
|
||||
```
|
||||
В словаре 5 элементов так как функция zip() останавливается на длине самой короткой последовательности.
|
||||
|
||||
```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
|
||||
```
|
||||
|
||||
### 5.4 Объект-множество
|
||||
```py
|
||||
>>> mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}
|
||||
>>> mnoz1
|
||||
{'двигатель', 'линия связи', 'микропроцессор', 'датчик'}
|
||||
>>> len(mnoz1)
|
||||
4
|
||||
>>> 'датчик' in mnoz1
|
||||
True
|
||||
>>> mnoz1.add('реле')
|
||||
>>> mnoz1
|
||||
{'двигатель', 'датчик', 'реле', 'линия связи', 'микропроцессор'}
|
||||
>>> mnoz1.remove('линия связи')
|
||||
>>> mnoz1
|
||||
{'двигатель', 'датчик', 'реле', 'микропроцессор'}
|
||||
>>> mnoz2={21,'строка', 21, (4, 2), '4', 4}
|
||||
>>> mnoz2
|
||||
{'4', 4, 'строка', 21, (4, 2)}
|
||||
>>> len(mnoz2)
|
||||
5
|
||||
>>> 'датчик' in mnoz2
|
||||
False
|
||||
>>> mnoz2.add('cat')
|
||||
>>> mnoz2.remove('4')
|
||||
>>> mnoz2
|
||||
{4, 'строка', 21, 'cat', (4, 2)}
|
||||
```
|
@ -0,0 +1,38 @@
|
||||
# Общее контрольное задание по теме 2
|
||||
|
||||
Корнеев Максим, А-03-23
|
||||
|
||||
## Задание
|
||||
|
||||
Реализовать, записать в текстовый файл и проанализировать результаты последовательности инструкций, выполняющих следующие действия:
|
||||
* Создать переменную с именем familia и со значением - символьной строкой – своей фамилией в латинской транскрипции.
|
||||
* Создать переменную со значением, совпадающим с первой буквой из familia.
|
||||
* Создать переменную с именем sp_kw со значением – списком всей ключевых слов языка Python.
|
||||
* Удалите из списка sp_kw значение 'nonlocal'. Выводом списка в командном окне IDLE убедитесь, что это значение удалено из списка.
|
||||
* Создайте кортеж kort_nam с именами: вашим и еще 3-х студентов из вашей группы. Напишите инструкцию, позволяющую убедиться, что тип переменной – это tuple.
|
||||
* Напишите инструкцию, добавляющую в kort_nam имена еще двух студентов.
|
||||
* Напишите инструкцию, позволяющую определить, сколько раз в кортеже присутствуют студенты с именем «Дима».
|
||||
* Создайте словарь dict_bas, в котором ключами являются русские названия типов переменных, использованных в предыдущих операторах, а значениями – ранее созданные переменные, соответствующие этим типам.
|
||||
|
||||
|
||||
## Решение
|
||||
|
||||
```py
|
||||
>>> familia='Korneev'
|
||||
>>> first_letter=familia[0]
|
||||
>>> first_letter
|
||||
'K'
|
||||
>>> sp_kw=keyword.kwlist
|
||||
>>> 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', 'nonlocal', 'not', 'or', 'pass', 'raise', 'return', 'try', 'while', 'with', 'yield']
|
||||
>>> 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=('Максим', 'Даня', 'Дима', 'Артем')
|
||||
>>> type(kort_nam)
|
||||
<class 'tuple'>
|
||||
>>> kort_nam = kort_nam + ('Давид','Дима')
|
||||
>>> kort_nam.count('Дима')
|
||||
2
|
||||
>>> dict_bas={'строка': ['familia', 'first_letter'], 'список': 'sp_kw', 'кортеж': 'kort_nam'}
|
||||
```
|
Загрузка…
Ссылка в новой задаче