【问题标题】:How to display a message when a prompted input isn't entered?未输入提示输入时如何显示消息?
【发布时间】:2019-10-05 08:04:42
【问题描述】:

我要重新开始编程,所以我开始了一个项目,该项目根据用户输入的边数以及用户希望掷骰子的次数来掷骰子。我在涉及时间的程序部分遇到问题。当用户在提示后十秒内未输入时,我希望显示一条消息。如果再过十秒钟没有输入任何内容,则应显示一条消息,依此类推。我正在使用 python。

目前大部分程序都在运行,但只有在输入后才会检查时间。因此,用户可以无限地坐在输入屏幕上而不会得到提示。我真的很困惑如何同时等待输入,同时检查自提示输入以来经过的时间量。

def roll(x, y):
    rvalues = []
    while(y > 0):
        y -= 1
        rvalues.append(random.randint(1, x))
    return rvalues

def waitingInput():
    # used to track the time it takes for user to input
    start = time.time()
    sides = int(input("How many sides does the die have? "))
    times = int(input("How many times should the die be rolled? "))
    tElapsed = time.time() - start
    if tElapsed <= 10:
        tElapsed = time.time() - start
        rInfo = roll(sides, times)
        print("Each side occurs the following number of times:")
        print(Counter(rInfo))
        waitingInput()
    else:
        print("I'm waiting...")
        waitingInput()

任何建议将不胜感激。我希望尽我所能改进我的编码,因此欢迎对不相关的代码提出建设性的批评。

【问题讨论】:

标签: python loops recursion time dice


【解决方案1】:

像这样的情况需要线程定时器类。 python标准库提供了一个:

import threading

...

def waitingInput():
    # create and start the timer before asking for user input
    timer = threading.Timer(10, print, ("I'm waiting...",))
    timer.start()

    sides = int(input("How many sides does the die have? "))
    times = int(input("How many times should the die be rolled? "))

    # once the user has provided input, stop the timer
    timer.cancel()  

    rInfo = roll(sides, times)
    print("Each side occurs the following number of times:")
    print(Counter(rInfo))

【讨论】:

  • 谢谢,这帮助很大!我很好奇,为什么 print 之后需要一个逗号,并且字符串: timer = threading.Timer(10, print, ("I'm waiting...",))。我看到没有它们,它会打印出我正在等待而实际上没有等待十秒钟。
  • threading.Timer() 接受三个参数:(1) 间隔,(2) 要执行的函数,(3) 给该函数的参数,作为一个元组。您必须在此处分别显示函数和参数 - 如果删除逗号,您最终会给出 print("I'm waiting...") 作为第二个参数 - 它返回 None,因此您最终会得到 threading.Timer(10, None)("I'm waiting...",) 中的逗号是您在 python 中指定 1 元组的方式(只放括号会模棱两可)-["I'm waiting..."] 也可以在这里使用。
猜你喜欢
  • 2016-08-09
  • 1970-01-01
  • 1970-01-01
  • 2018-01-22
  • 1970-01-01
  • 2014-09-24
  • 1970-01-01
  • 2018-10-26
  • 1970-01-01
相关资源
最近更新 更多