你能让这段代码在Python2.7和3.5中运行吗

你能让这段代码在Python2.7和3.5中运行吗,python,python-2.7,python-3.x,Python,Python 2.7,Python 3.x,我有在Python3.5中运行的代码,但在Python2.7中需要它。因为在学校系统中,我只能写3.5,只能写2.7。该程序用herron原理计算平方根。对不起,我英语不好 #y = number from that you want the square root #a = first side of the square #b = second side of the square #m = middle of both numbers #x = a*b/m #i = number of

我有在Python3.5中运行的代码,但在Python2.7中需要它。因为在学校系统中,我只能写3.5,只能写2.7。该程序用herron原理计算平方根。对不起,我英语不好

#y = number from that you want the square root 
#a = first side of the square
#b = second side of the square
#m = middle of both numbers
#x = a*b/m
#i = number of Iteration
#c = number of maked Iterations
import math

c = 0
m = 0
x = 0

y = int(input("Number from that you want the square root(only numbers without a comma):"))
i = int(input("Number of Iterationen: "))


a = y/2
b = 2

print("first side of the square",a)
print("second side of the square", b)


while i > 0:
    m = (a+b)/2
    x = (a*b)/m
    a = m
    b = x
    print("first side of square after",c,"Iterations is",a)
    print("second side of square after",c,"Iterations is",b)
    i = i-1
    c = c+1

print("Final",a)

print("calculate per command",math.sqrt(y))

将此行添加到程序顶部:

from __future__ import division, print_function
然后它将在2.7下运行,并给出与运行3.5时相同的答案


“但是,如果您输入一个Python表达式而不是一个数字,它将在Python 2中执行,而在Python 3中会出现一个错误,因为input()在Python 2中和Python 3中的含义不同。”——

您可以使用Rob解决方案,或者您可以将每个
print()
更改为
print
(带空格)
e、 g.改变:

print("calculate per command",math.sqrt(y))
进入:

您应该将
input
功能更改为
raw\u input


(虽然它仍然可以正常工作,但不会出现所有错误:)

@Rob对于来自“未来”导入部门的“打印”功能行的“代码”的看法完全正确

但是,如果您还希望具有等效的
输入
功能,您可以使用:

try:
    input = raw_input  # Py2
except NameError:
    pass               # Py3
或与:


该程序已经在2.7版中运行。您到底想要什么?可以编写同时在Python2.7和Python3.5上运行的代码。一种方法是使用
6个
库和两个
\uuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuuu导入。我认为
从导入部分,打印函数
或将
(a+b)/2
更改为
(a+b)/2.
就足够了。@Robᵩ 该程序在Python2.7中运行。
input()
调用将执行意外操作,因为它们将计算您输入的所有Python代码。print语句将在Python 2中打印元组,这也是不需要的。@mseifer此外,需要使用来自uuu future\uuuu导入print\u函数的
,以及在检测到Python 2时设置
input=raw\u input
的逻辑。但是,如果输入一个Python表达式而不是一个数字,它将在Python 2中执行,然而,在Python3中会出现一个错误,因为
input()
在Python2和3中有不同的含义。@SvenMarnach-True。我找不到合适的词语来表达,所以我会偷你的。
try:
    input = raw_input  # Py2
except NameError:
    pass               # Py3
from six.moves import input