If, elif and or statements

When i run this exercise code, it always prints ‘code1’ regardless of the input

i = input('if exercise:\n')
if i == 'A' or 'B' or 'C':
    print('code1')
elif i == 'D' or 'E' or 'F':
    print('code2')
elif i == 'G' or 'H' or 'I':
    print('code3')
else:
    print('code4')

if exercise:
D
code1

The IDE doesn’t show any syntax error and the debugger doesn’t flare anything.
What did i do wrong?

Please refer to:

2 Likes

Thanks!
I’m very new to coding.

So what you want is:

i = input('if exercise:\n')
if i in 'ABC':
    print('code1')
elif i in 'DEF':
    print('code2')
elif i in 'GHI':
    print('code3')
else:
    print('code4')
2 Likes

In Python, each condition in an if statement should be explicitly compared with the variable i. In your code snippet the variable “i” is not compared explicitly to its value like so:

if i == ‘A’ or ‘B’ or ‘C’:

To fix this issue, we need to explicitly compare each condition to the variable i.

Here’s the corrected code snippet:

Python

if i == 'A' or i == 'B' or i == 'C':

Explanation:

In the corrected code snippet, each condition (i == 'A', i == 'B', i == 'C') is explicitly compared to the variable i. This modification ensures that the logic of the if statement correctly checks whether i is equal to ‘A’, ‘B’, or ‘C’.

I hope this helps :slight_smile:

1 Like

Assuming that you’re using Python 3.10 or later, you can also use the new match statement, which lets you do pretty much what you tried, except that you must spell “or” as “|”:

i = input('match exercise:\n')
match i:
    case 'A' | 'B' | 'C':
        print('code1')
    case 'D' | 'E' | 'F':
        print('code2')
    case 'G' | 'H' | 'I':
        print('code3')
    case _:
        print('code4')
1 Like