Search code examples
pythonif-statementsearchreplacereturn

Python checking several if-conditions (find & replace word with number)


I want to find a string (blue or red) and turn it into a number (1 or 2). I have in my Code 2 if-Conditions. Both of them are true. So I should get as an output the number 1 and 2.
But depending on that where I put return, I always get either 1 or 2, but never 1 and 2 at the same time. What am I missing? Is it not possible to have 2 if-conditions at the same time?
My Input-Text looks for example like this:

myInput = "I like the colors blue and red."

def check_color(document):

    for eachColor in document:

        if ("blue" in myInput):
            color_status = "1"
            #return color_status # only 1 as result

        if ("red" in myInput):
            color_status = "2"
            #return color_status # only 1 as result
        else:
            color_status = "0"
            #return color_status # only 1 as result
    #return color_status # only 2 as result

Without any return --> Output: None

function call

color_output = check_color(myInput)
print(color_output)

Solution

  • Of course you need a return statement to get any result at all. The problem is in the concept: If you want to return zero or more values, a list would be the easiest solution. (Your code simply overwrites the 1 by the 2).

       color_status = []
       if "blue" in myInput:
            color_status.append("1")
    
       if "red" in myInput:
            color_status.append("2")
    
       return color_status