2017-08-06 122 views
0

我正在製作一個簡單的python程序作爲rubiks立方體計時器。它使用點擊庫,但我不認爲這與問題有關。當我完成程序並運行循環時,它不會再運行我的程序。Python循環錯誤

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) 

所以每次我打了會發生什麼Ÿ它只是去,如果塊。爲什麼會這樣,我該如何解決它?

回答

1

if鍵==''和newKey ==''行要求您在點擊y後點擊空格。示例流程:'y',空格,空格'n'。如果你點擊y,那麼跳過這些塊,然後返回到y/n語句。

0

我測試了你的程序,它工作正常。唯一的問題是,一旦你點擊「y」,沒有任何東西可以告訴你程序已經重新啓動。

嘗試移動print "Press the spacebar to start the timer"以在while stillTiming內循環之後。你進入後y由於if key == ' ':if newKey == ' ':

目前的邏輯是難以遵循你的代碼

0

你的程序是尋找空間。我建議你將你的代碼分解成多個函數塊。這樣它就更具可讀性,並且不太可能遇到像這樣的邏輯錯誤。下面是一個例子:

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()