그래서 내가 integral(function, n=1000, start=0, stop=100)
이 nums.py
에 정의 된 함수가 (구문 모두 호환) :프로그램은 파이썬 2.7에서 작동,하지만 파이썬 3.3
def integral(function, n=1000, start=0, stop=100):
"""Returns integral of function from start to stop with 'n' rectangles"""
increment, num, x = float(stop - start)/n, 0, start
while x <= stop:
num += eval(function)
if x >= stop: break
x += increment
return increment * num
그러나, (내 프로그래밍 클래스) 선생님이 우리가 원하는을 별도의 프로그램을 작성하여 input()
을 사용하여 입력을 얻은 다음이를 리턴하십시오. 그래서, 내가 가진 : 파이썬 2.7에서 실행하면 잘 작동
def main():
from nums import integral # imports the function that I made in my own 'nums' module
f, n, a, b = get_input()
result = integral(f, n, a, b)
msg = "\nIntegration of " + f + " is: " + str(result)
print(msg)
def get_input():
f = str(input("Function (in quotes, eg: 'x^2'; use 'x' as the variable): ")).replace('^', '**')
# The above makes it Python-evaluable and also gets the input in one line
n = int(input("Numbers of Rectangles (enter as an integer, eg: 1000): "))
a = int(input("Start-Point (enter as an integer, eg: 0): "))
b = int(input("End-Point (enter as an integer, eg: 100): "))
return f, n, a, b
main()
:
>>>
Function (in quotes, eg: 'x^2'; use 'x' as the variable): 'x**2'
Numbers of Rectangles (enter as an integer, eg: 1000): 1000
Start-Point (enter as an integer, eg: 0): 0
End-Point (enter as an integer, eg: 100): 100
Integration of x**2 is: 333833.5
을하지만, 파이썬 3.3 (선생님은 우리가 사용 주장하는)에, 내 integral
에 오류가 발생합니다 같은 정확한 입력과 기능 : (파이썬 3.3) 자체 또한
Traceback (most recent call last):
File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\Programming Class\integration.py", line 20, in <module>
main()
File "D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\Programming Class\integration.py", line 8, in main
result = integral(f, n, a, b)
File "D:\my_stuff\Google Drive\Modules\nums.py", line 142, in integral
num += eval(function)
TypeError: unsupported operand type(s) for +=: 'int' and 'str'
, integral
잘 작동합니다 :
>>> from nums import integral
>>> integral('x**2')
333833.4999999991
덕분에 내 잘못이 내 수업에 있다고 생각합니다. 모든 도움이 인정됩니다. 감사합니다 :)