簡體   English   中英

如果語句未觸發

[英]If statement not triggering

我試圖使此代碼在將i設置為56和i設置為0之間交替顯示,但似乎無法觸發第二個if語句。 第一個作品。

  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)

您有兩個單獨的if ,因此輸入第一個,將is56設置為False ,然后立即輸入第二個並將其設置回True 相反,您可以使用else子句:

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)

有異議嗎?

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

第一個if塊中的更改將立即被下一個反向。

您想用單個if/else塊替換單獨的if塊。

另外,您可以簡單地使用itertools.cycle對象來實現此目的:

from itertools import cycle

c = cycle([0, 56])

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

如果沒有elif ,則原始代碼(如果有效)將執行兩個塊。 為什么不:

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

while True: 
    print_i(56)
    print_i(0)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM