Do I need a session state or something else for a very basic guess a number app?

Hi everyone - I have a very simple question (I think :slight_smile: ). I have been trying to teach my kids to use streamlit and we decided to write a very simple “Guess a number” app. It generates a random number between 1 and 10 and asks the user to guess. The problem is, when a user enters the number and submits the guess the program re-runs and another number is generated.
Is there a way around it? Can I save somewhere the random number generated prior to an event (e.g. button click or Enter click in the input box)?

Please let me know whether it will require session state or something else?

Thank you in advance!

Hi @Negmat_Mullodzhanov,

You can define a function that returns a random number and then decorate it with st.cache.

@st.cache
def generate_random_number():
    return random.randint(1,100)

x = generate_random_number()

To generate a new number after guessing correct you can clear the cache or make the function accept some variable that’s passed to the function so it’s re-run after a correct guess.

https://docs.streamlit.io/en/stable/api.html#streamlit.cache

2 Likes

Hi,

Thank you very much for the help it worked! It was a very simple problem, but a learned a few interesting things trying to do it (@st.cache and how to clear it). Pasting code here in case it will help someone solve a more real/complex problem:

Blockquote

import streamlit as st

import random

import math

from streamlit import caching

st.title(“Guess a number”)

@st.cache

def get_random_number():

return str(math.floor((random.random()) * 10) + 1)

random_number = get_random_number()

number_entered = st.text_input(“Guess a number betwen 1 and 10”)

if st.button(“Submit Answer”):

if number_entered == random_number:

    caching.clear_cache()

    st.balloons()

else:

    st.write("You are wrong!")

Blockquote

2 Likes