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

Python数组查找异常:输入值存在却始终提示未找到如何解决

问题原因

代码的核心问题是类型不匹配:

  • Python 中input()函数返回的用户输入默认是字符串类型,而数组a中存储的全部是整数类型
  • 字符串与整数做相等判断时,即使字面量数值一致,结果也永远为False,所以永远会触发未找到的逻辑。

修复代码

只需要将用户输入转换为整数类型即可,修改后代码如下:

a = [2,5,7,9,11]

# 将输入的字符串转为整数类型
cari = int(input("Input the value : "))
ketemu = False
for i in range(0, len(a)):
    if cari == a[i]:
        ketemu = True
        break

if ketemu:
  print("Value: ", cari, "found it")
else:
  print("Value: ", cari, "not found")

简化方案

Python 内置in运算符可以直接判断元素是否存在于序列中,不需要手动遍历,代码可以简化为:

a = [2,5,7,9,11]
cari = int(input("Input the value : "))
if cari in a:
    print(f"Value: {cari} found it")
else:
    print(f"Value: {cari} not found")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 02:48:01