python - 打印 Python 上的额外新行
问题描述
我有一个有趣的小功能,可以用星号打印菱形。它看起来像这样:
from time import sleep
while True:
whitespaces_count = 0
dots_count = 8
for _ in range(0, 5):
print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
whitespaces_count += 2
dots_count -= 2
sleep(0.15)
whitespaces_count = 6
dots_count = 2
for _ in range(0, 4):
print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
whitespaces_count -= 2
dots_count += 2
sleep(0.15)
print("\n")
它工作正常,但是,在每个print
命令之后,它都会打印额外的空白行,因此输出如下所示:
********
*** ***
** **
* *
* *
** **
*** ***
********
但我希望它看起来像这样:
********
*** ***
** **
* *
* *
** **
*** ***
********
我在做什么错?
解决方案
你的问题不是print
,而是你的第一个循环运行了一个额外的时间,打印没有点,所有的空白。将其更改为循环range(4)
而不是range(5)
多余的行消失。
旁注:您应该真正利用循环本身来确定要使用多少个星号和空格print
;您正在使用 arange
来决定要运行多少个循环,但它可以执行双重任务,从而允许这样做(最低限度的固定代码):
whitespaces_count = 0
dots_count = 8
for _ in range(4):
print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
whitespaces_count += 2
dots_count -= 2
sleep(0.15)
成为:
for whitespaces_count in range(0, 8, 2):
dots_count = 8 - whitespaces_count
print("*"*(dots_count//2)+" "*whitespaces_count+"*"*(dots_count//2))
sleep(0.15)
或者让循环做更多的工作,将更多的工作推给性能优于手写代码的内置程序(并dots_count
参考每边的点数):
for whitespaces_count, dots_count in zip(range(0, 8, 2), range(4, 0, -1)):
print("*"*dots_count + " "*whitespaces_count + "*"*dots_count)
sleep(0.15)
推荐阅读
- javascript - 使用 vueJS 有条件地设置 href 属性
- angular - 如何在 Visual Studio Code 中仅调试编写的代码?
- javascript - reCAPTCHA 和 JS 表单验证
- java - 使用 spring data-jpa 映射本机查询结果集的更好方法
- python - python subprocess.Popen 正在创建重复文件并写入重复文件而不是原始文件
- amazon-web-services - 我们可以从正在运行的 EC2 实例中删除安全组吗?
- powershell - Powershell ArrayList 神奇地插入一个零
- excel - 如何使用 Excel 在 VBA 中禁用 ListView 控件中的箭头键
- sql - 如何在sql中打印钻石
- java - 什么数据类型