首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用if...then...else检查对象是否已经存在

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

Stack Overflow用户
提问于 2016-03-17 12:18:19
回答 2查看 100关注 0票数 0

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

为你的新动物输入一个名字:狗新生物已经被创建。这种动物的名字是:动物已经存在的狗。

它创建了新的生物,但同时也显示了“生物已经存在”的信息。我如何摆脱这条信息,使它只出现在生物已经存在的时候?

代码语言:javascript
复制
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")
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2016-03-17 12:32:52

您正在noc中测试每个已经存在的生物,如果您已经使用了多个生物,并且已经使用了已选择的名称,那么您最终会添加一个新的生物,并抱怨名称已经存在。

分离这两个测试;首先查看名称是否已经存在,并且只在循环完成时添加新的评测器:

代码语言:javascript
复制
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语句, not if语句):

代码语言:javascript
复制
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循环完成所有迭代而没有break时,才会执行for循环的for块。因为只有在找到匹配的名称时才执行break,所以您可以安全地假设没有这样的名称,并在else块中创建一个新的Critter()

票数 2
EN

Stack Overflow用户

发布于 2016-03-17 12:24:12

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/36060360

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档