форкнуто от main/python-labs
Вы не можете выбрать более 25 тем
Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
9.8 KiB
9.8 KiB
Протокол по Теме 4
Марков Никита Сергеевич, А-03-23
1. Начало работы
Запуск IDLE, установление рабочего каталога
2. Стандартные функции
2.1 Функция round – округление числа с заданной точностью
>>> round(123.456,1)
123.5
>>> round(123.456,0)
123.0
>>> round(123.456)
123
2.2. Функция range
>>> gg=range(76,123,9)
>>> gg
range(76, 123, 9)
>>> list(gg)
[76, 85, 94, 103, 112, 121]
>>> range(23)
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. Функция zip
>>> qq = ['Markov','Butko','Ogarkov','Krishtul']
>>> ff=zip(gg,qq)
>>> ff
<zip object at 0x0000026369CB4400>
>>> tuple(ff)
((76, 'Markov'), (85, 'Butko'), (94, 'Ogarkov'), (103, 'Krishtul'))
>>> ff[0]
Traceback (most recent call last):
File "<pyshell#13>", line 1, in <module>
ff[0]
TypeError: 'zip' object is not subscriptable
Нельзя обращаться с указанием индекса, т.к. объект является итерируемым класса zip
2.4 Функция eval
>>> fff=float(input('коэффициент усиления=')); dan=eval('5*fff-156')
коэффициент усиления=5
>>> dan
-131.0
2.5 Функция exec
>>> exec(input('введите инструкции:'))
введите инструкции:perem=-123.456;gg=round(abs(perem)+98,3)
>>> gg
221.456
2.6. Функции abs, pow, max, min, sum, divmod, len, map
>>> abs(-14)
14
>>> pow(2, 3)
8
>>> max(1, 2, 3)
3
>>> min(1, 2, 3)
1
>>> sum([1, 2, 3])
6
>>> divmod(5, 3)
(1, 2)
>>> len(range(0, 15+1))
16
>>> map_test = map(lambda x: round(x, 1), [12.1245, 14.125234, 534.222])
>>> list(map_test)
[12.1, 14.1, 534.2]
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(90)
0.8939966636005579
>>> math.acos(0)
1.5707963267948966
>>> 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(3.14) # округление вверх
4
>>> math.floor(3.14) # округление вниз
3
>>> math.pi
3.141592653589793
>>> math.sin((2*math.pi/7) + math.exp(0.23))
0.8334902641414562
4. Функции из модуля cmath, c комплексными числами
>>> 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)
-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.random() # вещественное число от 0.0 до 1.0
0.12874671061082976
>>> random.uniform(5, 15) # вещественное число от 5.0 до 15.0
13.134575401523493
>>> random.randint(1, 100) # целое число от 1 до 100
32
>>> random.gauss(0, 1) # mu - среднее значение, sigma - стандартное отклонение
-0.07800637063087972
>>> random.choice([1, 2, 3, 4]) # случайный выбор элемента из списка, кортежа, строки и т.д.
3
>>> My_Numbers = [1, 2, 3, 4]
>>> random.shuffle(My_Numbers)
>>> My_Numbers
[1, 2, 4, 3]
>>> random.sample(My_Numbers, 2) # случайный выбор двух элементов из My_Numbers
[4, 1]
>>> random.betavariate(2, 5)
0.16541871582286427
>>> random.gammavariate(2, 1)
0.6551814424330216
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
1760283309.499735
>>> c2=time.time()-c1
>>> c2
10.906989812850952
>>> dat=time.gmtime()
>>> dat
time.struct_time(tm_year=2025, tm_mon=10, tm_mday=12, tm_hour=15, tm_min=35, tm_sec=35, tm_wday=6, tm_yday=285, tm_isdst=0)
>>> dat.tm_mon
10
>>> time.asctime((2024, 12, 10, 18, 7, 14, 1, 345, 0)) #год, месяц, день, час, минута, секунда, день недели, день года, летнее время
'Tue Dec 10 18:07:14 2024'
>>> time.ctime(time.time())
'Sun Oct 12 18:36:59 2025'
>>> time.mktime((2025, 12, 25, 15, 30, 0, 0, 0, 0))
1766665800.0
7. Графические функции
>>> import pylab
>>> x=list(range(-3,55,4))
>>> x
[-3, 1, 5, 9, 13, 17, 21, 25, 29, 33, 37, 41, 45, 49, 53]
>>> t=list(range(15))
>>> t
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14]
>>> pylab.plot(t,x)
[<matplotlib.lines.Line2D object at 0x000002630D20D340>]
>>> 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)
[<matplotlib.lines.Line2D object at 0x0000026312246130>]
>>> pylab.plot(X2)
[<matplotlib.lines.Line2D object at 0x00000263122463D0>]
>>> pylab.show()
Результат:
>>> region=['Центр','Урал','Сибирь','Юг']
>>> naselen=[65,12,23,17]
>>> pylab.pie(naselen,labels=region)
([<matplotlib.patches.Wedge object at 0x000002631062D130>, <matplotlib.patches.Wedge object at 0x000002631062D1F0>, <matplotlib.patches.Wedge object at 0x000002631063B970>, <matplotlib.patches.Wedge object at 0x000002631063BDF0>], [Text(-0.191013134139045, 1.0832885038559115, 'Центр'), Text(-0.861328292412156, -0.6841882582231001, 'Урал'), Text(0.04429273995539947, -1.0991078896938387, 'Сибирь'), Text(0.9873750693480946, -0.48486129194837324, 'Юг')])
>>> pylab.show()
Результат:
>>> pylab.bar(region, naselen)
<BarContainer object of 4 artists>
>>> pylab.title('Население по регионам')
Text(0.5, 1.0, 'Население по регионам')
>>> pylab.ylabel('Население (млн)')
Text(0, 0.5, 'Население (млн)')
>>> pylab.show()
Результат:
>>> pylab.hist(naselen)
(array([2., 0., 1., 0., 0., 0., 0., 0., 0., 1.]), array([12. , 17.3, 22.6, 27.9, 33.2, 38.5, 43.8, 49.1, 54.4, 59.7, 65. ]), <BarContainer object of 10 artists>)
>>> pylab.title('Гистограмма распределения населения')
Text(0.5, 1.0, 'Гистограмма распределения населения')
>>> pylab.xlabel('Население (млн)')
Text(0.5, 0, 'Население (млн)')
>>> pylab.ylabel('Частота')
Text(0, 0.5, 'Частота')
>>> pylab.show()
Результат:
8. Статистический модуль statistics
>>> import statistics
>>> numbers = [1,2,3,4,5,6,7,8,9]
>>> statistics.mean(numbers)
5
>>> statistics.median(numbers)
5
>>> statistics.mode(numbers)
1