使用Python 2.7函数返回的值在同一行上打印
使用,我们可以在同一行上写入多个打印语句使用Python 2.7函数返回的值在同一行上打印,python,python-2.7,Python,Python 2.7,使用,我们可以在同一行上写入多个打印语句 print 'hello', print 'world' 问题:打印函数返回的值时,如何将多个函数调用返回的值打印在同一行上 以下代码在单独的行上打印每个函数返回的值: import math def square_root(a): x = a e = 0.0000001 while True: print x y = (x + a/x)/2 if( abs(x - y
print 'hello',
print 'world'
问题:打印函数返回的值时,如何将多个函数调用返回的值打印在同一行上
以下代码在单独的行上打印每个函数返回的值:
import math
def square_root(a):
x = a
e = 0.0000001
while True:
print x
y = (x + a/x)/2
if( abs(x - y) < e ):
return x
x = y
def test_square_root():
for i in range(1,10):
print float(i),
print square_root(float(i)),
print math.sqrt(float(i)),
print abs( square_root(float(i)) - math.sqrt(float((i))) )
test_square_root()
在test_square_root函数的最后一个print语句中添加逗号:
print abs( square_root(float(i)) - math.sqrt(float((i))) ),
或者,您可以从函数中生成每个项目,而不是打印它:
def test_square_root():
for i in range(1,10):
yield float(i)
yield square_root(float(i))
yield math.sqrt(float(i))
yield abs( square_root(float(i)) - math.sqrt(float((i))) )
for item in test_square_root():
print item,
在test_square_root函数的最后一个print语句中添加逗号:
print abs( square_root(float(i)) - math.sqrt(float((i))) ),
或者,您可以从函数中生成每个项目,而不是打印它:
def test_square_root():
for i in range(1,10):
yield float(i)
yield square_root(float(i))
yield math.sqrt(float(i))
yield abs( square_root(float(i)) - math.sqrt(float((i))) )
for item in test_square_root():
print item,
移除
print x
在你的功能里面。这就是导致线路过早结束的原因。移除
print x
在你的功能里面。这就是导致行过早结束的原因。问题是以平方根表示的打印语句,而不是该语句。问题是以平方根表示的打印语句,而不是该语句。