Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

494 строки
14 KiB
Plaintext

Python 3.13.7 (v3.13.7:bcee1c32211, Aug 14 2025, 19:10:51) [Clang 16.0.0 (clang-1600.0.26.6)] on darwin
Enter "help" below or click "Help" above for more information.
def uspeh():
"""Подтверждение успеха операции"""
print('Выполнено успешно!')
uspeh()
Выполнено успешно!
dir()
['__annotations__', '__builtins__', '__doc__', '__loader__', '__name__', '__package__', '__spec__', 'uspeh']
help(uspeh)
Help on function uspeh in module __main__:
uspeh()
Подтверждение успеха операции
def sravnenie(a,b):
"""Сравнение a и b"""
if a>b:
print(a,' больше ',b)
elif a<b:
print(a, ' меньше ',b)
else:
print(a, ' равно ',b)
n,m=16,5;sravnenie(n,m)
16 больше 5
n,m='a','5';sravnenie(n,m)
a больше 5
def logistfun(b,a):
"""Вычисление логистической функции"""
import math
return a/(1+math.exp(-b))
v,w=1,0.7;z=logistfun(w,v)
z
0.6681877721681662
def slozh(a1,a2,a3,a4):
""" Сложение значений четырех аргументов"""
return a1+a2+a3+a4
slozh(1,2,3,4)
10
slozh('1','2','3','4')
'1234'
b1=[1,2];b2=[-1,-2];b3=[0,2];b4=[-1,-1]
q=slozh(b1,b2,b3,b4)
q
[1, 2, -1, -2, 0, 2, -1, -1]
b1=(1,2);b2=(-1,-2);b3=(0,2);b4=(-1,-1)
q=slozh(b1,b2,b3,b4)
q
(1, 2, -1, -2, 0, 2, -1, -1)
b1={1,2};b2={-1,-2};b3={0,2};b4={-1,-1}
q=slozh(b1,b2,b3,b4)
Traceback (most recent call last):
File "<pyshell#25>", line 1, in <module>
q=slozh(b1,b2,b3,b4)
File "<pyshell#15>", line 3, in slozh
return a1+a2+a3+a4
TypeError: unsupported operand type(s) for +: 'set' and 'set'
b1={'a':1,'b':2};b2={'a':-1,'b':-2}
q=slozh(b1,b2)
Traceback (most recent call last):
File "<pyshell#27>", line 1, in <module>
q=slozh(b1,b2)
TypeError: slozh() missing 2 required positional arguments: 'a3' and 'a4'
b1={'a':1,'b':2};b2={'a':-1,'b':-2};b3={'a':0,'b':2};b4={'a':-1,'b':-1}
q=slozh(b1,b2,b3,b4)
Traceback (most recent call last):
File "<pyshell#29>", line 1, in <module>
q=slozh(b1,b2,b3,b4)
File "<pyshell#15>", line 3, in slozh
return a1+a2+a3+a4
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
def inerz(x,T,ypred):
""" Модель устройства с памятью:
x- текущее значение вх.сигнала,
T -постоянная времени,
ypred - предыдущее значение выхода устройства"""
y=(x+T*ypred)/(T+1)
return y
sps=[0]+[1]*100
spsy=[]
TT=20
yy=0
for xx in sps:
yy=inerz(xx,TT,yy)
spsy.append(yy)
import matplotlib
import matplotlib as plt
plt.plot()
Traceback (most recent call last):
File "<pyshell#40>", line 1, in <module>
plt.plot()
File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/matplotlib/_api/__init__.py", line 218, in __getattr__
raise AttributeError(
AttributeError: module 'matplotlib' has no attribute 'plot'
a=plt.figure()
Traceback (most recent call last):
File "<pyshell#41>", line 1, in <module>
a=plt.figure()
File "/Library/Frameworks/Python.framework/Versions/3.13/lib/python3.13/site-packages/matplotlib/_api/__init__.py", line 218, in __getattr__
raise AttributeError(
AttributeError: module 'matplotlib' has no attribute 'figure'
import matplotlib.pyplot as plt
plt.plot()
[]
plt.plot(sps, spsy)
[<matplotlib.lines.Line2D object at 0x113a13390>]
plt.show()
arr = [i for i in range(101)]
plt.plot(arr, spsy)
[<matplotlib.lines.Line2D object at 0x12016c550>]
plt.show()
len(spsy)
101
plt.show()
plt.plot(arr, spsy)
[<matplotlib.lines.Line2D object at 0x1201c2e90>]
plt.show()
dir(inerz)
['__annotations__', '__builtins__', '__call__', '__class__', '__closure__', '__code__', '__defaults__', '__delattr__', '__dict__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__get__', '__getattribute__', '__getstate__', '__globals__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__kwdefaults__', '__le__', '__lt__', '__module__', '__name__', '__ne__', '__new__', '__qualname__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__type_params__']
inerz.__doc__
'Модель устройства с памятью:\nx- текущее значение вх.сигнала,\n T -постоянная времени,\n ypred - предыдущее значение выхода устройства'
help(inerz)
Help on function inerz in module __main__:
inerz(x, T, ypred)
Модель устройства с памятью:
x- текущее значение вх.сигнала,
T -постоянная времени,
ypred - предыдущее значение выхода устройства
fnkt=sravnenie
v=16
fnkt(v,23)
16 меньше 23
typ_fun=8
if typ_fun==1:
def func():
print('Функция 1')
else:
def func():
print('Функция 2')
func()
Функция 2
def fun_arg(fff,a,b,c):
"""fff-имя функции, используемой
в качестве аргумента функции fun_arg"""
return a+fff(c,b)
SyntaxError: unexpected indent
def fun_arg(fff,a,b,c):
"""fff-имя функции, используемой
в качестве аргумента функции fun_arg"""
return a+fff(c,b)
zz=fun_arg(logistfun,-3,1,0.7)
SyntaxError: unexpected indent
zz=fun_arg(logistfun,-3,1,0.7)
def logistfun(a,b=1): #Аргумент b – необязательный; значение по умолчанию=1
"""Вычисление логистической функции"""
import math
return b/(1+math.exp(-a))
logistfun(0.7)
0.6681877721681662
logistfun(0.7,2)
1.3363755443363323
logistfun(b=0.5,a=0.8)
0.34498724056380625
b1234=[b1,b2,b3,b4]
qq=slozh(*b1234)
Traceback (most recent call last):
File "<pyshell#74>", line 1, in <module>
qq=slozh(*b1234)
File "<pyshell#15>", line 3, in slozh
return a1+a2+a3+a4
TypeError: unsupported operand type(s) for +: 'dict' and 'dict'
b1=[1,2];b2=[-1,-2];b3=[0,2];b4=[-1,-1]
b1234=[b1,b2,b3,b4]
qq=slozh(*b1234)
qq
[1, 2, -1, -2, 0, 2, -1, -1]
dic4={"a1":1,"a2":2,"a3":3,"a4":4}
qqq=slozh(**dic4)
qqq
10
e1=(-1,6);dd2={'a3':3,'a4':9}
qqqq=slozh(*e1,**dd2)
def func4(*kort7):
"""Произвольное число аргументов в составе кортежа"""
smm=0
for elt in kort7:
smm+=elt
return smm
func4(-1,2)
1
func4(-1,2,0,3,6)
10
def func4(a,b=7,*kort7): #Аргументы: a-позиционный, b- по умолчанию + кортеж
"""Кортеж - сборка аргументов - должен быть последним!"""
smm=0
for elt in kort7:
smm+=elt
return a*smm+b
func4(-1,2,0,3,6)
-7
def func4(a,b=7,**dic5): #Аргументы: a-позиционный, b- по умолчанию + кортеж
"""Кортеж - сборка аргументов - должен быть последним!"""
smm=0
for elt in dic5:
smm+=elt
return a*smm+b
func4(-1,2,0,3,6)
Traceback (most recent call last):
File "<pyshell#93>", line 1, in <module>
func4(-1,2,0,3,6)
TypeError: func4() takes from 1 to 2 positional arguments but 5 were given
func4(-1,2,{'a': 0},{'b': 3},{'c': 6})
Traceback (most recent call last):
File "<pyshell#94>", line 1, in <module>
func4(-1,2,{'a': 0},{'b': 3},{'c': 6})
TypeError: func4() takes from 1 to 2 positional arguments but 5 were given
a=90 # Числовой объект – не изменяемый тип
def func3(b):
b=5*b+67
func3(a)
SyntaxError: multiple statements found while compiling a single statement
a=90 # Числовой объект – не изменяемый тип
def func3(b):
b=5*b+67
func3(a)
SyntaxError: multiple statements found while compiling a single statement
a=90
def func3(b):
b=5*b+67
func3(a)
a
90
sps1=[1,2,3,4]
def func2(sps):
sps[1]=99
func2(sps1)
print(sps1)
[1, 99, 3, 4]
kort=(1,2,3,4)
func2(kort)
Traceback (most recent call last):
File "<pyshell#109>", line 1, in <module>
func2(kort)
File "<pyshell#105>", line 2, in func2
sps[1]=99
TypeError: 'tuple' object does not support item assignment
anfun1=lambda: 1.5+math.log10(17.23)
anfun1()
Traceback (most recent call last):
File "<pyshell#111>", line 1, in <module>
anfun1()
File "<pyshell#110>", line 1, in <lambda>
anfun1=lambda: 1.5+math.log10(17.23)
NameError: name 'math' is not defined. Did you forget to import 'math'?
import math
anfun1=lambda: 1.5+math.log10(17.23)
anfun1()
2.7362852774480286
anfun2=lambda a,b : a+math.log10(b)
anfun2(17,234)
19.369215857410143
anfun3=lambda a,b=234: a+math.log10(b)
anfun3(100)
102.36921585741014
def func5(diap,shag):
""" Итератор, возвращающий значения
из диапазона от 1 до diap с шагом shag"""
for j in range(1,diap+1,shag):
yield j
for mm in func5(7,3):
print(mm)
1
4
7
alp=func5(7,3)
print(alp.__next__())
1
print(alp.__next__())
4
print(alp.__next__())
7
print(alp.__next__())
Traceback (most recent call last):
File "<pyshell#128>", line 1, in <module>
print(alp.__next__())
StopIteration
glb=10
def func7(arg):
loc1=15
glb=8
return loc1*arg
res=func7(glb)
def func8(arg):
loc1=15
print(glb)
glb=8
return loc1*arg
res=func8(glb)
Traceback (most recent call last):
File "<pyshell#136>", line 1, in <module>
res=func8(glb)
File "<pyshell#135>", line 3, in func8
print(glb)
UnboundLocalError: cannot access local variable 'glb' where it is not associated with a value
glb
10
glb=11
def func7(arg):
loc1=15
global glb
print(glb)
glb=8
return loc1*arg
res=func7(glb)
11
glb
8
globals().keys()
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'uspeh', 'sravnenie', 'n', 'm', 'logistfun', 'v', 'w', 'z', 'slozh', 'b1', 'b2', 'b3', 'b4', 'q', 'inerz', 'sps', 'spsy', 'TT', 'yy', 'xx', 'matplotlib', 'plt', 'arr', 'fnkt', 'typ_fun', 'func', 'fun_arg', 'zz', 'b1234', 'qq', 'dic4', 'qqq', 'e1', 'dd2', 'qqqq', 'func4', 'a', 'func3', 'sps1', 'func2', 'kort', 'anfun1', 'math', 'anfun2', 'anfun3', 'func5', 'mm', 'alp', 'glb', 'func7', 'res', 'func8'])
locals().keys()
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'uspeh', 'sravnenie', 'n', 'm', 'logistfun', 'v', 'w', 'z', 'slozh', 'b1', 'b2', 'b3', 'b4', 'q', 'inerz', 'sps', 'spsy', 'TT', 'yy', 'xx', 'matplotlib', 'plt', 'arr', 'fnkt', 'typ_fun', 'func', 'fun_arg', 'zz', 'b1234', 'qq', 'dic4', 'qqq', 'e1', 'dd2', 'qqqq', 'func4', 'a', 'func3', 'sps1', 'func2', 'kort', 'anfun1', 'math', 'anfun2', 'anfun3', 'func5', 'mm', 'alp', 'glb', 'func7', 'res', 'func8'])
================================ RESTART: Shell ================================
glb
Traceback (most recent call last):
File "<pyshell#146>", line 1, in <module>
glb
NameError: name 'glb' is not defined
def func8(arg):
loc1=15
glb=8
print(globals().keys()) #Перечень глобальных объектов «изнутри» функции
print(locals().keys()) #Перечень локальных объектов «изнутри» функции
return loc1*arg
glb=11
hh=func8(glb)
dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'func8', 'glb'])
dict_keys(['arg', 'loc1', 'glb'])
'glb' in globals().keys()
True
def func9(arg2,arg3):
def func9_1(arg1):
loc1=15
glb1=8
print('glob_func9_1:',globals().keys())
print('locl_func9_1:',locals().keys())
return loc1*arg1
loc1=5
glb=func9_1(loc1)
print('loc_func9:',locals().keys())
print('glob_func9:',globals().keys())
return arg2+arg3*glb
kk=func9(10,1)
glob_func9_1: dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'func8', 'glb', 'hh', 'func9'])
locl_func9_1: dict_keys(['arg1', 'loc1', 'glb1'])
loc_func9: dict_keys(['arg2', 'arg3', 'func9_1', 'loc1', 'glb'])
glob_func9: dict_keys(['__name__', '__doc__', '__package__', '__loader__', '__spec__', '__annotations__', '__builtins__', 'func8', 'glb', 'hh', 'func9'])
znach=input('k1,T,k2,Xm,A,F,N=').split(',')
k1,T,k2,Xm,A,F,N=2,20,5,0,3,31,10
k1=float(znach[0])
import math
vhod=[]
for i in range(N):
vhod.append(A*math.sin((2*i*math.pi)/F))
Traceback (most recent call last):
File "<pyshell#160>", line 1, in <module>
for i in range(N):
NameError: name 'N' is not defined
T=float(znach[1])
k2=float(znach[2])
Xm=float(znach[3])
A=float(znach[4])
F=float(znach[5])
N=float(znach[6])
for i in range(N):
vhod.append(A*math.sin((2*i*math.pi)/F))
Traceback (most recent call last):
File "<pyshell#168>", line 1, in <module>
for i in range(N):
TypeError: 'float' object cannot be interpreted as an integer
N=int(znach[6])
for i in range(N):
vhod.append(A*math.sin((2*i*math.pi)/F))
vhod
[0.0, 0.6038955602659801, 1.1830675653399556, 1.713804645284377, 2.17437836168736, 2.5459327724842526, 2.813256396441241, 2.9654049729843344, 2.9961495215131584, 2.904231356598613]
def realdvig(xtt,kk1,TT,yti1,ytin1):
#Модель реального двигателя
yp=kk1*xtt #усилитель
yti1=yp+yti1 #Интегратор
ytin1=(yti1+TT*ytin1)/(TT+1)
return [yti1,ytin1]
SyntaxError: unindent does not match any outer indentation level
def realdvig(xtt,kk1,TT,yti1,ytin1):
#Модель реального двигателя
yp=kk1*xtt #усилитель
yti1=yp+yti1 #Интегратор
ytin1=(yti1+TT*ytin1)/(TT+1)
return [yti1,ytin1]
def tahogen(xtt,kk2,yti2):
#Модель тахогенератора
yp=kk2*xtt #усилитель
yti2=yp+yti2 #интегратор
return yti2
def nechus(xtt,gran):
#зона нечувствит
if xtt<gran and xtt>(-gran):
ytt=0
elif xtt>=gran:
ytt=xtt-gran
elif xtt<=(-gran):
ytt=xtt+gran
return ytt
SyntaxError: expected an indented block after 'if' statement on line 3
def nechus(xtt,gran):
#зона нечувствит
if xtt<gran and xtt>(-gran):
ytt=0
elif xtt>=gran:
ytt=xtt-gran
elif xtt<=(-gran):
ytt=xtt+gran
return ytt
yi1=0;yin1=0;yi2=0
vyhod=[]
for xt in vhod:
xt1=xt-yi2 #отрицательная обратная связь
[yi1,yin1]=realdvig(xt1,k1,T,yi1,yin1)
yi2=tahogen(yin1,k2,yi2)
yt=nechus(yin1,Xm)
vyhod.append(yt)
print('y=',vyhod)
SyntaxError: unexpected indent
print('y=',vyhod)
print('y=',vyhod)
y= [0.0, 0.0575138628824743, 0.19757451809698162, 0.37271445071909315, 0.44764431066344834, 0.24935818305562138, -0.3024162461562951, -1.0323481238173855, -1.4374313649904746, -0.8573979371237693]