Добавил:
Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:
Скачиваний:
14
Добавлен:
09.08.2021
Размер:
185.68 Кб
Скачать

Python, ПОАС, ОКЗ, ИКЗ 3 и протокол по теме 2

#Общее контрольное задание по Теме 2

>>>familia="family"

>>>first=familia[0]

>>>import keyword

>>>sp_kw=keyword.kwlist

>>>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']

#Нет значения 'nonlocal'.

>>>kort_nam=('Kira','Roma','Nastya','Katya')

>>>type(kort_nam)

<class 'tuple'>

#Класс tuple - кортеж.

>>>kort_nam=kort_nam+('Anna','Denis')

>>>kort_nam

('Kira', 'Roma', 'Nastya', 'Katya', 'Anna', 'Denis')

#В конец кортежа добавились элементы 'Anna','Denis'.

>>>kort_nam.count('Дима')

0

#В кортеже нет элемента 'Дима', то есть этот элемент встречается 0 раз.

>>>dict_bas=dict(zip(['Строка символов','Список','Кортеж'],[familia+first,sp_kw,kort_nam]))

>>>dict_bas

{'Строка символов': 'familyK', 'Список': ['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'], 'Кортеж': ('Kira', 'Roma', 'Nastya', 'Katya', 'Anna', 'Denis')}

#В словаре dict_bas ключами являются символьные строки 'Строка символов', 'Список', 'Кортеж', а значениями - строка символов familia+first, список sp_kw, кортеж kort_nam.

#Индивидуальное контрольное задание 3 по Теме 2

#Объекты b1,b2 относятся к классу "словарь" (dict), об этом говорят фигурные скобки и наличие двоеточия между ключами и значениями словаря.

>>>b1={'d':23,'f':11,'k':45}

>>>type(b1)

<class 'dict'>

#Проверка класса: dict - словарь.

1

>>>b2={'u':6,'v':67}

>>>type(b2)

<class 'dict'>

#Проверка класса: dict - словарь.

#Создание объекта b3 того же класса со всеми 5 элементами:

>>>b3=b1.copy()

>>>b3.update(b2)

#Проверка:

>>>b3

{'d': 23, 'f': 11, 'k': 45, 'u': 6, 'v': 67}

>>> type(b3)

<class 'dict'>

# Протокол по Теме 2

>>>import os

>>>os.chdir('d:\\family\\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']

>>> 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__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']

>>>type(f2) <class 'int'>

>>>del f1,f2

>>>dir()

['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'os']

#Объектов f1, f2 больше нет в оперативной памяти.

#Пункт 3

>>> gg1=1.6

2

>>>gg1

1.6

>>>hh1='Строка'

>>>hh1

'Строка'

>>> 73sr=3

SyntaxError: invalid syntax

>>> 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']

>>>kwl=keyword.kwlist

>>>kwl

['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']

#Пункт 5

>>>import builtins

>>>dir(builtins)

['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException', 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning', 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError', 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning', 'EOFError', 'Ellipsis', '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', 'all', '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(-5.3)

5.3

>>>help(len)

Help on built-in function len in module builtins:

3

len(obj, /)

Return the number of items in a container.

>>>len([1,2,3,'a'])

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 arguments, return the largest argument.

>>>max([-5,0,4])

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 arguments, return the smallest argument.

>>>min([-5,0,4])

-5

>>>help(pow)

Help on built-in function pow in module builtins:

pow(x, y, z=None, /)

Equivalent to x**y (with two arguments) or x**y % z (with three arguments)

Some types, such as ints, are able to use a more efficient algorithm when invoked using the three argument form.

>>>pow(5,2)

25

>>>help(round)

4

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(2.673)

3

>>>round(2.673,2)

2.67

>>>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([10,0,-1,5,4]) [-1, 0, 4, 5, 10]

>>>sorted([10,0,-1,5,4],reverse=True) [10, 5, 4, 0, -1]

>>>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([-5,5,4])

4

>>>help(zip)

Help on class zip in module builtins:

class zip(object)

|

zip(*iterables) --> zip object

|

 

|

Return a zip object whose .__next__() method returns a tuple where

5

|

the i-th element comes from the i-th iterable argument. The .__next__()

|

method continues until the shortest iterable in the argument sequence

|

is exhausted and then it raises StopIteration.

|

 

|

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.

|

 

|

----------------------------------------------------------------------

|

Static methods defined here:

|

 

|

__new__(*args, **kwargs) from builtins.type

|

Create and return a new object. See help(type) for accurate signature.

>>>stl1=[1,2,3]

>>>stl2=[4,5,6]

>>>stl=zip(stl1,stl2)

>>>list(stl)

[(1, 4), (2, 5), (3, 6)]

#Пункт 6

>>>Gg1=45

>>>gg1

1.6

>>>Gg1

45

#Пункт 7.1

>>>bb1=True; bb2=False

>>>bb1;bb2

True

False

>>> type(bb1) <class 'bool'>

6

#Пункт 7.2

>>>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

>>>type(a)

<class 'float'>

>>>cc2=complex(a,b)

>>>type(cc2)

<class 'complex'>

>>>cc2 (3.67-0.45j)

#Пункт 7.3

>>>ss1='Это - строка символов'

>>>type(ss1)

<class 'str'>

>>>ss1="Это - строка символов"

>>>type(ss1)

<class 'str'>

>>>ss1a="Это - \" строка символов \", \n \t выводимая на двух строках"

>>>print(ss1a)

Это - " строка символов ",

выводимая на двух строках

>>>ss1b= 'Меня зовут: \nFIO.'

>>>print(ss1b)

Меня зовут:

7

FIO

>>> 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#18>", line 1, in <module> ss1[4]='='

TypeError: 'str' object does not support item assignment

>>>ss1=ss1[:4]+'='+ss1[5:]

>>>ss1

'Это = строка символов'

>>>s1=ss1b[:10]

>>>s1

'Меня зовут'

8

>>>s2=ss1b[5:10:2]

>>>s2

'звт'

>>>s3=ss1b[-21:10]

>>>s3

'овут'

>>>bb2=1>5

>>>type(bb2) <class 'bool'>

>>>bb2 False

>>>ii2=540

>>>type(ii2) <class 'int'>

>>>ii2

540

>>>ff2=10e-2

>>>type(ff2) <class 'float'>

>>>ff2

0.1

>>>cc3=-5j

>>>type(cc3) <class 'complex'>

>>>cc3

(-0-5j)

>>>ss2="Новая строка"

>>>type(ss2)

<class 'str'>

>>> ss2 'Новая строка'

>>>ss3='a'

>>>type(ss3) <class 'str'>

>>>ss3

'a'

#Пункт 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,

9

8,9,10]

>>>spis1[-1] (5-9j)

>>>stup[-8::2] [0, 1, 1, 1]

#В новый список вошло 4 элемента, которые в исходном списке имели индексы -8, -6,-4,-2.

>>>spis1[1]='Список'

>>>spis1

[111, 'Список', (5-9j)]

>>>len(spis1)

3

>>>help(spis1.append)

Help on built-in function append:

append(...) method of builtins.list instance L.append(object) -> None -- append object to end

>>>spis1.append('New item')

>>>spis1+['New item']

[111, 'Список', (5-9j), 'New item', 'New item']

>>>spis1.append(ss1b)

>>>spis1

[111, 'Список', (5-9j), 'New item', 'Меня зовут: \nFIO']

>>>spis1.pop(1) 'Список'

>>>spis1

[111, (5-9j), 'New item', 'Меня зовут: \nFIO']

>>> help(spis1.insert)

Help on built-in function insert:

insert(index, object, /) method of builtins.list instance Insert object before index.

>>>spis1.insert(1,'new')

>>>spis1

[111, 'new', (5-9j), 'New item', 'Меня зовут: \nFIO']

>>> help(spis1.remove)

Help on built-in function remove:

remove(value, /) method of builtins.list instance Remove first occurrence of value.

Raises ValueError if the value is not present.

10

Соседние файлы в папке Лабораторные_Python