форкнуто от main/python-labs
Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
10 KiB
10 KiB
Отчёт по Теме 4
Кузьменко Елена, А-02-23
1. Запустили интерактивную оболочку IDLE.
2.Стандартные функции.
2.1.Округление числа с заданной точностью.
>>> a = round(123.456,1); a; type(a)
123.5
<class 'float'>
>>> a1 = round(123.456,0); a1; type(a1)
123.0
<class 'float'>
>>> a2 = round(123.456); a2; type(a2)
123
<class 'int'>
2.2. Последовательные целые числа.
>>> gg = range(76,123,9); gg; type(gg) #От 76 до 123 с шагом 9
range(76, 123, 9)
<class 'range'>
>>> list(gg)
[76, 85, 94, 103, 112, 121]
>>> gg1 = range(23); gg1 #Создаёт последовательность от 0 до 23 с шагом 1
range(0, 23)
>>> list(range(23))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22]
2.3.Общий объект.
>>> qq = ["Кузьменко", "Беженарь", "Добровольска", "Криви"]; qq
['Кузьменко', 'Беженарь', 'Добровольска', 'Криви']
>>> ff = zip(gg,qq); ff; type(ff)
<zip object at 0x0000014F96720F40>
<class 'zip'>
>>> ff1 = tuple(ff); ff1
((76, 'Кузьменко'), (85, 'Беженарь'), (94, 'Добровольска'), (103, 'Криви'))
>>> ff1[0]
(76, 'Кузьменко')
>>> tuple(ff)
((76, 'Кузьменко'), (85, 'Беженарь'), (94, 'Добровольска'), (103, 'Криви'))
>>> ff
<zip object at 0x0000014F94622440>
>>> ff[0]
Traceback (most recent call last):
File "<pyshell#32>", line 1, in <module>
ff[0]
TypeError: 'zip' object is not subscriptable
2.4. Функция eval().
>>> fff = float(input('коэффициент усиления=')); dan = eval('5*fff-156')
коэффициент усиления=32
>>> dan; type(dan)
4.0
<class 'float'>
2.5. Функция exec().
>>> exec(input('введите инструкции:'))
введите инструкции:perem = -123.456; gg = round(abs(perem)+98,3)
>>> gg
221.456
eval() - возвращает результат; exec() - выполняет код без возврата значения.
2.6. Другие функции.
>>> abs(-5)
5
>>> pow(2,3)
8
>>> max(-1,5,3)
5
>>> min(-1,5,3)
-1
>>> sum([1,2,3])
6
>>> divmod(10,3) # частное и остаток от деления
(3, 1)
>>> len("sdjalad")
7
>>> s=map(str,[1,2,3]); s #Применяет функцию к каждому элементу итерируемого объекта
<map object at 0x0000014F967EFDF0>
>>> list(s)
['1', '2', '3']
3.Функции стандартного модулю math
>>> import math
>>> dir(math)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atan2', 'atanh', 'ceil', 'comb', 'copysign', 'cos', 'cosh', 'degrees', 'dist', 'e', 'erf', 'erfc', 'exp', 'expm1', 'fabs', 'factorial', 'floor', 'fmod', 'frexp', 'fsum', 'gamma', 'gcd', 'hypot', 'inf', 'isclose', 'isfinite', 'isinf', 'isnan', 'isqrt', 'lcm', 'ldexp', 'lgamma', 'log', 'log10', 'log1p', 'log2', 'modf', 'nan', 'nextafter', 'perm', 'pi', 'pow', 'prod', 'radians', 'remainder', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau', 'trunc', 'ulp']
>>> help(math.factorial)
Help on built-in function factorial in module math:
factorial(x, /)
Find x!.
Raise a ValueError if x is negative or non-integral.
>>> math.factorial(5)
120
>>> math.sin(math.pi)
1.2246467991473532e-16
>>> math.acos(0.5)
1.0471975511965979
>>> math.degrees(math.pi)
180.0
>>> math.radians(180) # градусы в радианы
3.141592653589793
>>> math.exp(1)
2.718281828459045
>>> math.log(10)
2.302585092994046
>>> math.log10(100)
2.0
>>> math.sqrt(16)
4.0
>>> math.ceil(4.3) # Округление вверх
5
>>> math.floor(4.8)
4
4.Модуль cmath для работы с комплексными числами.
>>> import cmath
>>> dir(cmath)
['__doc__', '__loader__', '__name__', '__package__', '__spec__', 'acos', 'acosh', 'asin', 'asinh', 'atan', 'atanh', 'cos', 'cosh', 'e', 'exp', 'inf', 'infj', 'isclose', 'isfinite', 'isinf', 'isnan', 'log', 'log10', 'nan', 'nanj', 'phase', 'pi', 'polar', 'rect', 'sin', 'sinh', 'sqrt', 'tan', 'tanh', 'tau']
>>> cmath.sqrt(1.2-0.5j) #квадратный корень
(1.118033988749895-0.22360679774997896j)
>>> cmath.phase(1-0.5j) #фаза(угол) - arctan(b/a)
-0.4636476090008061
5.Модуль random для операций с псевдослучайными числами.
>>> import random
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', '_Sequence', '_Set', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_accumulate', '_acos', '_bisect', '_ceil', '_cos', '_e', '_exp', '_floor', '_inst', '_log', '_os', '_pi', '_random', '_repeat', '_sha512', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'choices', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'lognormvariate', 'normalvariate', 'paretovariate', 'randbytes', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'triangular', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> help(random.seed)
Help on method seed in module random:
seed(a=None, version=2) method of random.Random instance
Initialize internal state from a seed.
The only supported seed types are None, int, float,
str, bytes, and bytearray.
None or no argument seeds from current time or from an operating
system specific randomness source if available.
If *a* is an int, all bits are used.
For version 2 (the default), all of the bits are used if *a* is a str,
bytes, or bytearray. For version 1 (provided for reproducing random
sequences from older versions of Python), the algorithm for str and
bytes generates a narrower range of seeds.
>>> random.seed() #нужен для инициализации генератора псевдослучайных чисел. Воспроизводит последовательность при каждом запуске.
>>> random.random() #случайное число от 0 до 1, не включая верхнюю границу
0.08881917055800503
>>> random.uniform(1,10) #равномерное распределение
8.672615135853867
>>> random.gauss(0,1) #нормальное распределение
-1.571314734927639
>>> random.randint(1,100) #случайное целое
91
>>> random.choice(['1','2','a','b'])
'b'
>>> s = [1,2,3,4,5]
>>> random.shuffle(s); s
[3, 4, 1, 2, 5]
>>> random.sample(s,3) #случайная выборка
[4, 5, 1]
>>> random.betavariate(2,5) #бета-распределение
0.22293634372615048
>>> random.gammavariate(2,1) #гамма-распределение
3.778718164367487
6.Модуль time - работа с календарем и со временем.
>>> import time
>>> dir(time)
['_STRUCT_TM_ITEMS', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'altzone', 'asctime', 'ctime', 'daylight', 'get_clock_info', 'gmtime', 'localtime', 'mktime', 'monotonic', 'monotonic_ns', 'perf_counter', 'perf_counter_ns', 'process_time', 'process_time_ns', 'sleep', 'strftime', 'strptime', 'struct_time', 'thread_time', 'thread_time_ns', 'time', 'time_ns', 'timezone', 'tzname']
>>> c1=time.time(); c1
1760380211.648074
>>> c2 = time.time()-c1; c2
30.08062195777893
>>> dat=time.gmtime(); dat
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=13, tm_hour=18, tm_min=32, tm_sec=19, tm_wday=0, tm_yday=286, tm_isdst=0)
>>> dat.tm_mon
10
>>> dat.tm_min
32
>>> dat.tm_mday
13
>>> time.localtime()
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=13, tm_hour=21, tm_min=34, tm_sec=31, tm_wday=0, tm_yday=286, tm_isdst=0)
>>> time.asctime()
'Mon Oct 13 21:35:28 2025'
>>> time.ctime(time.time()) #секунды в строку
'Mon Oct 13 21:35:47 2025'
>>> time.sleep(2) #задержка выполнения на 2 секунды
>>> time.mktime(time.localtime()) #преобразование в секунды
1760380623.0
7.Графические функции.
>>> import pylab
>>> x = list(range(-3,55,4))
>>> t = list(range(15))
>>> pylab.plot(t,x)
[<matplotlib.lines.Line2D object at 0x0000019FF7371640>]
>>> pylab.title('Первый график')
Text(0.5, 1.0, 'Первый график')
>>> pylab.xlabel('время')
Text(0.5, 0, 'время')
>>> pylab.ylabel('сигнал')
Text(0, 0.5, 'сигнал')
>>> pylab.show()
>>> X1=[12,6,8,10,7]; X2=[5,7,9,11,13]
>>> pylab.plot(X1); pylab.plot(X2)
[<matplotlib.lines.Line2D object at 0x0000019FFB0C0C40>]
[<matplotlib.lines.Line2D object at 0x0000019FFB0C0F40>]
>>> pylab.show()
>>> region=['Центр','Урал','Сибирь','Юг']
>>> naselen=[65,12,23,17]
>>> pylab.pie(naselen,labels=region)
([<matplotlib.patches.Wedge object at 0x0000019FFB283E20>, <matplotlib.patches.Wedge object at 0x0000019FFB283EE0>, <matplotlib.patches.Wedge object at 0x0000019FFB2AB100>, <matplotlib.patches.Wedge object at 0x0000019FFB2AB580>], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')])
>>> pylab.show()
>>> X0 = [1,1,2,2,2,3,3,3,4,4,5]
>>> pylab.hist(X0,5)
(array([2., 3., 3., 2., 1.]), array([1. , 1.8, 2.6, 3.4, 4.2, 5. ]), <BarContainer object of 5 artists>)
>>> pylab.show()
>>> x0 = ['a','b','c']
>>> x10 = [123,321,112]
>>> pylab.bar(x0,x10)
<BarContainer object of 3 artists>
>>> pylab.show()
8.Модуль statistics.
>>> import statistics
>>> s = [123, 49, 3, 16, 8, 10, 9]
>>> statistics.mean(s) # среднее
31.142857142857142
>>> statistics.median(s) # медиана
10
>>> statistics.stdev(s) # стандартное отклонение
43.30291973000039
>>> statistics.variance(s) # дисперсия
1875.1428571428573
>>> s1 = [123, 49, 3, 3, 3, 16, 8, 8, 10, 9]
>>> statistics.mode(s1) # мода
3




