форкнуто от main/python-labs
Родитель
d13201d93e
Сommit
23de86c9c6
@ -0,0 +1,484 @@
|
||||
# Отчет по теме 2
|
||||
|
||||
Лыкова Елизавета, А-01-23
|
||||
|
||||
## 1. Запуск IDLE, привязка католога, создание файла отчета.
|
||||
|
||||
```py
|
||||
import os
|
||||
os.chdir("C:\\Users\\Home\\Desktop\\python-labs\\TEMA2\\")
|
||||
```
|
||||
|
||||
## 2. Изучение простых объектов, операции присваивания.
|
||||
|
||||
```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']
|
||||
```
|
||||
|
||||
## 3. Изучение правил наименования объектов.
|
||||
|
||||
```py
|
||||
gg1 = 1.6
|
||||
hh1 = "Строка"
|
||||
73sr = 3
|
||||
SyntaxError: invalid decimal literal
|
||||
and = 7
|
||||
SyntaxError: invalid syntax
|
||||
```
|
||||
|
||||
## 4. Список ключевых слов.
|
||||
|
||||
```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']
|
||||
keyword_list = keyword.kwlist
|
||||
```
|
||||
|
||||
## 5. Список встроенных идентификаторов.
|
||||
|
||||
```py
|
||||
dir(builtins)
|
||||
['ArithmeticError', 'AssertionError', 'AttributeError',
|
||||
'BaseException', 'BaseExceptionGroup', 'BlockingIOError',
|
||||
'BrokenPipeError', 'BufferError', 'BytesWarning',
|
||||
'ChildProcessError',...]
|
||||
help(abs)
|
||||
Help on built-in function abs in module builtins:
|
||||
|
||||
abs(x, /)
|
||||
Return the absolute value of the argument.
|
||||
|
||||
help (len)
|
||||
Help on built-in function len in module builtins:
|
||||
|
||||
len(obj, /)
|
||||
Return the number of items in a container.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
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.
|
||||
|
||||
abs(-5)
|
||||
5
|
||||
len('primer')
|
||||
6
|
||||
max(9,8,3)
|
||||
9
|
||||
min(9,8,3)
|
||||
3
|
||||
pow(2,3)
|
||||
8
|
||||
round (5.2381, 2)
|
||||
5.24
|
||||
pack = (2,5,1,0,4)
|
||||
sorted(pack)
|
||||
[0, 1, 2, 4, 5]
|
||||
sum(pack)
|
||||
12
|
||||
pack2 = ('A','B','C','D','E')
|
||||
fullpack = list(zip(pack,pack2))
|
||||
print(fullpack)
|
||||
[(2, 'A'), (5, 'B'), (1, 'C'), (0, 'D'), (4, 'E')]
|
||||
```
|
||||
|
||||
## 6. Убеждаемся, что малые и большие буквы в именах объектов различаются.
|
||||
|
||||
```py
|
||||
Gg1=45
|
||||
gg1,Gg1
|
||||
(1.6, 45)
|
||||
```
|
||||
|
||||
## 7. Изучение простых базовых типов объектов.
|
||||
|
||||
## 7.1. Логический тип
|
||||
|
||||
```py
|
||||
bb1=True;bb2=False
|
||||
bb1,bb2
|
||||
(True, False)
|
||||
type(bb1)
|
||||
<class 'bool'>
|
||||
```
|
||||
|
||||
## 7.2. Остальные типы
|
||||
|
||||
```py
|
||||
ii1=-1234567890
|
||||
ii1
|
||||
-1234567890
|
||||
type(ii1)
|
||||
<class 'int'>
|
||||
ff1=-8.9876e-12
|
||||
ff1
|
||||
-8.9876e-12
|
||||
type(ff1)
|
||||
<class 'float'>
|
||||
dv1=0b1101010
|
||||
type(dv1)
|
||||
<class 'int'>
|
||||
vsm1=0o52765
|
||||
vsm1
|
||||
22005
|
||||
type(vsm1)
|
||||
<class 'int'>
|
||||
shest1=0x7109af6
|
||||
shest1
|
||||
118528758
|
||||
type(shest1)
|
||||
<class 'int'>
|
||||
cc1=2-3j
|
||||
cc1
|
||||
(2-3j)
|
||||
type(cc1)
|
||||
<class 'complex'>
|
||||
a=3.67;b=-0.45
|
||||
cc2=complex(a,b)
|
||||
cc2
|
||||
(3.67-0.45j)
|
||||
```
|
||||
|
||||
## 7.3 Символьная строка.
|
||||
|
||||
```py
|
||||
ss1='Это-строка символов'
|
||||
ss1="Это-строка символов"
|
||||
ssa1 = "Это - \"строка символов\", \n \t выводимая на двух строках"
|
||||
print(ssa1)
|
||||
Это - "строка символов",
|
||||
выводимая на двух строках
|
||||
ss1b = 'Меня зовут: \n Лыкова Е.А'
|
||||
print(ss1b)
|
||||
Меня зовут:
|
||||
Лыкова Е.А
|
||||
mnogo = """Нетрудно заметить, что в результате операции
|
||||
над числами разных типов получается число,
|
||||
имеющее более сложный тип из тех, которые участвут в операции."""
|
||||
print(mnogo)
|
||||
Нетрудно заметить, что в результате операции
|
||||
над числами разных типов получается число,
|
||||
имеющее более сложный тип из тех, которые участвут в операции.
|
||||
ss1[0]
|
||||
'Э'
|
||||
ss1[8]
|
||||
'к'
|
||||
ss1[-2]
|
||||
'о'
|
||||
ss1[6:9]
|
||||
'рок'
|
||||
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#82>", line 1, in <module>
|
||||
ss1[4]='='
|
||||
TypeError: 'str' object does not support item assignment
|
||||
ss1=ss1[:4]+'='+ss1[5:]
|
||||
ss1
|
||||
'Это-=трока символов'
|
||||
print(ss1b)
|
||||
Меня зовут:
|
||||
Лыкова Е.А
|
||||
ss1b[5:8]
|
||||
'зов'
|
||||
ss1b[::-2]
|
||||
'АЕаоы твзяе'
|
||||
ss1b[-6:10:3]
|
||||
''
|
||||
```
|
||||
|
||||
## 8. Изучение более сложных типов объектов.
|
||||
|
||||
## 8.1 Списки.
|
||||
|
||||
```py
|
||||
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]
|
||||
spis[-1]
|
||||
10
|
||||
stup[-8::2]
|
||||
[0, 1, 1, 1]
|
||||
```
|
||||
|
||||
В этот список вошло четыре элемента. В исходном списке они имели индексы 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']
|
||||
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.append(ss1b)
|
||||
spis1
|
||||
[111, 'Список', (5-9j), 'New item', 'Меня зовут: \n Лыкова Е.А']
|
||||
spis1.pop(1)
|
||||
'Список'
|
||||
spis1
|
||||
[111, (5-9j), 'New item', 'Меня зовут: \n Лыкова Е.А']
|
||||
spis1.insert(1, 'Vesch')
|
||||
spis1
|
||||
[111, 'Vesch', (5-9j), 'New item', 'Меня зовут: \n Лыкова Е.А']
|
||||
spis1.remove(111)
|
||||
spis1
|
||||
['Vesch', (5-9j), 'New item', 'Меня зовут: \n Лыкова Е.А']
|
||||
spis1.extend(['lol'])
|
||||
spis1
|
||||
['Vesch', (5-9j), 'New item', 'Меня зовут: \n Лыкова Е.А', 'lol']
|
||||
spis1.clear()
|
||||
spis1
|
||||
[]
|
||||
spisnew = [ 'V', 'C', 'O', 'S']
|
||||
spisnew.sort()
|
||||
spisnew
|
||||
['C', 'O', 'S', 'V']
|
||||
spisnew.reverse()
|
||||
spisnew
|
||||
['V', 'S', 'O', 'C']
|
||||
spisnew.copy()
|
||||
['V', 'S', 'O', 'C']
|
||||
spiscopy = spisnew.copy()
|
||||
spiscopy
|
||||
['V', 'S', 'O', 'C']
|
||||
spisnew.count('O')
|
||||
1
|
||||
spisnew.index('O')
|
||||
2
|
||||
spis2=[spis1,[4,5,6,7]]
|
||||
spis2[0][1]
|
||||
'Spisok'
|
||||
spis2[0][1]=78
|
||||
spis2
|
||||
[[111, 78, (5-9j)], [4, 5, 6, 7]]
|
||||
spis1
|
||||
[111, 78, (5-9j)]
|
||||
```
|
||||
|
||||
Объект spis1 отличается от своего изначального вида, поскольку мы использовали на нём различные функции,
|
||||
которые добавляли, убирали и изменяли объекты в нём.
|
||||
|
||||
```py
|
||||
spisochek = [17, 17, 17, 16]
|
||||
moispisok = [1991, 'Stroka', False, spisochek]
|
||||
moispisok
|
||||
[1991, 'Stroka', False, [17, 17, 17, 16]]
|
||||
```
|
||||
|
||||
## 8.2 Объект-кортеж
|
||||
|
||||
```py
|
||||
kort1 = (222,'Kortezh',77+8j)
|
||||
kort1 = kort1 + (1,2)
|
||||
kort1 = kort1 + (ss1b,)
|
||||
kort2 = kort1[:2]+kort1[3:]
|
||||
kort2.index(2)
|
||||
3
|
||||
kort1.count(222)
|
||||
1
|
||||
kort1[2]=90
|
||||
Traceback (most recent call last):
|
||||
File "<pyshell#177>", line 1, in <module>
|
||||
kort1[2]=90
|
||||
TypeError: 'tuple' object does not support item assignment
|
||||
moikort = (2005,'StrokaNovaya',spisochek,kort1)
|
||||
moikort
|
||||
(2005, 'StrokaNovaya', [17, 17, 17, 16], (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 devation',3:'correlation'}
|
||||
dic3={'statistics':dic2,'POAS':['base','elementary','programming']}
|
||||
dic3['statistics'][2]
|
||||
'standart devation'
|
||||
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 = ('A','B','C','D','E','F','G')
|
||||
spisok = (1,2,3,4,5)
|
||||
slovar = dict(zip(kortezh,spisok))
|
||||
print(slovar,len(slovar))
|
||||
{'A': 1, 'B': 2, 'C': 3, 'D': 4, 'E': 5} 5
|
||||
```
|
||||
|
||||
## 8.4. Объект-множество
|
||||
|
||||
```py
|
||||
mnoz1={'двигатель','датчик','линия связи','датчик','микропроцессор','двигатель'}
|
||||
mnoz1
|
||||
{'микропроцессор', 'линия связи', 'датчик', 'двигатель'}
|
||||
len(mnoz1)
|
||||
4
|
||||
'датчик' in mnoz1
|
||||
True
|
||||
mnoz1.add('реле')
|
||||
mnoz1.remove('линия связи')
|
||||
mnoz1
|
||||
{'микропроцессор', 'двигатель', 'датчик', 'реле'}
|
||||
mnozestvo = {'огурец','дикий огурец','кукуруза'}
|
||||
len(mnozestvo)
|
||||
3
|
||||
'кукуруза' in mnozestvo
|
||||
True
|
||||
mnozestvo.add('кукуруза сейчас')
|
||||
mnozestvo
|
||||
{'дикий огурец', 'огурец', 'кукуруза сейчас', 'кукуруза'}
|
||||
mnozestvo.remove('огурец')
|
||||
mnozestvo
|
||||
{'дикий огурец', 'кукуруза сейчас', 'кукуруза'}
|
||||
```
|
||||
Загрузка…
Ссылка в новой задаче