简体   繁体   English

如何检查用户在Python中为某个单词输入的所有输入?

[英]How get check all input the user enters for a certain word in Python?

I am new to python programming. 我是python编程的新手。 I want to call a function whenever the user enters the word "inventory" after I prompt them for an input at any point in the game. 我想在用户在游戏中的任何时候提示他们输入后,只要用户输入单词"inventory" ,就要调用一个函数。 At the moment I am doing this: 目前,我正在这样做:

    def myFunction():
        #do something

    userInput = input("Some input")
    someMoreInput = input("Do something")

    if userInput == "inventory" or someMoreInput == "inventory":
        myFunction()

The problem with this is that whenver I want to have the user enter something (and that will happen a lot ) I have to add the variable name to my if statement. 这里的问题是,whenver我希望让用户输入的东西(这会发生很多 )我有变量名称添加到我的if语句。

You have to use a loop for this, for instance: 为此,您必须使用循环,例如:

userInput = ''
while userInput != 'inventory':
    userInput = input("Enter input: ")
myFunction()

As far as i have understood your question, you don't want to define a variable for your input again and again. 据我了解您的问题,您不想一次又一次为输入定义变量。

Well, you don't have to. 好吧,您不必这样做。 You can compare directly: 您可以直接比较:

if input("Some input")=="inventory": 
    myFunction()

Oscar's implementation seems to be correct however, if you want to check input every time without declaring a variable; 如果您想每次都检查输入而不声明变量,那么Oscar的实现似乎是正确的。 simply use input() 只需使用input()

def myFunction():
     #do something

while input() != "inventory":
     #print("you did not enter inventory")
     input()
myFunction()

this will keep asking for input unless it equals "inventory" and you don't need to use even a single variable. 这将继续要求输入,除非它等于“库存”,并且您甚至不需要使用单个变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM