Prassanth
Prassanth

Reputation: 69

In a multi-condition IF statement, How to print only the value of a satisfied condition?

In the below code if the first IF condition is satisfied A[0] should be printed. If the second IF condition is satisfied then A[1] should be printed.

In this code, I want to print 'B'

A = ['A','a','O','E','B','B']
if ((A[0] == A[2]) or (A[1] == A[3]) or (A[4] == A[5])):
  print(A[])

I have 20 conditions to check and want to print the value in the one true condition that satisfies.

Upvotes: 0

Views: 1395

Answers (4)

DarrylG
DarrylG

Reputation: 17156

A = ['A','a','O','E','B','B']
print(next(x[0] for x in zip(A[0::2], A[1::2]) if x[0] == x[1]))

    Works as follows:
        A[0::2] are even elements of the array
        A[1::2] are odd elements of the array
        zip(A[0::2], A[1::2]) => (A[0], A[1]), (A[2], A[3]), ...
        (x[0] for x in zip(A[0::2], A[1::2]) if x[0] == x[1]))

    Creates a generator which only has an output when a pair (i.e. (A[i], A[i+1])  
    has the same value (i.e. A[i] == A[i+1]).  
    x[0] corresponds to the first element of the pair x.

next(...)

Returns the next output from the generator (see https://www.programiz.com/python-programming/methods/built-in/next)

Upvotes: 0

lenik
lenik

Reputation: 23528

This should be the easiest way, much easier to scale once your A array starts to grow into the hundreds or thousands of elements:

A = ['A','a','O','E','B','B']

for i in range(0,len(A),2) :
    if A[i] == A[i+1] :
        print A[i]
        break    # optionally, if you need just one result

Upvotes: 3

Sam Creamer
Sam Creamer

Reputation: 5361

Try this:

A = ['A','a','O','E','B','B']
if A[0] == A[1]:
    print(A[0])
elif A[2] == A[3]:
    print(A[2])
elif A[4] == A[5]:
    print(A[4])

Alternatively, if you want to print multiple of the conditions if they're all true, you can do the following:

A = ['A','a','O','E','B','B']
if A[0] == A[1]:
    print(A[0])
if A[2] == A[3]:
    print(A[2])
if A[4] == A[5]:
    print(A[4])

In that case, you would see all three things printed if they all evaluated to True.

EDIT: To answer your question about having 20, if they all the same logic (all of the conditions), then you can write something like this.

for i in range(0, len(A), 2):
    n = i + 1
    if A[i] == A[n]:
        print(A[i])

This would work for any length of A.

Upvotes: 0

awakenedhaki
awakenedhaki

Reputation: 301

You would have to separate those if statements into a series of if-elif.

if A[0] == A[1]:
   print(A[0])
elif ...

In python 3.8, you might be able to use assignment expressions. Not sure however, since python 3.8 is only in beta and I have not tested it out yet.

Upvotes: 1

Related Questions