简体   繁体   English

如何使 `else` 块在此代码中仅出现一次?

[英]How can I make the `else` block only occur once in this code?

I have this code:我有这个代码:

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

When I try this code, I get messages from both if and else blocks.当我尝试这段代码时,我会从ifelse块中收到消息。 For example:例如:

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.

After reading some other answers, I tried using break , but it does not seem to help.在阅读了其他一些答案后,我尝试使用break ,但似乎没有帮助。 How can I make it so that the "Username is invalid" message only appears if the name is not in any of the tribes, and make it only appear once?如何才能使“用户名无效”消息仅在该名称不在任何部落中时出现,并使其仅出现一次?

Use elif for a sequence of mutually exclusive conditions.elif用于一系列互斥条件。 The final else: will be used if none of them were true.最后的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.")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM