使用if ... then ... else in来检查对象是否已经存在

时间:2016-03-17 12:18:19

标签: python

在创建新的生物块中,我想检查生物是否已经存在。我在其中添加了一个if ... then ... else结构但是当我运行程序并尝试添加一个新的生物(那个已经不存在的那个)时,输出是:

  

输入新生物的名称:Dog New critter已创建。   这个生物被命名为:生物已经存在的狗

它创造了新的生物,但它也显示了消息"那个生物已经存在"。如何删除该消息,以便仅在生物已存在时才会出现?

class Critter(object):   
    noc = []
    # I have omitted ther rest of the code of the class for simplicity.

# main    
# Create a new critter/object using the class Critter and store it in the list named noc
new_crit = input("Enter a name for your new critter: ")
for i in noc:
    if i.name != new_crit:  # name is a parameter used in the class Critter
        Critter.noc.append(Critter(new_crit))
        print("New critter has been created. the critter is named: ", new_crit)
    else:
        print("That critter already exists")

2 个答案:

答案 0 :(得分:2)

您正在noc测试每个已经存在的生物,如果您有多个生物,则使用已选择的名称​​ ,结束添加新的生物都抱怨名称已经存在。

将两个测试去耦;首先看看名字是否已经存在,只有当循环完成时才 添加新的生物:

new_crit = input("Enter a name for your new critter: ")
for i in noc:
    if i.name == new_crit:  # name is a parameter used in the class Critter
        print("That critter already exists")
        return

# we can only get here if no such name was found, otherwise the function
# would have exited at the `return`
Critter.noc.append(Critter(new_crit))
print("New critter has been created. the critter is named: ", new_crit)

如果这不在函数内,您可以使用breakfor...else(因此请将else块附加到for语句, if语句:

new_crit = input("Enter a name for your new critter: ")
for i in noc:
    if i.name == new_crit:  # name is a parameter used in the class Critter
        print("That critter already exists")
        break
else:
    # we can only get here if no such name was found, otherwise the for 
    # loop would have ended at the `break`
    Critter.noc.append(Critter(new_crit))
    print("New critter has been created. the critter is named: ", new_crit)

else循环的for块仅在for循环完成所有迭代但没有break时执行。由于break仅在找到匹配的名称时执行,因此您可以放心地假设没有此类名称并在Critter()块中创建新的else

答案 1 :(得分:0)

使用for i in Critter.noc:打印错误代替if i.name in Critter.noc,否则Critter.noc.append(Critter(new_crit))