如何解决Streamlit应用中使用IF语句时出现的报错问题
问题分析与修复方案
代码中的核心问题
- 类型不匹配错误:
st.text_input返回字符串类型,直接和整数12比较会触发TypeError,必须先将输入转换为整数,同时要处理非数字输入的异常。 st.selectbox参数错误:该组件的正确格式是st.selectbox(标签, 选项列表),原代码把选项分开传参,会导致报错。- 变量未定义风险:当年龄≤12时,
name等变量不会被定义,后续调用st.write(f"{name}")会触发NameError。 - 逻辑冗余错误:
while循环在这里完全没必要,用if判断即可,且break语句在这里毫无意义。 - 无效赋值问题:
st.write()返回None,把它赋值给result后,输出result只会显示None。 - 输入框提示语格式错误:原代码直接拼接字符串作为输入框标签,应该用
placeholder参数设置提示文本,让界面更规范。
修正后的代码
import streamlit as st import pandas as pd st.write("Welcome to my Sample Survey App!") # 处理年龄输入,转换为整数并捕获异常 age_input = st.text_input("What is your age?", placeholder="Please enter your age here correctly") try: age = int(age_input) if age_input else None except ValueError: st.error("Please enter a valid number for age!") age = None # 年龄符合条件时显示问卷 if age and age > 12: name = st.text_input("What is your full name?", placeholder="Enter your full name") sex = st.selectbox("Select your gender:", ["Male", "Female"]) phone_number = st.number_input("Enter your phone number:", min_value=0) father_name = st.text_input("What's your father's name?", placeholder="Enter father's name") mother_name = st.text_input("What's your mother's name?", placeholder="Enter Mother's name") address = st.text_input("Where do you live?", placeholder="Enter your current address") # 提交按钮逻辑 if st.button("Submit", type="primary"): st.write(f"Thank you {name}! Thanks for your time.") # 年龄不符合条件时提示 elif age is not None and age <= 12: st.write("You are not qualified for this survey")
修复说明
- 新增异常处理,确保年龄输入为有效数字,避免类型错误。
- 修正
st.selectbox的参数格式,添加明确标签和选项列表。 - 将提交逻辑放在条件判断内,避免未定义变量的报错。
- 替换冗余的
while循环为elif判断,逻辑更清晰。 - 移除无效的
result赋值,直接在提交时输出感谢语。 - 使用
placeholder参数设置输入框提示文本,界面更友好。
内容的提问来源于stack exchange,提问作者Levis Vargbaye kerzuah
相关产品推荐
相关产品推荐

