Python函数返回值问题:数组元素查找结果与预期不符求助
问题分析:自定义查找函数返回结果异常的原因
问题场景
要求用自定义函数实现数组元素查找,不能使用count()这类内置函数,代码如下:
scores = [3,7,6,9,4,3,5,2,6,8] y = int(input("What score are you searching for in the scores array? ")) a = len(scores) z = False def count1(c,b): for d in range(0,c): if scores[d] == y: print("yes") b = True return(b) else: print("no") count1(a,z) if z == True: print(y, "occurs in the array") else: print(y, "does not occur in the array")
输入数组中存在的元素3后,输出如下:
Python 3.7.5 (tags/v3.7.5:5c02a39a0b, Oct 15 2019, 00:11:34) [MSC v.1916 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license()" for more information. >>> = RESTART: C:\Users\18skeffingtonc\ What score are you searching for in the scores array? 3 yes 3 does not occur in the array
问题根源
核心问题在于Python不可变类型的传递逻辑:
- 布尔值属于不可变类型,调用
count1(a,z)时,函数内部的b只是外部z的副本,修改b = True只会改变函数内的局部变量,不会影响外部的z。 - 虽然函数返回了修改后的
True,但你没有将这个返回值赋值给外部的z,导致z始终保持初始的False,最终判断错误。
另外还有两个冗余问题:
- 循环中每次不匹配都打印"no",会输出大量无关信息,完全没必要。
- 函数名
count1和实际功能不匹配,这个函数是做存在性检查,而非计数。
修正方案
方案一:接收函数返回值(推荐)
直接将函数的返回值赋值给z,同时优化函数逻辑:
scores = [3,7,6,9,4,3,5,2,6,8] y = int(input("What score are you searching for in the scores array? ")) def is_exists(arr, target): for num in arr: if num == target: return True return False # 将函数返回值赋值给z z = is_exists(scores, y) if z: print(y, "occurs in the array") else: print(y, "does not occur in the array")
方案二:用可变类型传递(不推荐,可读性差)
如果一定要通过修改外部变量实现,可以用列表这类可变类型包裹布尔值,让函数内部能修改外部变量的内容:
scores = [3,7,6,9,4,3,5,2,6,8] y = int(input("What score are you searching for in the scores array? ")) z = [False] # 用列表包裹布尔值,变成可变类型 def check_exists(arr_length, flag): for d in range(arr_length): if scores[d] == y: flag[0] = True return check_exists(len(scores), z) if z[0]: print(y, "occurs in the array") else: print(y, "does not occur in the array")
内容的提问来源于stack exchange,提问作者ceskeff11
相关产品推荐
相关产品推荐

