1

I currently have

seq1 = "--MFA"
seq2= "--MFU"

for i in range(0, len(seq1)):

    if seq1[i] or seq2[i] == '-':

        print  "hi"
    else:
        print "bye"

Why does it print "hi" 5 times (even if seq1[i] and seq1[i] are M, F, A/U). I thought it was a regex problem at first, but even escaping the hyphen yielded the same results.

1
  • When in doubt, use the REPL (IDLE or in the shell) and type. '-' or '2' >>> '-' '-' or '2' == '-' >>> '-' So you can guess that it always return the left part because it's interpreted as True. Commented Nov 7, 2013 at 13:47

3 Answers 3

3

if seq1[i] or seq2[i] == '-':

Means:

if (seq1[i]) or (seq2[i] == '-'):

If seq[i] has a value of True (i.e, if bool(seq1[i]) == True), then the conditional statement will instantly be true, because of the or. With an or operator, if one side is True, then the conditional runs.

Note that bool(seq1[i]) will always be True because a string with any length is considered True.

Hence, 'hi' is printed.

Sign up to request clarification or add additional context in comments.

Comments

2
if seq1[i] or seq2[i] == '-':

This condition means that if seq1[i] is true or seq2[i] = '-' do the following. In that case, seq1[i] is true the 5 times. Then, it prints 'hi' 5 times.

Comments

1

There are a number of alternatives you could use here

if '-' in (seq1[i], seq2[i]):

Is concise, but is funny to read.

if seq1[i] == '-' or seq2[i] == '-':

Feels more natural

A cleaner way to loop through the sequences together is to use zip

for i, j in zip(seq1, seq2):

    if i == '-' or j == '-':
        print  "hi"
    else:
        print "bye"

If you were looping through more sequences together, a good way to extend the comparison is to use any

for item in zip(seq1, seq2, seq3, seq4, ...):
    if any(i == '-' for i in item):
        print  "hi"
    else:
        print "bye"

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.