2017-08-06 5 views
0

rubiksキューブタイマーとして動作するように単純なPythonプログラムを作っています。それはクリックライブラリを使用しますが、私は問題と関係しているとは思わない。プログラムを終了してループを実行すると、プログラムが再実行されません。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 

は、これはそれだけで、もしブロックに行くのy

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