I am making a simple python program to work as a rubiks cube timer. It uses the click library but I don't think that has to do with the problem. When I finish the program and run through the loop, it does not run my program again.
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
And this is what happens in my terminal
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)
So everytime I hit y it just goes to that if block. Why is this and how can I fix it?
3 Answers 3
The if key == ' ' and newKey == ' ' lines require you to hit space after you hit y. Example flow: 'y', space, space, 'n'. If you instead hit y, then those blocks are skipped, taking you back to the y/n statement.
Comments
I tested your program, and it works fine. The only issue is that, once you hit "y", there is nothing that tells you that the program has restarted.
Try moving print "Press the spacebar to start the timer" to be right after the inner while stillTiming loop.
Comments
your program is looking for space after you enter y due to if key == ' ': and if newKey == ' ':
the current logic is hard to follow with your code. I would suggest you break your code into blocks of functions. That way it is more readable and you will less likely run into logical errors like this. Here is an example below:
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()