Kyle Sponable
Kyle Sponable

Reputation: 735

If statement not triggering

I am trying to make this code alternate between setting i as 56 and i as 0 I cant seem to get the second if statement to trigger. The first one works.

  while True:
        print 'is55 before if logic is' + str(is56)
        if is56 == True:
            i = 0 
            is56 = False 
            #print 'true statement' + str(i)
            print 'True is56 statement boolean is ' + str(is56)
        if is56 == False:   
            i = 56 
            is56 = True                
        print  'i is ' + str(i)

Upvotes: 0

Views: 82

Answers (4)

alexanderbird
alexanderbird

Reputation: 4198

Without an elif, the original code, if working, would execute both blocks. Why not:

def print_i(i):
    print 'i is ' + str(i)

while True: 
    print_i(56)
    print_i(0)

Upvotes: 0

Ari Gold
Ari Gold

Reputation: 1548

any objections ?

while True:
    print 'is55 before if logic is' + str(is56)
    i = is56 = 0 if is56 else 56             
    print  'i is ' + str(i)

Upvotes: 1

Moses Koledoye
Moses Koledoye

Reputation: 78556

The changes in the first if block are immediately reversed by the next one.

You want to replace the separate if blocks with a single if/else block.

On another note, you could simply use an itertools.cycle object to implement this:

from itertools import cycle

c = cycle([0, 56])

while True:
    i = next(c)
    print  'i is ' + str(i)
    # some code

Upvotes: 0

Mureinik
Mureinik

Reputation: 311308

You have two separate if, so you enter the first one, set is56 to False, and then immediately enter the second one and set it back to True. Instead, you could use an else clause:

while True:
    print 'is55 before if logic is' + str(is56)
    if is56:
        i = 0 
        is56 = False 
    else: # Here!
        i = 56 
        is56 = True                
    print  'i is ' + str(i)

Upvotes: 2

Related Questions