程序在Python 2.7中运行,但不在Python 3.3中运行(语法与两者兼容)

时间:2013-02-09 00:36:05

标签: function python-3.x python-2.7

所以我在integral(function, n=1000, start=0, stop=100)中定义了函数nums.py

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

正因为如此,我相信错误在我班上的课程中...任何和所有帮助都表示赞赏。谢谢:))

1 个答案:

答案 0 :(得分:4)

您遇到的问题是input在Python 2和Python 3中的工作方式不同。在Python 3中,input函数的工作方式类似于Python 2中的raw_input。 Python 2的input函数相当于Python 3中的eval(input())

由于您使用公式输入的引号,您遇到了麻烦。当您在Python 2上运行时键入'x**2'(带引号)作为公式时,文本在eval函数中得到input,您将得到一个没有引号的字符串作为结果。这很有效。

当您为Python 3的input函数提供相同的字符串时,它不会执行eval,因此保留引号。如果稍后eval公式作为积分计算的一部分,则会得到字符串x**2(不带任何引号)作为结果,而不是x平方的值。当您尝试将字符串转换为0时会出现异常。

要解决此问题,我建议您只使用一个版本的Python,或者将以下代码放在文件的顶部,以便在两个版本中获得Python 3样式input

# ensure we have Python 3 semantics from input, even in Python 2
try:
    input = raw_input
except NameError:
    pass

然后只需输入没有引号的公式,它就可以正常工作。