从函数:(返回值[复制]

Returning values from a function :( [duplicate]

提问人:ceskeff11 提问时间:11/25/2022 更新时间:11/25/2022 访问量:47

问:

请有人解释一下这里出了什么问题吗? 不幸的是,我的任务是使用函数完成此操作;否则,我会使用像 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")

我的代码^

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 函数 参数 boolean boolean-logic

评论

1赞 UnholySheep 11/25/2022
Python 是按值传递的,因此在函数内部编写不会获得任何结果,因为它只会修改函数内部的变量b = True
0赞 ceskeff11 11/25/2022
你能详细说明一下,我能做些什么来解决这个问题吗?
0赞 UnholySheep 11/25/2022
在所有代码路径中返回一个值,然后实际使用它,而不是像现在这样忽略它
0赞 Vin 11/25/2022
@ceskeff11,当你传递给你的函数时,该函数会接受 的值,将其分配给局部变量,然后用 做一些事情。原始变量实际上没有发生任何事情 - 它的 VALUE 被传递到函数中,然后使用。当函数调用结束时,保持不变 - 因此,当您运行块时,计算结果始终为 。zcount1zbbzzif z==TruezFalse
0赞 ceskeff11 11/25/2022
@vin有什么方法可以返回 b 的值并将其分配给 z 的值?

答:

0赞 Vin 11/25/2022 #1

解决眼前问题的基本方法是修改要读取的行。count1(a, z)z = count1(a, z)

这样,你给你的 ,允许修改,然后用你的 生成的新值覆盖旧的值。zcount1count1zzcount1

也就是说,你的代码中有很多你并不真正需要的东西。做你正在尝试的事情的一个简洁的方法是:

scores = [3,7,6,9,4,3,5,2,6,8]

def count1(scores):
    y = int(input("What score are you searching for in the scores array?  "))
    print (f'{y} is {"" if y in scores else "not "}in the array.')
    
count1(scores)

试试这个:

What score are you searching for in the scores array?  3
3 is in the array.

What score are you searching for in the scores array?  12
12 is not in the array.

评论

0赞 ceskeff11 11/25/2022
将我的函数的返回值分配给 z 有效 - 非常感谢