首页 > 解决方案 > 如果没有响应,给用户提示

问题描述

我正在尝试创建一个程序,该程序通过对问题的三个回答来要求用户输入。现在我的问题几乎是一段长的,但理想情况下,我想先问一个初始问题,然后如果用户在任何时间内没有输入任何内容,就开始给出提示。

answers = []
def questions(question):
    print(question)
    for i in range(1, 4, 1):
        answers.append(input(f"{i}. "))

questions("""What are your three favorite things? """)

理想情况下,会有一些行为类似于下面的伪代码:

ask user for input
    if no response within 30 seconds:
        give first hint
    elif no respose within 30 seconds:
        give second hint        

提前致谢!

标签: python

解决方案


您可以创建一个hint等待一段时间然后输出提示的过程。如果用户回答了问题,则使用terminate()hint终止进程。

import time
from multiprocessing import Process

answers = []

def questions(question):
    print(question)

    for i in range(1, 4, 1):
        answers.append(answer(f"{i}. "))

    print(answers)


def hint():
    # For testing simplification, I decrease the wait time

    time.sleep(5)
    print('\nhint1 after 5 seconds')

    time.sleep(3)
    print('hint2 after 3 seconds')


def answer(i):
    phint = Process(target=hint)
    phint.start()

    uanswer = input(i)
    phint.terminate()

    return uanswer

questions("""What are your three favorite things? """)

输出看起来像

What are your three favorite things? 
1. 
hint1 after 5 seconds
hint2 after 3 seconds
test
2. 
hint1 after 5 seconds
test1
3. test3
['test', 'test1', 'test3']

推荐阅读