[英]Why ELSE statement is executed before IF statement?
当我尝试检查一个值是否在我的 JSON 列表中时,else 语句在我的 IF 语句之前执行。
所以如果我写下名字:MartinDufour,程序会告诉我 NO 然后告诉我 YES。 哪个不正常..(看下面的短程序就明白了)
import json
with open("user.json") as k:
data = json.load(k)
def addlb():
for i in data["person"]:
if i["Name"] == name:
print("Yes")
break
else:
print("No")
print("Write the Name:")
name = input()
addlb()
用户.json
{
"person": [
{
"Name": "Peter",
"Number": "5143324232"
},
{
"Name": "MartinDufour",
"Number": "5147745840"
},
{
"Name": "OlivierDeschamps",
"Number": "5145544029"
},
{
"Name": "DenisCodere",
"Number": "5143324242"
}
]
}
您还可以使用内置函数any
,如果任何条件返回 True 则返回 True 否则返回 False 。
import json
with open("user.json") as k:
data = json.load(k)
def addlb(name):
found = any(n['Name'] == name for n in data['person'])
print('Yes' if found else 'No')
print("Write the Name:")
name = input()
addlb(name)
你可以做这样的事情
import json
with open("user.json") as k:
data = json.load(k)
def addlb():
found_name=False
for i in data["person"]:
if i["Name"] == name:
found_name=True
break
if found_name:
print("Yes")
else:
print("No")
print("Write the Name:")
name = input()
addlb()
您在这里所做的是注意您是否使用found_name
变量找到了名称。 如果您从未找到它,则found_name
将保持为 false。 如果它找到了它,那么它就会被设置为 true。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.