Click here to Skip to main content
15,902,275 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Im trying to format the output for this calculation but it keeps giving my an error for the line where Im formatting i saying i is undefined, Im guessing its something to do with i being used in the definition but Im not entirely sure and also not sure how to get it to recognize it.

There could be a problem with my n, Im trying to get it to double each time in the range to 512 so not sure if thats the problem but Im also working on trying to figure that out and not sure if thats affecting i

What I have tried:

Theres some more code before this just getting input and defining more definitions but I dont think its relevant to the problem.

Python
def my_trap(a,b,n):
    sum= 0
    h= (b-a)/n #width of each interval
    for i in range(1,n+1):
        x=a+i*h
        sum=sum+2*f(x)
        return (h/2)*(sum+f(a)+f(b))
   
print('\nThis programme estimates the integral of the function sin(x) in the \
          integral [a,b] using the trapezoidal method.')

a=getinput('a')
b=getinput('b')

n=512/2
n=n*2

error= analytical(a,b)-my_trap(a,b,n)

print('{0:<20}'.format(i),'|'\
      '{0:<20.5f}'.format(my_trap(a,b,n)), '|', \
      '{0:<20.5f}'.format(error))
Posted
Updated 26-Mar-20 13:33pm
v3
Comments
Richard MacCutchan 27-Mar-20 4:29am    
The return statement in my_trap is wrongly indented.
CiaraMc96 27-Mar-20 6:57am    
Thank you, fixed that now but it still isnt recognizing i, how do I make it accessible elsewhere with what phil said?
phil.o 27-Mar-20 10:06am    
i being only accessible and assigned inside the loop, you have to create another variable in the scope you wish to use it. Then, in the loop, assign the value of i to that broader variable. BUT: you will only be able to get the last value of i, unless you have a mechanism to exit the loop early. If you don't exit the loop early, then you can assume the last value of i will always be n.

1 solution

Variable i is scoped to the for loop; this means that you can only use it inside the loop, and it will be unaccessible from anywhere else.

Please always enclose your code block between <pre> tags; especially for python, where indentation is of utmost importance, we need to have the exact indentation of the code.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900