我想知道如何让Python验证输入行并在输入时使用输入完成任务。 例如:
alphabet = "abcdefghijklmnopqrstuvwxyz"
useralphabet = input("Please enter however much of the alphabet you know:")
while(useralphabet in alphabet):
break
print("You know", 26 - len(useralphabet), "letters of the alphabet!")
很明显,我知道这段代码无法按预期工作,但我希望它能说明我的想法,即让用户输入文本,直到他们输入的文本不再是指定字符串的一部分
答案取决于您的操作系统。通常,操作系统只有在您按下
ENTER
键之后才将输入字符串交给python。如果需要按键入方式执行,则可能需要调用一些依赖于系统的调用来关闭输入缓冲请参阅Python read a single character from the user了解有关此问题的更多信息
下面是一个工作示例(在Linux上使用Python 3.8.6进行测试)。如果需要为其他系统修改,请参阅this答案
hinput
函数在输入字符时读取字符,并为通过新字符和整行的每个新字符调用on_char
在我的示例中,当用户键入
x
时on_char
函数返回True
,这会导致hinput
函数停止等待新输入如果用户键入
hello
,它将自动完成为hello, world
,并终止hinput
相关问题 更多 >
编程相关推荐