0

だから私はで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

integralただし、Python 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単独で (Python 3.3 で) 正常に動作します。

>>> from nums import integral
>>> integral('x**2')
333833.4999999991

そのため、私のクラスのプログラムに問題があると思います...どんな助けも大歓迎です。ありがとう :)

4

1 に答える 1

4

発生している問題はinput、Python2とPython3では動作が異なることです。Python3では、input関数はPython2と同じようにraw_input動作します。Python2のinput関数はPython3と同等eval(input())です。

数式で入力している引用符が原因で問題が発生しています。'x**2'Python 2で実行しているときに数式として(引用符を使用して)入力すると、関数でテキストが編集evalinputれ、結果として引用符のない文字列が取得されます。これは機能します。

Python 3のinput関数に同じ文字列を指定すると、は実行されないevalため、引用符は残ります。後でeval積分計算の一部として数式を実行すると、結果として、 2乗x**2の値ではなく、文字列(引用符なし)が取得されます。xこれにより、文字列を。にしようとすると例外が発生します0

これを修正するには、Pythonの1つのバージョンのみを使用するか、ファイルの先頭に次のコードを配置してinput、両方のバージョンでPython3スタイルを取得することをお勧めします。

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

次に、引用符なしで数式を入力するだけで、正しく機能するはずです。

于 2013-02-09T01:02:27.827 に答える