为什么ELSE语句在IF语句之前执行?

时间:2020-01-28 21:56:11

标签: python json if-statement

当我尝试检查JSON列表中是否有值时,else语句在IF语句之前执行。

因此,如果我输入名称:MartinDufour,程序将告诉我“否”,然后告诉我“是”。这不正常..(请参阅下面的简短程序以了解

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()

user.json

{
  "person": [
    {
      "Name": "Peter",
      "Number": "5143324232"
    },
    {
      "Name": "MartinDufour",
      "Number": "5147745840"
    },
    {
      "Name": "OlivierDeschamps",
      "Number": "5145544029"
    },
    {
      "Name": "DenisCodere",
      "Number": "5143324242"
    }
  ]
}

2 个答案:

答案 0 :(得分:2)

您还可以使用内置函数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)

答案 1 :(得分:1)

您可以这样做

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将保持为假。如果找到了,它将设置为true。