[英]Streamlit python variable declaration
我寫了一些虛擬代碼來復制我的問題。 我需要在 Streamlit 中進行一些簡單的計算,但我似乎無法找出它們如何處理變量以及如何存儲信息這是我的示例:
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)
我得到錯誤:
NameError: name 'param1' is not defined
我究竟做錯了什么?
這個問題與Streamlit無關,只是沒有定義變量。 讓我在沒有 Streamlit 部分的情況下重寫您的代碼,並添加注釋以查看是否可以澄清事情:
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)
錯誤更有意義嗎? 如果要添加foo
和bar
,必須先定義它們,這里不是這樣。
如果您確定將在選項 C 之前使用選項 A 和 B 調用代碼,那么它應該可以工作。 但是你最好事先設置一些默認值,比如foo = None
和bar = None
。 如果它們在C
步驟中仍然為 None,您仍然會收到錯誤,但這會更清楚。
或者,也許您正在尋找的是 會話狀態?
會話狀態有效。 不知道它是否 100% 正確,但這適用於一個小測試示例:
import streamlit as st
from streamlit_option_menu import option_menu
"st.session_state object", st.session_statewith st.sidebar:
selected = option_menu(
menu_title= "Exposure time calculator",
options=['A', 'B', 'C'],
)
if selected == 'A':
param1 = st.number_input('val1', value=20.0, key='key1')
param2 = st.number_input('val2', value = 30.0, key = 'key2')
elif selected == 'B':
add = st.session_state.key1 + st.session_state.key2
divide = st.session_state.key1/st.session_state.key2
st.write(add)
st.write(divide)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.