如何使"else"块在此代码中只出现一次



我有这个代码:

vesi = ["Cody", "Dwight", "Jesse", "Justine", "Nneka", "Noelle"]
coco = ["Cassidy", "Geo", "James", "Karla", "Lindsay", "Ryan"]
baka = ["Elie", "Jeanine", "Mike", "Morriah", "Owen", "Sami"]
playername = input("Enter player name:")
if playername in vesi:
print(f"{playername} is a member of the Vesi tribe.")
break
else:
print("Username is invalid or does not exist in the Vesi, Coco, or Baka tribe. Please try again.")
break
if playername in coco:   
print(f"{playername} is a member of the Coco tribe.")
break
else:
print("Username is invalid or does not exist in the Vesi, Coco, or Baka tribe. Please try again.")
break
if playername in baka:
print(f"{playername} is a member of the Baka tribe.")
break
else:
print("Username is invalid or does not exist in the Vesi, Coco, or Baka tribe. Please try again.")
break

当我尝试这个代码时,我会从ifelse块中得到消息。例如:

Enter player name:Geo
Geo is a member of the Coco tribe.
Username is invalid or does not exist in the Vesi, Coco, or Baka tribe. Please try again.

在阅读了其他一些答案后,我尝试使用break,但似乎没有帮助。我怎样才能使";用户名无效";只有当名字不在任何部落中时,信息才会出现,并且只出现一次?

对互斥条件序列使用elif。如果它们都不是真的,那么将使用最终的else:

if playername in vesi:
print(f"{playername} is a member of the Vesi tribe.")
elif playername in coco:   
print(f"{playername} is a member of the Coco tribe.")
elif playername in baka:
print(f"{playername} is a member of the Baka tribe.")
else:
print("Username is invalid or does not exist in the Vesi, Coco, or Baka tribe. Please try again.")

最新更新