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

Python实现Linear search线性搜索运行后无法输出预期结果如何排查

你代码的核心错误是类型不匹配:Python中input()函数默认返回字符串类型,而你用来对比的数组arr中存储的都是整数,字符串和整数做相等判断永远返回False,因此永远无法匹配到目标值。

修复方案

  • 将输入的内容转换为整数类型,把第一行代码修改为:n = int(input("enter a number: "))
  • 额外说明:Python中语句末尾不需要加分号,原代码里count = 0;的分号属于冗余写法,可直接删除。

修正后的完整可运行代码:

n = int(input("enter a number: "))
arr = [1,42,3,45,5]
count = 0
for i in range(0, len(arr)):
    if arr[i] == n:
        count = count + 1
if count>0:
    print("found")
else:
    print("not found")

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.05 22:00:00