简体   繁体   中英

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)

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)

any objections ?

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

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM