1

is there any way for ask question by if statement and after afew sec if user didnot give any answer , if state use a default answer?

inp = input("change music(1) or close the app(2)")

if inp = '1':
    print("Music changed)

elif inp = '2':
    print("good by")

in this case if user dont give any answer after 30 sec by default if statement choose number 3

  • 1
    `input()` is not designed for that kind of interaction, so there is no way to do it with only `input()` and if-statement. Working answer will be a lot more complex than original code. – youknowone May 06 '19 at 17:33
  • You are missing a `"` in the line `print("Music changed)` – Reedinationer May 06 '19 at 17:33
  • 1
    Possible duplicate of [Keyboard input with timeout in Python](https://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python) – zvone May 06 '19 at 17:37
  • https://stackoverflow.com/questions/1335507/keyboard-input-with-timeout-in-python – user6037143 May 06 '19 at 17:40
  • using "input" halts the program until it gets a response, but it can be done with multiprocessing, threads, or asyncio, if you are interested in one of those solutions. – Kurt E. Clothier May 06 '19 at 17:47

2 Answers2

0
from threading import Timer

out_of_time = False

def time_ran_out():
    print ('You didn\'t answer in time') # Default answer
    out_of_time = True

seconds = 5 # waiting time in seconds
t = Timer(seconds,time_ran_out)
t.start()
inp = input("change music(1) or close the app(2):\n")

if inp != None and not out_of_time:
     if inp == '1':
          print("Music changed")
     elif inp == '2':
          print("good by")
     else:
          print ("Wrong input")
     t.cancel()

Timer Objects

This class represents an action that should be run only after a certain amount of time has passed — a timer. Timer is a subclass of Thread and as such also functions as an example of creating custom threads.

Timers are started, as with threads, by calling their start() method. The timer can be stopped (before its action has begun) by calling the cancel() method. The interval the timer will wait before executing its action may not be exactly the same as the interval specified by the user.

For example:

def hello():
    print("hello, world")

t = Timer(30.0, hello)
t.start()  # after 30 seconds, "hello, world" will be printed

class threading.Timer(interval, function, args=None, kwargs=None)

Create a timer that will run function with arguments args and keyword arguments kwargs, after interval seconds have passed. If args is None (the default) then an empty list will be used. If kwargs is None (the default) then an empty dict will be used.

cancel()

Stop the timer, and cancel the execution of the timer’s action. This will only work if the timer is still in its waiting stage.

ncica
  • 6,018
  • 1
  • 12
  • 30
0

Here's an alternative way to do it (python 3), using multiprocessing. Note, to get the stdin to work in the child process, you have to re open it first. I'm also converting the input from string to int to use with the multiprocessing value, so you might want to error check there as well.

import multiprocessing as mp
import time
import sys
import os


TIMEOUT = 10
DEFAULT = 3


def get_input(resp: mp.Value, fn):
    sys.stdin = os.fdopen(fn)
    v = input('change music(1) or close the app (2)')
    try:
        resp.value = int(v)
    except ValueError:
        pass # bad input, maybe print error message, try again in loop.
        # could also use another mp.Value to signal main to restart the timer


if __name__ == '__main__':

    now = time.time()
    end = now + TIMEOUT

    inp = 0
    resp = mp.Value('i', 0)
    fn = sys.stdin.fileno()
    p = mp.Process(name='Get Input', target=get_input, args=(resp, fn))
    p.start()

    while True:
        t = end - time.time()
        print('Checking for timeout: Time = {:.2f}, Resp = {}'.format(t, resp.value))

        if t <= 0:
            print('Timeout occurred')
            p.terminate()
            inp = DEFAULT
            break
        elif resp.value > 0:
            print('Response received:', resp.value)
            inp = resp.value
            break
        else:
            time.sleep(1)

    print()
    if inp == 1:
        print('Music Changed')
    elif inp == 2:
        print('Good Bye')
    else:
        print('Other value:', inp)
Kurt E. Clothier
  • 210
  • 1
  • 10