-2

I'm still experimenting with if, elif and else. I don't understand why the first if condition is executed even if you don't choose blue as your favorite color.

I tried changing the indentation but I always get syntax errors.

color = input("Whats your favorite color?\n")

if color == 'blue' or 'Blue':
    print("Blue is a great color")
    print(f"{color} is your favorite color")
elif color == 'yellow' or 'Yellow':
    print(f"{color} is your color")
    print("Yellow is awesome!")
else:
    print("Choose something")

When I enter random letters, for example, 'sdfd' I should get the result "Choose a real color" but instead I get Blue is a great color sdfd is your favorite color

DataPlug
  • 340
  • 3
  • 10

4 Answers4

2

This is because if color == 'blue' or 'Blue': is like if (color == 'blue') or ('Blue'):

And 'Blue' being a non-empty string it evaluates to True.

You could do if color in ['Blue', 'blue']: or even better: if color.lower() == 'blue':

Taek
  • 1,004
  • 7
  • 20
0

Your test condition have one mistake. Instead of if color == 'blue' or 'Blue':, you should do it like this:

if color == 'blue' or color == 'Blue':

This should work fine! (Dont forget to change the other conditions too!) The final result should be like:

color = input("Whats your favorite color?\n")

if color == 'blue' or color == 'Blue':
    print("Blue is a great color")
    print(f"{color} is your favorite color")
elif color == 'yellow' or color == 'Yellow':
    print(f"{color} is your color")
    print("Yellow is awesome!")
else:
    print("Choose something")
0

For this example it might be easier to use the text method .lower()

if color == 'blue' or 'Blue':

can be correctly expressed as:

if color.lower() == 'blue':

This will also capture if someone enters "BLUE" or "bLUE".

This will be easier to read and debug.

CodeCupboard
  • 1,507
  • 3
  • 17
  • 26
0

General Answer

With any if...else statement in Python with multiple conditions, each condition must be stated explicitly and clearly. So with your if color == 'blue' or 'Blue' statement, you are not clearly stating the two conditions. The first section, if colour == 'blue' is completely fine, however, after the or comparator, you must state the next condition in its entirety.

The code should look something like this: if color == 'blue' or color == 'Blue':

Possible Improvements:

You could also improve this by implementing string manipulation by incorporating .upper(), .title() and various other ones into your code. This will help you reduce the number of conditions in your if...else statements.

Ar5hv1r
  • 17
  • 7