简体   繁体   English

如果if语句未在循环内激活,是否有条件运行?

[英]Is there a conditional that runs if an if statement does not activate within a loop?

Making a simple program that swaps the location of numbers in a loop until they are in ascending order. 编写一个简单的程序,在循环中交换数字的位置,直到它们升序。 I want the program to end when the if conditional is never activated within a instance of the for loop. 我希望当for循环的实例中从未激活过if条件时,该程序结束。 Is there a shorter way to do this without the use of a while true/false or like? 有没有使用一会儿true / false或诸如此类的简短方法?

while tf == True:
    for i in range(lisLen-1):
        tf=False
        if listy[i]>listy[i+1]:
             tf=True
             swap(listy, i, i+1)

Get rid of the variable, and use break instead. 摆脱变量,而改用break Then you can use the else: clause to test this. 然后,您可以使用else:子句对此进行测试。 That clause runs if the loop ended normally instead of with break . 如果循环正常结束而不是使用break则该子句运行。

while True:
    for i in range(lisLen-1):
        if listy[i]>listy[i+1]:
            swap(listy, i, i+1)
            break
    else:
        break

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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