Home > Software design >  How do i have the if statement become effective after the 30 seconds
How do i have the if statement become effective after the 30 seconds

Time:12-04

I want the if statement working after the 30 seconds but that isn't the case right now. I heard people recommend threading but that's just way too complicated for me.

import os
import time

print('your computer will be shutdown if you dont play my game or if you lose it')

shutdown = input("What is 12 times 13? you have 30 seconds.")

time.sleep(30)

if shutdown == '156':
    exit()

elif shutdown == '':
    print('you didnt even try') and os.system("shutdown /s /t 1")

else:
    os.system("shutdown /s /t 1")

I tried threading already but that is really complicated and I'm expecting to print you didn't even try and shutdown after the 30 seconds if you didn't input anything

CodePudding user response:

I recommend to use threads because it makes the thing much easier here. Try this:

import threading
import time

user_input = ""
ANSWER_TIME = 30

def time_over():
    match input:
        case '156':
            exit(0)
        case '':
            print('you didnt even try')
            os.system("shutdown /s /t 1")
        case _:
            os.system("shutdown /s /t 1")

exit_timer = threading.Timer(ANSWER_TIME, time_over)
print('your computer will be shutdown if you dont play my game or if you lose it')
exit_timer.start()

user_input = input("What is 12 times 13? you have 30 seconds.")

Note that I replaced the if-else statements with match-cases, which are IMHO more readable. I also replaced your and statement (if you want to execute two statements, just write them below each other).

CodePudding user response:

I would use inputimeout

https://pypi.org/project/inputimeout/

from inputimeout import inputimeout, TimeoutOccurred
import os

if __name__ == "__main__":
    print('your computer will be shutdown if you dont play my game or if you lose it')
    try:
        answer = inputimeout(prompt="What is 12 times 13? you have 30 seconds.", timeout=30)
    except TimeoutOccurred:
        os.system("shutdown /s /t 1")
    if answer == '':
        print('you didnt even try')
        os.system("shutdown /s /t 1")
  • Related