在“创建新的生物”块中,我希望检查该生物是否已经存在。我在其中添加了一个if...then ...else结构,但是当我运行程序并尝试添加一个新的生物(不存在的)时,输出是:
为你的新动物输入一个名字:狗新生物已经被创建。这种动物的名字是:动物已经存在的狗。
它创建了新的生物,但同时也显示了“生物已经存在”的信息。我如何摆脱这条信息,使它只出现在生物已经存在的时候?
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")发布于 2016-03-17 12:32:52
您正在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)如果这不在函数中,则可以使用break和for...else (因此,将else块附加到for语句, not 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循环完成所有迭代而没有break时,才会执行for循环的for块。因为只有在找到匹配的名称时才执行break,所以您可以安全地假设没有这样的名称,并在else块中创建一个新的Critter()。
发布于 2016-03-17 12:24:12
使用for i in Critter.noc:代替if i.name in Critter.noc打印错误,否则使用Critter.noc.append(Critter(new_crit))
https://stackoverflow.com/questions/36060360
复制相似问题