以下示例说明了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循环的理解弄乱了什么?
默认情况下,Python的end
函数的print
参数是换行符。这就是循环打印通常会在单独的行上打印值的原因。 (将您自己的换行符附加到您打印的每条消息上都是很麻烦的,因此在大多数情况下,默认设置是有意义的。)
通过传递end=''
,您将覆盖默认值,以便每个值都打印在同一行上。