python-两个print命令输出内容显示在同一行

print函数

在python2中,print只是一个关键字,但是在3.x中,print 是一个函数。

定义:
print(*objects, sep=' ', end='\n', file=sys.stdout);

参数:
*objects-复数,一次可输出多个对象,用‘,’分开
sep – 用来间隔多个对象,默认值是一个空格。
end --用来设定以什么结尾。默认值是换行符 \n,可以换成其他字符串。
file – 要写入的文件对象。

无返回值。

所以想要把多个输出放在同一行,只需要设定end的内容即可。
一个例子:

print ("hello", end=" ")
print("world")

输出结果为

hello world

再比如输出斐波那契数列(<1000):

a, b = 0, 1
while a <1000:
    print(a, end = ',')
    a, b = b, a+b
print('...')    

输出结果为

0,1,1,2,3,5,8,13,21,34,55,89,144,233,377,610,987,...

猜你喜欢

转载自blog.csdn.net/weixin_40406018/article/details/88779449