【发布时间】:2013-02-09 00:36:05
【问题描述】:
所以我在nums.py 中定义了函数integral(function, n=1000, start=0, stop=100):
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() 获取输入,然后返回它。所以,我有:
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()
在 Python 2.7 中运行时,它运行良好:
>>>
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
但是,在 Python 3.3(我的老师坚持我们使用它)中,它会在我的 integral 函数中引发错误,并且输入完全相同:
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 本身(在 Python 3.3 中)也可以正常工作:
>>> from nums import integral
>>> integral('x**2')
333833.4999999991
因此,我相信问题出在我的课程计划中……感谢您提供任何帮助。谢谢:)
【问题讨论】:
标签: function python-3.x python-2.7