Ad

If-Else Branches Not Executing - Python 3

- 1 answer

I am working through a problem asking me to define a function that mixes two primary colours. I am wondering why, when i execute the program calling the function, it is only executing the first "if" branch and does not execute any of the other statements. My code is as follows:

    if "red" and "blue":
        result = "fuchsia"
    elif "red" and "green":
        result = "yellow"
    elif "green" and "blue":
        result = "aqua"
    elif "red" and "red":
        result = "red"
    elif "blue" and "blue":
        result = 'blue'
    elif "green" and "green":
        result = "green"
    else:
        result = "Error"
    return result
Ad

Answer

Code is below & uses or and and keyword inside if statement to determine the color.

color1 = "red"
color2 = "green"

def getColor(color1, color2):
    if color1 == "red" and color2 == "blue" or color1=="blue" and color2=="red":
        result = "fuchsia"
    elif color1 == "red" and color2=="green" or color1=="green" and color2== "red":
        result = "yellow"
    elif color1 == "green" and color2 == "blue" or color1 == "blue" and color2 == "green":
        result = "aqua"
    elif color1=="red" and color2=="red":
        result = "red"
    elif color1 == "blue" and color2=="blue":
        result = 'blue'
    elif color1 == "green" and color1=="green":
        result = "green"
    else:
        result = "Error"
    return result

print(getColor(color1, color2))

output:

$ python3 color.py 
yellow

A better approach use Enum in python to determine the color:

import enum

color1 = "red"
color2 = "green"

class Color(enum.Enum):
    RED = "RED"
    GREEN = "GREEN"
    BLUE = "BLUE"

def getColor(color1 :Color, color2:Color):
    red = False
    green = False
    blue = False

    red = color1==Color.RED or color2 == Color.RED
    green = color1==Color.GREEN or color2 == Color.GREEN
    blue = color1==Color.BLUE or color2 == Color.BLUE

    if red and blue:
        return "fuchsia"
    if red and green:
        return "yellow" 
    if green and blue:
        return "aqua"
    if color1 is Color.RED and color2 is Color.RED:
        return "red"
    if color1 is Color.GREEN and color2 is Color.GREEN:
        return "green"
    if color1 is Color.BLUE and color2 is Color.BLUE:
        return "blue"
    return "Error"
print(getColor(Color.RED, Color.GREEN))
print(getColor(Color.GREEN, Color.RED))
print(getColor(Color.GREEN, Color.GREEN))

Output:

$ python3 color.py 
yellow
yellow
green
Ad
source: stackoverflow.com
Ad