Search code examples
pythonwhile-loop

How can I make a repeat until loop?


complete newbie here. I wanted to make the user enter a name that matches one of the names in the dictionary, else the program asks again until a correct name is entered. Here's the code:

class Yakuza:
    def __init__(self, name, clan):
        self.name = name
        self.clan = clan
        
    def present(self):
        print(f"Hello! I am {self.name} from the {self.clan} clan!")
        
user1 = Yakuza("Kiryu", "Dojima")
user2 = Yakuza("Nishikiyama", "Dojima")

Startup = input("Welcome to Yakuza 0! Press Enter to start.")

character_dictionary = {"Kiryu" : "Dojima Clan",
                        "Nishikiyama" : "Dojima Clan"}
print(character_dictionary)

character_select = input("Select your character: ")

while character_select in character_dictionary:

    if character_select == "Kiryu":
        user1.present()
            
    elif character_select == "Nishikiyama":
        user2.present()
    
    else:
        print("This character is not available. Try again")

I expected the loop to work until a correct name is entered but it keeps going forever. Also, does it matter whether the character_select input is in or out of the while loop?


Solution

  • class Yakuza:
        def __init__(self, name, clan):  # Fixed __init__ typo here
            self.name = name
            self.clan = clan
    
        def present(self):
            print(f"Hello! I am {self.name} from the {self.clan} clan!")
        
    user1 = Yakuza("Kiryu", "Dojima")
    user2 = Yakuza("Nishikiyama", "Dojima")
    
    Startup = input("Welcome to Yakuza 0! Press Enter to start.")
    
    character_dictionary = {"Kiryu": "Dojima Clan", "Nishikiyama": "Dojima Clan"}
    print(character_dictionary)
    
    while True:  # Changed the condition here
        character_select = input("Select your character: ")  # Moved inside the loop
        if character_select in character_dictionary:
            if character_select == "Kiryu":
                user1.present()
                break  # Exit the loop after successful execution
            elif character_select == "Nishikiyama":
                user2.present()
                break  # Exit the loop after successful execution
        else:
            print("This character is not available. Try again.")