While loop workaround

Every time I use a while loop, it seems Streamlit gets stuck inside it. Even if I tell the loop to break as soon as a certain condition is True, the condition remains the same. I also have tried putting the while loop inside a function and call it using a thread (foreground and background) and the result was the same.

Is there any workaround for this? Loops are one of the most used logics in programming languages.

Hi @julio -

Can you post a code snippet that demonstrates the behavior youโ€™re describing? Iโ€™ve not of a situation where while loops donโ€™t work, but happy to take a look.

Best,
Randy

For example, this terminates:

import streamlit as st
import time

x = 0

p = st.empty()

while x < 10:
    p.write(f"Your value is {x}")
    time.sleep(1)
    x += 1
1 Like

Hi Randy, thank you for the reply. Your example worked just fine! By the way, I get stucked when I have a โ€œwhile Trueโ€ after a condition that checks if a checkbox is ticked. For example:

obj2 = st.sidebar.checkbox('On / Off')
if obj2:
    while True:
        print('Checkbox ON')

The example above was built thinking about the flow described by one user here in the forum, in which he states the code is always executed entirely from top to bottom in Streamlit, so that should be the way to go for the while loop.

But as I mentioned before, your example worked perfectly! Thank you.

Julio

1 Like