You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python代码运行异常咨询:当option2取值为1时程序无法执行的原因排查

为什么当option2取值为1时我的Python DataFrame查询代码无法运行?

问题描述

我写了一段基于Python DataFrame的报告查询代码,当输入的option2为1时,程序没有执行预期的位置数据查询逻辑。相关代码如下:

option2 = ""
specificReport = "yes"
if specificReport == "yes":
    specificReport = str.lower(input("是否查看特定报告(是/否):" ))
    option2 = str.lower(input("你想要查询哪类数据(1. 位置,2. 风险类型,3. 风险等级,4. 日期与时间):"))
if option2 == 1:
    locationValue = input('请输入要查询的位置:')
    LocationRow = (dataframe.loc[dataframe['Location Name'] == locationValue])
    print(locationRow)

问题原因

核心问题是数据类型不匹配:

  • Python的input()函数不管用户输入什么内容,返回的结果都是字符串类型。也就是说当你输入"1"时,option2存储的是字符串"1",而非整数1。
  • 你的判断条件写的是option2 == 1,这里是用字符串和整数做相等比较,结果永远是False,所以后续的位置查询代码块根本不会被执行。

解决方案

你有两种简单的修复方式:

方式一:将判断条件改为字符串匹配

直接把判断值改成字符串"1",和input()返回的类型保持一致:

option2 = ""
specificReport = "yes"
if specificReport == "yes":
    specificReport = str.lower(input("是否查看特定报告(是/否):" ))
    option2 = input("你想要查询哪类数据(1. 位置,2. 风险类型,3. 风险等级,4. 日期与时间):")
if option2 == "1":  # 改为字符串"1"匹配
    locationValue = input('请输入要查询的位置:')
    LocationRow = dataframe.loc[dataframe['Location Name'] == locationValue]
    print(LocationRow)

注:这里去掉了str.lower(),因为数字输入转小写没有实际意义,反而会增加不必要的逻辑。

方式二:将option2转换为整数类型

把input()获取的结果转成整数,这样就能和整数1正常比较了(注意:如果用户输入非数字内容会触发报错,若需要更健壮的逻辑可以添加异常捕获):

option2 = ""
specificReport = "yes"
if specificReport == "yes":
    specificReport = str.lower(input("是否查看特定报告(是/否):" ))
    # 将输入转换为整数类型
    option2 = int(input("你想要查询哪类数据(1. 位置,2. 风险类型,3. 风险等级,4. 日期与时间):"))
if option2 == 1:
    locationValue = input('请输入要查询的位置:')
    LocationRow = dataframe.loc[dataframe['Location Name'] == locationValue]
    print(LocationRow)

内容的提问来源于stack exchange,提问作者Darren Wong

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.01 01:19:09