Skip to content
Advertisement

Streamlit python variable declaration

I wrote some dummy code to replicate my problem. I need to do some simple computations in Streamlit, but I can’t seem to find out how they handle variables and how to store info Here is my example:

import streamlit as st

sidebarOption = st.sidebar.radio('Options',("A","B","C"))

if sidebarOption == 'A':

    param1 = st.number_input('Value 1', min_value=1.0, max_value=100.0, value =20.0, step=0.1 )
    param2 = st.number_input('Value 2', min_value=1.0, max_value=50.0, value =24.0, step=0.1 )
    
elif sidebarOption == 'B':
    param3 = st.number_input('Value 3', min_value=1.0, max_value=100.0, value =20.0, step=0.1 )
    param4 = st.number_input('Value 4', min_value=1.0, max_value=50.0, value =24.0, step=0.1 )
    

elif sidebarOption == 'C':
    add = param1+param3
    st.write('Add:', add)

I get the error:

NameError: name 'param1' is not defined

What am I doing wrong?

Advertisement

Answer

The question has nothing to do with Streamlit, the variables are just not defined. Let me rewrite your code without the Streamlit part and with added comments to see if that clarifies things:

option = 'C'

if option == 'A':
    foo = 1 # this line is not executed, since option is not A
elif option == 'B':
    bar = 2 # this line is not executed, since option is not B
elif option == 'C':
    # the code below is executed, but foo and bar are undefined, so there is an error
    baz = foo + bar
    print(baz)

Does the error make more sense? If you want to add foo and bar, they must be defined first, which is not the case here.

If you are sure that the code will be called with options A and B before option C, then it should work. But then you’d be better off setting some default values beforehand, like foo = None and bar = None. You’d still get an error if they are still None at the C step, but that would be clearer.

Or maybe you what you are looking for are session states?

User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement