在《用 Python 自动处理无聊的事情》的第 3 章中,这本书要求您复制一个打印锯齿形星号图案的脚本。我复制了代码,但一定做错了什么,因为星号不会曲折,它们只是打印一块星号。
import time, sys
indent = 0 # How many spaces to indent
indentIncreasing = True # Whether the indentation is increasing or not.
try:
while True: # The main program loop
print(' ' * indent, end='')
print('********')
time.sleep(0.1) # Pause for 1/10 of a second
if indentIncreasing:
# Increase the number of spaces
indent = indent + 1
if indent == 20:
# Change Direction:
indentIncreasing = False
else:
# Decrease the number of spaces
indent = indent - 1
if indent == 0:
# Change direction:
indentIncreasing = True
except KeyboardInterrupt:
sys.exit()
如何让星号打印出锯齿形图案?
你非常接近,你有一个缩进问题。既然您正在学习,我不想给您完整的代码,但是,当您检查
if indentIncreasing:
时,else
需要与之对齐。你的 else
距离太远了,没有与原来的 if
对齐
if indentIncreasing:
# Increase the number of spaces
else:
# Decrease the number of spaces