Blxck
Blxck

Reputation: 17

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. 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. 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?

Upvotes: 0

Views: 37

Answers (1)

Barmar
Barmar

Reputation: 781004

Use elif for a sequence of mutually exclusive conditions. The final else: will be used if none of them were true.

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.")

Upvotes: 2

Related Questions