[Python] How to i fix the point system in this program?

Discussão em 'Python' iniciado por Stack, Julho 6, 2025.

  1. Stack

    Stack Membro Participativo

    I've been trying to get it right but still can't, what i need the code to do is just and a point system which tracks the users right answers and wrong answers and prints the current amount of points scored by user after each question. (And maybe also display the current updated overall score somewhere on the lessons page.

    I've used streamlit library for this project.

    This is my pointsys.py


    import streamlit as st
    import time

    # Initialize score
    if "points" not in st.session_state:
    st.session_state.points = 0

    # Function to display current score
    def show_score():
    st.markdown(f"### Your current score: `{st.session_state.points}`")

    # Function to handle correct or incorrect answer
    def pointsys(bin):
    if bin == "true":
    st.session_state.points += 4
    st.success("✅ Correct! +4 points")
    elif bin == "false":
    st.session_state.points -= 1
    st.error("❌ Incorrect! -1 point")
    show_score()

    This is my answer.py


    import streamlit as st
    import time
    from pointsys import pointsys, show_score

    points = 0
    niga = []


    def _init_answer_store():
    if "answers" not in st.session_state:
    st.session_state.answers = {}

    def answers(question_id, options, label= None, py_ex= None):
    _init_answer_store()

    answered_correctly = st.session_state.answers.get(question_id, {}).get("correct", False)

    st.subheader(f"Question: {label or question_id}")

    if py_ex:
    st.code(py_ex, language = "python")


    if answered_correctly:
    selected = st.session_state.answers[question_id]["user_answer"]
    st.success(f"✅ You already answered correctly: {selected}")
    return True

    cols = st.columns(len(options))
    for i, (label, is_correct) in enumerate(options):
    with cols:
    if st.button(label, key=f"{question_id}_{i}"):
    if is_correct:
    st.session_state.answers[question_id] = {
    "correct": True,
    "user_answer": label
    }
    st.success("✅ Right answer!")
    refresh_page()
    return True
    else:
    wrong()
    return False

    def strans(question_id, correct_answers, label= None, py_ex = None):

    _init_answer_store()

    answered_correctly = st.session_state.answers.get(question_id, {}).get("correct", False)

    st.subheader(f"Question: {label or question_id}")
    if py_ex:
    st.code(py_ex, language = "python")

    if answered_correctly:
    saved = st.session_state.answers[question_id]["user_answer"]
    st.success(f"✅ You answered correctly: {saved}")
    return True

    user_input = st.text_input("Your answer:", key=f"input_{question_id}")

    if user_input:
    if user_input.strip() in [ans for ans in correct_answers]:
    st.session_state.answers[question_id] = {
    "correct": True,
    "user_answer": user_input.strip()
    }
    st.success("✅ Right answer!")
    pointsys("true")
    time.sleep(1)
    refresh_page()
    return True
    else:
    pointsys("false")
    wrong()
    return False

    def wrong():
    st.error("❌ Try again.")
    def ttxt(tip, second):
    placeholder = st.empty()
    for i in range(second, 0, -1):
    placeholder.info(f" Your tip will appear in {i} seconds...")
    time.sleep(1)
    placeholder.success(tip)

    def refresh_page(delay: float = 0.5):
    time.sleep(delay)
    st.rerun()

    And this is my "Lesson2questions.py"


    import streamlit as st
    from answer import answers, strans, ttxt, refresh_page

    st.set_page_config(initial_sidebar_state="collapsed")


    st.title("Lesson 2: Variable Basics")

    # --- Tip State Init ---
    if "tip_q1" not in st.session_state:
    st.session_state.tip_q1 = False
    if "tip_q3_1" not in st.session_state:
    st.session_state.tip_q3_1 = False
    if "tip_q3_2" not in st.session_state:
    st.session_state.tip_q3_2 = False


    q1 = answers("q1_assignment", [
    ("1. x='10'", False),
    ("2. x==10", False),
    ("3. x-10", False),
    ("4. x=10", True),
    ], "What is the correct way to assign a value to a variable?")

    if not st.session_state.tip_q1:
    if st.button("Need a tip for Q1?"):
    ttxt("Use '=' for assignment, '==' for comparison.", 3)
    st.session_state.tip_q1 = True


    q2 = answers("q2_value", [
    ("1. x", False),
    ("2. 5", True),
    ("3. null", False),
    ("4. idk", False),
    ], "What is the value of x after `x = 5`?")


    q3 = strans("q3_type", ["str", "string", "String", "Str"], "What is the data type of x = 'Hello'?")

    if not st.session_state.tip_q3_1:
    if st.button("Want a tip for Q3?"):
    ttxt("It's a text data type.", 3)
    st.session_state.tip_q3_1 = True

    elif not st.session_state.tip_q3_2:
    if st.button("Want the answer for Q3?"):
    ttxt("It's 'string' or 'str'.", 5)
    st.session_state.tip_q3_2 = True



    st.divider()
    if not (q1 and q2 and q3):
    st.warning("⏳ Please answer all questions correctly to continue.")
    else:
    st.success(" All questions correct! You may proceed.")
    if st.button("Next lesson"):
    st.switch_page("pages/Lesson3.py")

    Continue reading...

Compartilhe esta Página