【问题标题】:Why is the while loop here printing in the same line?为什么这里的while循环打印在同一行?
【发布时间】:2020-05-03 20:51:45
【问题描述】:

以下说明了 Python 中的一个示例 while 循环:

count = 0
print('Starting')
while count < 10:
   print(count, ' ', end='') # part of the while loop
   count += 1 # also part of the while loop
print() # not part of the while loop
print('Done')

运行这个例子的结果是:

Starting
0 1 2 3 4 5 6 7 8 9
Done

如果代码再次循环并且 print() 在第二个循环中重新运行,我不明白为什么 while 循环会在同一行打印。我期待数字以不同的行打印。我对 while 循环的理解搞砸了什么?

【问题讨论】:

  • 我正在从一本书中学习 Python,我还没有达到那么远,这是一个解释 while 循环的例子,它让我对 print 函数感到困惑。但蜥蜴比尔帮了大忙。 :)

标签: python python-3.x while-loop printing


【解决方案1】:

默认情况下,Python 的print 函数的end 参数是换行符。这就是为什么在循环中打印通常会在单独的行上打印值。 (将您自己的换行符附加到您打印的每条消息中会很乏味,因此在大多数情况下,默认值是有意义的。)

通过传递end='',您将覆盖默认值,以便每个值都打印在同一行上。

请参阅print function documentation

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-18
    • 1970-01-01
    • 1970-01-01
    • 2015-06-12
    • 1970-01-01
    • 2022-11-02
    • 1970-01-01
    相关资源
    最近更新 更多