Raluvas
Raluvas

Reputation: 15

Checking all user input for a specific value

Is it possible for Python to check all user input for a keyword to preform a specific action? I currently have it set up in my program that if the user enters 'quit' anywhere in the application that it will stop the program but I have a dozen or so different user inputs and was hoping that I did not have to go through and create an if statement for each one to watch for the keyword. Please see the sample code below:

def add_recipe(self): 
    """Adding a recipie to the recipe book"""
    recipe_name = input("Please enter the name of the recipe that you are adding: ")
    category = input("Please enter the category you would like this recipe to be a part of: ")
    preptime = input("Please enter the amount of time it will take to prepare this recipe: ")
    cooktime = input("Please enter the amount of time in minutes it will take to complete this recipe (please include minutes or hours): ")
    ingredients = input("Please list the ingredients for this recipe out in a comma separated list:")
    instructions = input("Please list out the instructions to making this recipe: ")
    if self.recipes[1] == {'Recipe Name' : '' , 'Category' : '' ,'Prep Time' : '' , 'Cooktime' : '' , 'Ingredients' : '' , 'Instructions' : ''}:
        self.recipes[1] = {'Recipe Name' : f'{recipie_name}', 'Category' : f'{category}' , 'Preptime': f'{preptime}', 'Cooktime' : f'{cooktime}' , 'Ingredients' : f'{ingredients}' , 'Instructions' : f'{instructions}'}
    else:   
        self.recipes[len(self.recipes) + 1] = {'Recipe Name' : f'{recipie_name}', 'Category' : f'{category}' ,'Preptime': f'{preptime}', 'Cooktime' : f'{cooktime}' , 'Ingredients' : f'{ingredients}' , 'Instructions' : f'{instructions}'}
        return self.recipes

Upvotes: 0

Views: 825

Answers (1)

Jasper
Jasper

Reputation: 631

You could add some sort of wrapper around the input. This example adds the method ask_input(msg) which takes one argument to use as the prompt. It returns the user supplied input so it works the same way as your original code, but inside this method you can do your keyword checking to trigger your action, or maybe store some flag to check for at the end.

def ask_input(msg):
    user_input = input(msg)
    if user_input == 'quit':
        sys.exit("User asked to quit")
    return user_input

def add_recipe(self):
    recipe_name = ask_input("Please enter the name of the recipe that you are adding: ")
    category = ask_input("Please enter the category you would like this recipe to be a part of: ")
    preptime = ask_input("Please enter the amount of time it will take to prepare this recipe: ")
    # etc...

Upvotes: 1

Related Questions