我正在用Python编写一个脚本,允许用户输入一个字符串,该字符串将指示脚本执行特定操作.为了争论,我会说我的命令列表是:
lock
read
write
request
log
Run Code Online (Sandbox Code Playgroud)
现在,我希望用户能够输入单词"log",它将执行特定操作,这非常简单.但是,我想匹配部分词.因此,例如,如果用户输入"lo",它应该匹配"lock",因为它在列表中更高.我已经尝试使用ccpes从libc中使用strncmp来实现这一目标,但还没有做出正面或反面.
所以我几乎搜索了"字符串","python","验证","用户输入"等字样的每个排列,但我还没有找到适合我的解决方案.
我的目标是提示用户是否想要使用字符串"yes"和"no"启动另一个事务,我认为字符串比较在Python中是一个相当简单的过程,但是有些东西不起作用对.我正在使用Python 3.X,因此据我所知,输入应该在不使用原始输入的情况下接受字符串.
即使输入"是"或"否",程序也会始终回放无效输入,但真正奇怪的是,每次输入一个字符串> 4个字符的长度或一个int值时,它会将其检查为有效的正值输入并重新启动程序.我还没有找到获得有效负输入的方法.
endProgram = 0;
while endProgram != 1:
#Prompt for a new transaction
userInput = input("Would you like to start a new transaction?: ");
userInput = userInput.lower();
#Validate input
while userInput in ['yes', 'no']:
print ("Invalid input. Please try again.")
userInput = input("Would you like to start a new transaction?: ")
userInput = userInput.lower()
if userInput == 'yes':
endProgram = 0
if userInput == 'no':
endProgram = 1
Run Code Online (Sandbox Code Playgroud)
我也试过了
while userInput != 'yes' or userInput != …Run Code Online (Sandbox Code Playgroud)