你可以使那个代码从3.5运行在python 2.7中

时间:2017-01-12 19:39:19

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

我有在python 3.5中运行的代码,但我需要它用于python 2.7。因为在学校系统上只运行2.7而且我只能写3.5。程序用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))

3 个答案:

答案 0 :(得分:2)

将此行添加到程序的顶部:

from __future__ import division, print_function

然后它将在2.7下运行并给出与您运行3.5相同的答案。

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

答案 1 :(得分:2)

@Rob对于from __future__ import division, print_function行肯定是正确的。

但如果您还想使用等效的input功能,可以使用:

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

six

from six.moves import input

答案 2 :(得分:0)

您可以使用Rob解决方案,也可以将每print()更改为print(带空格)
例如变化:

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

分为:

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

您应该将input功能更改为raw_input
(虽然它仍然可以正常工作,但只是赢得了所有错误:https://docs.python.org/2/library/functions.html#input