Python循环错误
我正在制作一个简单的python程序,用作rubiks多维数据集计时器。它使用点击库,但我认为这与问题无关。当我完成程序并运行循环时,它不会再次运行我的程序Python循环错误,python,Python,我正在制作一个简单的python程序,用作rubiks多维数据集计时器。它使用点击库,但我认为这与问题无关。当我完成程序并运行循环时,它不会再次运行我的程序 import click import time import sys print("CubeTimer 1.0") print("Press the spacebar to start the timer") stillTiming = True while stillTiming: key = click.getchar(
import click
import time
import sys
print("CubeTimer 1.0")
print("Press the spacebar to start the timer")
stillTiming = True
while stillTiming:
key = click.getchar()
if key == ' ':
print('starting timer')
# start timer
t0 = time.time()
newKey = click.getchar()
if newKey == ' ':
# stop timer
print('stopping timer')
t1 = time.time()
total = t1 - t0
print(total)
elif key =='esc':
sys.exit()
print('Time again? (y/n)')
choice = click.getchar()
if choice == 'y':
stillTiming = True
else:
stillTiming = False
这就是在我的终端发生的事情
CubeTimer 1.0
Press the spacebar to start the timer
starting timer
stopping timer
2.9003586769104004
Time again? (y/n)
Time again? (y/n)
Time again? (y/n)
Time again? (y/n)
Time again? (y/n)
Time again? (y/n)
Time again? (y/n)
Time again? (y/n)
所以每次我打y的时候,它就转到那个if块。这是为什么?我如何修复它?if key==''和newKey=''行要求您在点击y后点击空格。示例流:“y”,空格,空格,“n”。如果改为点击y,则跳过这些块,返回y/n语句。我测试了您的程序,它工作正常。唯一的问题是,一旦你点击“y”,没有任何信息告诉你程序已经重新启动
尝试移动
print“按空格键启动计时器”
以紧跟在内部之后,同时仍在计时循环。由于if key='':
和if newKey='':
您的代码很难遵循当前的逻辑。我建议您将代码分解为函数块。这样,它更具可读性,您将不太可能遇到这样的逻辑错误。下面是一个例子:
import click
import time
import sys
startTimer() #call startTimer function
def startTimer():
print("CubeTimer 1.0")
continueTiming = True
while continueTiming: #this will continue calling timing function
timing()
print('Time again? (y/n)')
choice = click.getchar() #here we decide if we want to try again
if choice == 'y':
continueTiming = True
else:
continueTiming = False
def timing():
print("Press the spacebar to start the timer")
key = click.getchar()
if key == ' ':
print('starting timer')
# start timer
t0 = time.time()
newKey = click.getchar()
if newKey == ' ':
# stop timer
print('stopping timer')
t1 = time.time()
total = t1 - t0
print(total)
elif key =='esc':
sys.exit()