提问人:ceskeff11 提问时间:11/25/2022 更新时间:11/25/2022 访问量:47
从函数:(返回值[复制]
Returning values from a function :( [duplicate]
问:
请有人解释一下这里出了什么问题吗? 不幸的是,我的任务是使用函数完成此操作;否则,我会使用像 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
输入应为有效输入的输出^
答:
0赞
Vin
11/25/2022
#1
解决眼前问题的基本方法是修改要读取的行。count1(a, z)
z = count1(a, z)
这样,你给你的 ,允许修改,然后用你的 生成的新值覆盖旧的值。z
count1
count1
z
z
count1
也就是说,你的代码中有很多你并不真正需要的东西。做你正在尝试的事情的一个简洁的方法是:
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 有效 - 非常感谢
评论
b = True
z
count1
z
b
b
z
z
if z==True
z
False