Home > OS >  if else statement in while loop while making sure the while loop keeps running
if else statement in while loop while making sure the while loop keeps running

Time:06-27

Im trying to make a countdown timer with the feature to reset/stop/pause/resume. so with my limited newbie logic I thought having an if/elif/else statement to check for user input letter within the while loop while the loop continues executing would be great. however for some reason it keeps stopping. how do I make this work?

code:

 import time
 import datetime

 def timeinput():
  # Inputs for hours, minutes, seconds on timer
  h = input("Enter the time in hours: ")
  m = input("Enter the time in minutes: ")
  s = input("Enter the time in seconds: ")
  countdown(int(h), int(m), int(s))

# Create class that acts as a countdown
 def countdown(h, m, s):
  # Print options for user to do
  print("Press w to reset \nPress s to stop \nPress a to pause \nPress d to resume")

  # Calculate the total number of seconds
  total_seconds = h * 3600   m * 60   s

  # While loop that checks if total_seconds reaches zero
  # If not zero, decrement total time by one second
  while total_seconds > 0:

    # Timer represents time left on countdown
    timer = datetime.timedelta(seconds = total_seconds)
    
    # Prints the time left on the timer
    print(timer, end="\r")
    
    # Delays the program one second
    time.sleep(1)

    # Reduces total time by one second
    total_seconds -= 1
    user=input()
    
    if user=="w":
      total_seconds=0
      print("Timer will now reset")
      timeinput()

   print("Bzzzt! The countdown is at zero seconds!")

  timeinput()

result: outcome of code

as you can see its stopping at 20 seconds instead of continuing the loop. i want it to be like the countdown keeps going but if the user presses w during the countdown it resets.

(ps if my code looks like it has wrong indentations, i am sorry coz its my first time on stack overflow and copying the code didn't go too well)

CodePudding user response:

Soo, I'm also kinda new to programming and python so I don't exactly how to make a timer with that functionality. What is happening is that when you use the input() function the code stops and waits for the user input.

I know you can use some libraries, like pygame, in order to check for user input inside the loop without stopping it, but without one I'm not sure how to do it.

You can also use the module keyboard, that comes inside python, and I think is great for the problem you shared. Check this post How to detect key presses?

CodePudding user response:

The command input() is blocking. It waits until it get something from the console. Maybe take a look at this post and try to implement a non blocking version of input. Non-blocking console input?

  • Related