Hi,
I am trying to make a simple app that could be used to multiply two integers (by using random numbers):
from random import randint
import streamlit as st
x = randint(1, 10)
y = randint(1, 10)
result = x * y
st.write(x, ' * ', y , '= ') #, x*y)
st.write('_________')
answer = int(st.text_input('Please enter your answer ', 1))
st.write('Your answer is', answer)
st.write('The correct answer is', result)
if answer == result:
st.success('Your answer is correct!')
st.balloons()
else:
st.warning("OOOPS, please try again!")
When I run the code it gives me “OOOPS, please try again!”, as shown in the figures:
I think the problem comes from this statement answer = int(st.text_input('Please enter your answer ', 1)). Could anybody help, please?
Hi @Yasser_Mustafa. Welcome to the community!!
The problem is that Streamlit will rerun yours script from top to bottom each time, which means that x
and y
will get new random values each time the script is executed. You can fix that by using st.cache
.
You might also consider using st.number_input
instead of st.text_input
.
That means your code would look like this:
from random import randint
import streamlit as st
@st.cache
def get_two_random_numbers():
x = randint(1, 10)
y = randint(1, 10)
return x, y
x, y = get_two_random_numbers()
result = x * y
st.write(x, ' * ', y , '= ') #, x*y)
st.write('_________')
answer = st.number_input('Please enter your answer ', 1)
st.write('Your answer is', answer)
st.write('The correct answer is', result)
if answer == result:
st.success('Your answer is correct!')
st.balloons()
else:
st.warning("OOOPS, please try again!")
Thanks for using Streamlit!
1 Like
Thank you very much@Adrien_Treuille, I really like Streamlit.
2 Likes