未输入提示输入时如何显示消息?
How to display a message when a prompted input isn't entered?
我重新开始编程,所以我开始了一个项目,该项目根据用户输入的面数以及用户希望掷骰子的次数来掷骰子。我在涉及时间的程序部分遇到了麻烦。当用户在收到提示后十秒内未输入时,我希望显示一条消息。如果再过 10 秒钟没有输入任何内容,则应显示一条消息,依此类推。我正在使用 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()
如有任何建议,我们将不胜感激。我希望尽我所能改进我的编码,因此欢迎对不相关的代码提出建设性的批评。
像这种情况需要线程计时器 class。 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))
我重新开始编程,所以我开始了一个项目,该项目根据用户输入的面数以及用户希望掷骰子的次数来掷骰子。我在涉及时间的程序部分遇到了麻烦。当用户在收到提示后十秒内未输入时,我希望显示一条消息。如果再过 10 秒钟没有输入任何内容,则应显示一条消息,依此类推。我正在使用 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()
如有任何建议,我们将不胜感激。我希望尽我所能改进我的编码,因此欢迎对不相关的代码提出建设性的批评。
像这种情况需要线程计时器 class。 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))