All loops running at once even before the inputs are being entered

####PLEASE HELP ME FIX THIS CODE IT IS NOT WORKING PROPERLY #####

import streamlit as st
from termcolor import colored
from re import search

st.title("GUESS THE MOVIE!!!")

# To accept a movie from the user and remove consonants from it

def movie_edit(movie):
    movie_list=[]
    movie_list[:0]=movie
    for i in range(0,len(movie)):
        if(movie_list[i]!='e'and movie_list[i]!='a'and movie_list[i]!='i' and movie_list[i]!='o' and movie_list[i]!='u' ):
            movie_list[i]='X'
        if(movie[i]==' '):
            movie_list[i]=' '  
    movie_new=""
    for x in movie_list:
        if(x=='X'):
            movie_new+='X'
        else:
            movie_new+=x
    return movie_new   

def main():

	menu = ["Home", "Rules", "About"]

	choice = st.sidebar.selectbox("Menu",menu)

	if choice == "Home":
		
		def play_player():
			mode = st.selectbox("Select Mode: ",["Player v/s Computer","Player v/s Player"], index = 1)
			st.write(mode)
			col1,col2 = st.columns(2)

		################################################################ COLUMN 1 ######################################################################

			col1.subheader("Enter Player 1 Name: ")
			name1 = col1.text_input("Player 1")
			col1.markdown(f"Player 1: {name1}")

		################################################################ COLUMN 2 ######################################################################

			col2.subheader("Enter Player 2 Name: ")
			name2 = col2.text_input("Player 2")
			col2.markdown(f"Player 2: {name2}")

		################################################################################################################################################
			count = 0
			round = st.number_input("How many rounds do you want to play?", min_value=1, max_value=10, value=1, step=1)
			count += 1
			st.write(round)
			p1_score = 0
			p2_score = 0

			for i in range(round):
				life2 = "Bollywood"
				mlist2 = []
				llist2 = ["a","i","e","o","u"]

				movie = st.text_input(f"Enter a movie", type = "password")
				movie_game = movie_edit(movie)
				correct2 = 0
				n2 = 0
				
				while(correct2 == 0 & n2 != 9):
					st.write(f"Lives: {life2}")
					st.write(f"{movie_game}")
					choice = st.number_input(f"What do you want to do {name2}", min_value=1, max_value=2, value=1, step=1)
					count += 1
					st.write("1. Guess The Moive")
					st.write("2. Guess The Letter")

					if(choice == 1):
						guess = st.text_input("Guess the movie name")
						if(guess not in mlist2):
							if(guess == movie):
								st.write(f"Congratulations!!! {name2}, You are correct. The moive name is {guess}")
								p2_score = p2_score + 1
								correct2 = 1
							else:
								st.write(f"Hard Luck {name2}, {guess} is not the right answer")
								mlist2.append(guess)
								live = []
								live = list(life2)
								live[n2] = "-"
								life2 = ""
								for x in live:
									life2 += x
								n2 = n2 + 1
								if(n2 == 9):
									st.write(f"Hard Luck {name2}. You ran out of lives")

						else:
							st.write(f"Movie {guess} is already tried and falied try again")

					if(choice == 2):
						guess = st.text_input("Guess the Letter")
						if(guess not in llist2):
							llist2.append(guess)
							if(search(guess,movie)):
								st.write(f"Congratulations!!! {name2} You have guessed the correct letter")
								mg = list(movie_game)
								m = list(movie)
								movie_game = ""
								movie = ""
								for i in range(len(m)):
									if(m[i] == guess):
										mg[i] = guess
								for x in mg:
									movie_game += x
								for x in m:
									movie += x
								if(movie_game == movie):
									st.write(f"Congratulations!!!! {name2}. You have guessed the movie correctly: {movie_game}")
									p2_score = p2_score + 1
									correct2 = 1
							else:
								st.write(f"Hard Luck {name2} the letter {guess} does not exit in the movie")
								live = []
								live = list(life1)
								live[n1] = "-"
								life1 = ""
								for x in live:
									life1 += x
								n1 = n1 + 1
								if(n1 == 9):
									st.write(f"Hard Luck {name1}, You ran out of lives")
						else:
							st.write(f"Letter {guess} is either a vowel or already tried and failed or guessed")
							st.write(f"SCORE: {name1}: {p1_score} {name2}: {p2_score}")

							if(p1_score > p2_score):
								st.write(f"Congratulations!!!! {name1} You won the game!!!!!")
							elif(p2_score > p1_score):
								st.write(f"Congratulations!!!! {name2} You won the game!!!!!")
							else:
								st.write("No One Won The Game!!!!!, It's A Tie")

		play_player()

	elif choice == "Rules":
		st.subheader("Rules")

	else:
		st.subheader("About")

if __name__ == "__main__":
	main()

Hello @Anannmaya_Singh, Welcome to the Streamlit community.

Note that whenever an app starts or there is any input/change in any of the widgets, Streamlit (re-)runs your code from top to bottom. This means for/while-loops won’t work as you’d expect in a normal python program.

Your code contains lots of if-statements and for-loops nested within a while-loop all of which Streamlit will start to process immediately the app runs. So you need to find ways to break up the code and direct the flow such that specific things happen only when certain conditions are met.

    word = st.sidebar.text_input(
        f"Enter a word :", type="password", key=f"word_{hm.hm_idxml_key}"
    )
    if hm.hm_word == "":
        if word == "":
            st.sidebar.warning("**Please enter the hidden word.**")
        else:
            hm.hm_word = word.upper()
            hm.hm_word_letters = set(hm.hm_word)
            st.experimental_rerun()
    elif hm.hm_word != "":
        st.sidebar.success("**Game in progress...**")

The above snippet ensures that the app does not move on until the user has provided a certain input. It’s from a Hangman game I created that has a similar structure to your game. You can run the full python code to see how the flow is directed and adapt your code to get the desired behaviour.

Cheers.

2 Likes

Thanks, I will try this approach