Streamlit is Repeatedly Running a Loop When Entering Details

I have a Streamlit code that initially asks for the candidate’s Full Name, Experience, and Language. Upon clicking the submit button, it displays three questions (Question 1, Question 2, Question 3). The issue arises when I enter an answer in the text box for Question 1. After that, when I attempt to enter an answer in the text box for Question 2, the page resets and starts from the beginning. How can I resolve this problem?

Here is the code

import streamlit as st
import pandas as pd

def main():
    st.title('Employer Test')
    st.markdown('## Candidate Information')

    # Full Name Input
    full_name = st.text_input('Full Name')

    # Experience Dropdown
    experience = st.selectbox("Experience", ["Fresher"], index=0)
    
    # Language Dropdown
    language = st.selectbox("Language", ["Python"], index=0)

    # Button to start the test
    if st.button('Submit'):
        if full_name:
            run_python_test(full_name)

def run_python_test(full_name):
    st.title('Python Test')

    # Dummy test questions and answers
    questions = [
        {
            'question': 'What is the output of the following code?\n\n```python\nx = 5\nprint(x)\n```',
            'options': ['5', '10', '0', 'Error'],
            'correct_answer': '5'
        },
        {
            'question': 'Which of the following is a Python data type?',
            'options': ['List', 'Streamlit', 'GitHub', 'HTML'],
            'correct_answer': 'List'
        },
        {
            'question': 'What is the result of the expression 3 + 7 * 2?',
            'options': ['13', '20', '17', 'Error'],
            'correct_answer': '17'
        }
        # Add more questions here...
    ]

    total_questions = len(questions)
    score = 0
    answer = []

    for i, question_data in enumerate(questions):
        question = question_data['question']
        options = question_data['options']
        correct_answer = question_data['correct_answer']

        st.write(f'Question {i+1}: {question}')

        # Display options for each question
        answer.append(st.text_area(f"Enter answer for Question {i+1}", key=f"answer_{i}"))

    # Add a submit button
    if st.button("Submit Test", key="submit_test"):
        # Process the answers and calculate score
        for i, ans in enumerate(answer):
            if ans == questions[i]['correct_answer']:
                score += 1
            st.write(f"Question {i+1} Answer: {ans}")

    percentage_score = (score / total_questions) * 100

    if percentage_score >= 60:
        save_result(full_name, percentage_score)
        st.session_state['test_completed'] = True

def save_result(full_name, score):
    data = {'Full Name': [full_name], 'Score': [score]}
    df = pd.DataFrame(data)
    df.to_csv('test_results.csv', index=False)
    st.write('Result saved successfully!')

if __name__ == '__main__':
    main()

1 Like

Welcome to the Streamlit Community forum and thank you for posting! :raised_hands:t5:

This is happening because Streamlit re-executes the script each time you enter an input in the questions. To fix this, you can consider using st.session_state to persist the state across all the reruns as you submit input in the text area.

I modified your code below to show how you can use st.session_state – feel free to adapt it to fit your case:

import streamlit as st
import pandas as pd

def main():
    st.title('Employer Test')
    
    # Check if 'started' key exists in session_state, if not, display candidate information
    if not st.session_state.get('started'):
        st.markdown('## Candidate Information')

        # Full Name Input
        full_name = st.text_input('Full Name')

        # Experience Dropdown
        experience = st.selectbox("Experience", ["Fresher"], index=0)
        
        # Language Dropdown
        language = st.selectbox("Language", ["Python"], index=0)

        # Button to start the test
        if st.button('Submit'):
            if full_name:
                st.session_state['started'] = True
                st.session_state['full_name'] = full_name
                run_python_test()
    else:
        run_python_test()

def run_python_test():
    st.title('Python Test')
    
    # Dummy test questions and answers
    questions = [
        {
            'question': 'What is the output of the following code?\n\n```python\nx = 5\nprint(x)\n```',
            'options': ['5', '10', '0', 'Error'],
            'correct_answer': '5'
        },
        {
            'question': 'Which of the following is a Python data type?',
            'options': ['List', 'Streamlit', 'GitHub', 'HTML'],
            'correct_answer': 'List'
        },
        {
            'question': 'What is the result of the expression 3 + 7 * 2?',
            'options': ['13', '20', '17', 'Error'],
            'correct_answer': '17'
        }
        # Add more questions here...
    ]
    
    total_questions = len(questions)
    if 'answer' not in st.session_state:
        st.session_state['answer'] = [''] * total_questions
    
    for i, question_data in enumerate(questions):
        question = question_data['question']

        st.write(f'Question {i+1}: {question}')
        
        # Display options for each question
        st.session_state['answer'][i] = st.text_area(f"Enter answer for Question {i+1}", value=st.session_state['answer'][i], key=f"answer_{i}")

    # Add a submit button
    if st.button("Submit Test", key="submit_test"):
        score = 0
        # Process the answers and calculate score
        for i, ans in enumerate(st.session_state['answer']):
            if ans == questions[i]['correct_answer']:
                score += 1
            st.write(f"Question {i+1} Answer: {ans}")
        
        percentage_score = (score / total_questions) * 100

        if percentage_score >= 60:
            save_result(st.session_state['full_name'], percentage_score)
            st.session_state['test_completed'] = True

def save_result(full_name, score):
    data = {'Full Name': [full_name], 'Score': [score]}
    df = pd.DataFrame(data)
    df.to_csv('test_results.csv', index=False)
    st.write('Result saved successfully!')

if __name__ == '__main__':
    main()

Happy Streamlit-ing! :balloon:

2 Likes

Hey @tonykip thanks for the solution it solves problem in one way but creates newer one in another way, the functionality of the code is to save results into a csv file which the new code is fails to do. Also one more suggestion is, can I run list of lists to ask question instead of list of list of dictionaries…?

questions = [
        {
            'question': 'What is the output of the following code?\n\n```python\nx = 5\nprint(x)\n```',
            'options': ['5', '10', '0', 'Error'],
            'correct_answer': '5'
        },
        {
            'question': 'Which of the following is a Python data type?',
            'options': ['List', 'Streamlit', 'GitHub', 'HTML'],
            'correct_answer': 'List'
        },
        {
            'question': 'What is the result of the expression 3 + 7 * 2?',
            'options': ['13', '20', '17', 'Error'],
            'correct_answer': '17'
        }
        # Add more questions here...
    ]

I expect your reply…