題目:使用python語言寫一個無窮波浪,然後按下ctrl + c停止
********
********
********
********
********
********
********
********
********
以下為我的程式碼:
import time, sys
indent = 0 #how many space to indent
indentIncreasing = True
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 space:
indent = indent - 1
if indent == 0:
#change direction:
indentIncreasing = True
except KeyboardInterrupt:
sys.exit()
用我的程式碼輸出為寬八顆星,長無窮大的長方形,
請問是哪裡出錯了呢?找了很久還是找不到問題...
謝謝
程式碼是不是排版有排錯?
if indentIncreasing:
#increase the number of spaces:
indent = indent + 1
if indent == 20:
#change direction
indentIncreasing = False
上面這段程式碼應該縮排進去變成以下
import time, sys
indent = 0 #how many space to indent
indentIncreasing = True
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 space:
indent = indent - 1
if indent == 0:
indentIncreasing = True
except KeyboardInterrupt:
sys.exit()
寫了個簡化版的,你觀察看看.當然這個並不是最好的.方法有很多,你可以多嘗試.
在做無窮的版本之前,可以先做簡化版本的,方便觀察.
#!/usr/bin/env python3
indent = 0
leftright = 1
for i in range(60):
print(' ' * indent, end='')
print('*')
if indent >= 20:
leftright = -1
if indent <= 0:
leftright = 1
indent = indent + leftright
indent = 9
increasing = -1
bound = abs(indent) + abs(increasing)
while True:
if abs(indent + increasing) >= bound:
increasing = -increasing
print(" " * abs(indent) + "****")
indent += increasing
這樣就好了吧...