我试图在他们自己的功能中定义r2和r1,我已经将它返回并打印出来,所以我知道它正式位于main()中。问题是当它试图在矩形()中获取变量时,它会给出一个r2未定义的错误。
我的教授告诉我们,如果你的基函数中定义了一个变量(在全局空间之外),那么它就可以在基函数之外的函数中读取。
我试图做的事情是不可行还是我只是错误地攻击它?我们不允许使用全局变量或代码的全局空间。以下是我试图运行的代码。
def f1(x):
return 5*x**4 + 3*x**3 - 10*x + 2
def rectangles():
step = (r2-r1)/shapes
total = 0
start = step + r1
for y in range(shapes):
res = f1(start)
start = step + start
total = total + res*step
print("The rectangle approximation is " + str(total))
def trapezoids():
step = (r2-r1)/shapes
total = 0
start = r1
for y in range(shapes):
m1 = f1(start)
total = step * (m1+f1(step+start))/2 + total
start = step + start
print("The trapezoid approximation is " + str(total))
def r1get():
ii=True
while ii == True:
r1 = input("Enter the start of the range: ")
try:
val = float(r1)
ii = 0
except ValueError:
ii== True
r1 = float(r1)
return r1
def r2get():
ii=True
while ii == True:
r2 = input("Enter the end of the range: ")
try:
val = float(r2)
ii = 0
except ValueError:
ii== True
r2 = float(r2)
return r2
#def mode():
def numshapes():
ii = True
while ii == True:
shapes = input("Enter how many shapes you want to use in your approximation: ")
try:
val = int(shapes)
shapes = int(shapes)
if shapes>=0:
ii=0
else:
ii=True
except ValueError:
ii== True
return shapes
def main():
#mode()
#print(mode)
r1 = r1get()
r2 = r2get()
shapes = numshapes()
rectangles()
trapezoids()
ma
在()