Search code examples
pythontimerconditional-statementscountdown

How to solve this User Input problem in countdown timer Python3.9.4


I have a countdown timer that asks for user input for a "lucky number". Once that number is entered, the timer starts to countdown and prints out a simple message.

My problem is that if the user input is not a number, I get the "Traceback (most recent call last) ValueError: invalid literal for int() with base 10"

I understand what that means, but I don't know how to make it bypass this condition so that the user input can be anything (not just numbers) and not give me an error, but rather just print out a message that would just say; "continue without lucky number"..-and just continue with the rest of the script..

Any help would be highly appreciated. Thanks.

Here is a screenshot of the code Here is a screenshot of the code


Solution

  • treat the user input as a string and then use a try-except to determine whether or not it is a number

    try: 
      number = int(stringvar)
    except:
      print("continue without lucky number")
    

    you could also then generate a random number for your timer if the user did not enter a number

    import time
    import random
    
    def countdown(t):
        while t:
            mins, secs = divmod(t, 60)
            timer = "{:02d}:{:02d}".format(mins, secs)
            print(timer, end='\r')
            time.sleep(1)
            t -= 1
    
    num = input("Enter your lucky number: ")
    
    isNum = False
    
    try:
        i = int(num)
        isNum = True
    except:
        print("Continue without lucky number")
    
    if isNum:
        countdown(i)
    else:
        rand = random.randint(1, 100)
        countdown(rand)
        print(f"timer number is: {rand}")
    

    that can be your whole timer program.