While loop

whileLoop.dyn (2.2 KB)



Does anybody know a practicle example of a whileLoop?
Maybe combined with a funktion or for loop?
I don’t clearly understand the concept. Sometimes i think it is better to use an If-condition.



While loops have many uses and usually work with if statements. The two most common I can think of:

  1. when you don’t know how many times you need to iterate. For loops need a definitive range but while loops can use a condition to check
  2. iterators like you will find in API, etc. Example: ConnectorSetIterator class. Iterators work with while loops so that it will go through every item inside its list until it exhausts it. They have their own specific methods to move through them like iterator.MoveNext()

Occasionally you may have a while loop that looks like while true: with a break somewhere inside or while x: with x as a variable switch but I don’t have any good specific examples right now.

1 Like

Ok, thank you … I will continue to investigate issus.

In this particular case, an if statement would work much better. Your while loop is exiting, but not for the reason you want it to.

Zahlen = 26
while Zahlen < 40:
    Zahlen = str(Zahlen) + " #Alles unter 40 ist OK!"
OUT = Zahlen

A while loop will continue to execute if the condition (Zahlen < 40, in this case) is True. The first test is 26 < 40, which evaluates to True. The original value of 26, which is an integer, is then replaced with "26 #Alles unter 40 ist OK!". So, the next time the test is done, it will compare "26 #Alles unter 40 ist OK!" to 40 and evaluates to False. A good example of the use for a while loop might be:

my_int = 26
tests = []
while my_int < 40:
    tests.append(str(my_int) + " #Alles unter 40 ist OK!")
    my_int += 1 # Increment my_int by 1 to ensure loop will exit eventually
OUT = tests

which would output the following: