程序工作在Python 2.7中,但不是Python 3.3(语法对于两者兼容) [英] Program Works in Python 2.7, but not Python 3.3 (Syntax is compatible for both)

查看:458
本文介绍了程序工作在Python 2.7中,但不是Python 3.3(语法对于两者兼容)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此,我在 nums.py 中定义了函数整数(函数,n = 1000,start = 0,stop = 100)
$ $ $ $ $ $ $ $ $ $ $ $ $ $ $> def积分函数n = 1000开始= 0停止= 100
返回从'n'开始到停止的函数的积分'
increment,num,x = float(stop - start)/ n,0,开始
,而x < ; =停止:
num + = eval(函数)
如果x> = stop:break
x + =增量
返回增量* num
输入来获取输入()
然后返回它。所以,我有:

  def main():
from nums import integral#导入我在我自己的'nums'模块
f,n,a,b = get_input()
result = integral(f,n,a,b)
msg =\\\
+ f +is:+ str(result)
print(msg)
$ b $ def get_input():
f = str(input(Function(in quotes,eg:'x ^ 2';使用'x'作为变量):))。replace('^','**')
#上面的代码使得它可以被Python评估,并且在一行中获得输入
n = int(输入(矩形数(输入为整数,例如:1000):))
a = int(输入(起始点(输入为整数,例如:0): ))
b = int(输入(End-Point(输入为整数,例如:100):))
返回f,n,a,b

main ()

在Python 2.7中运行时,它工作正常:

 >>> 
函数(用引号括起来,例如:'x ^ 2';用'x'作为变量):'x ** 2'
矩形数(输入为整数,例如:1000): 1000
起点(以整数形式输入,例如:0):0
终点(输入为整数,例如:100):100

x ** 2是:333833.5

然而,在Python 3.3中(我的老师坚持使用它)

 积分函数中产生了一个错误> Traceback(最近一次调用最后):
文件D:\ my_stuff\Google Drive \ documents \SCHOOL\Programming\Python\Programming Class\integration.py,第20行,在< module>
main()
文件D:\my_stuff\Google Drive\documents\SCHOOL\Programming\Python\Programming Class\integration.py,第8行
result = integral(f,n,a,b)
在整数
中的文件D:\my_stuff\Google Drive \Modules\\\
ums.py,第142行num + = eval(function)
TypeError:不支持的操作数类型(s),用于+ =:'int'和'str'

此外,整数本身(在Python 3.3中)工作正常:

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

因此,我相信故障在我的课程我的课程...任何和所有的帮助表示赞赏。感谢:)

解决方案

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



由于您使用公式输入的报价标记,您会遇到麻烦。在Python 2上运行时键入'x ** 2'(带引号)作为公式时,文本将获得 eval 输入函数中输入$ c> ed,然后得到一个不带引号的字符串作为结果。这是有效的。



当你给Python 3的输入函数赋予相同的字符串时,它不会执行 eval ,所以引号保持不变。当你以后 eval 这个公式作为你的积分计算的一部分时,你得到字符串 x ** 2 (没有任何引号)作为结果,而不是 x 的平方的平方。当你尝试字符串< 0 。



为了解决这个问题,我建议使用just一个版本的Python,或者将下面的代码放在文件的顶部,以获得两种版本中的Python 3样式 input

 #确保从输入中得到Python 3的语义,即使在Python 2中
try:
input = raw_input
除了NameError:
pass

然后只需输入您的公式而不用引号,它应该可以正常工作。


So I have the function integral(function, n=1000, start=0, stop=100) defined in 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

However, my teacher (for my Programming class) wants us to create a separate program that gets the input using input() and then returns it. So, I have:

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()

When run in Python 2.7, it works fine:

>>> 
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

However, in Python 3.3 (which my teacher insists we use), it raises an error in my integral function, with the same exact input:

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'

In addition, integral by itself (in Python 3.3) works fine:

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

Because of that, I believe the fault is in my program for my class... Any and all help is appreciated. Thanks :)

解决方案

The issue you're running into is that input works differently in Python 2 and Python 3. In Python 3, the input function works like the raw_input does in Python 2. Python 2's input function is equivalent to eval(input()) in Python 3.

You're getting into trouble because of the quoteation marks you're typing with the formula. When you type 'x**2' (with the quotes) as your formula when running on Python 2, the text gets evaled in the input function and you get a string with no quotation marks as the result. This works.

When you give the same string to Python 3's input function, it doesn't do an eval, so the quotation marks remain. When you later eval the formula as part of your integral calculation, you get the string x**2 (without any quotation marks) as the result, not the value of x squared. This results in an exception when you try the string to 0.

To fix this, I suggest either using just one version of Python, or putting the following code at the top of your file to get a Python 3 style input in both versions:

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

Then just type in your formula without quotation marks and it should work correctly.

这篇关于程序工作在Python 2.7中,但不是Python 3.3(语法对于两者兼容)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆