Search code examples
pythonpython-3.xvalidationdefinition

How would I do a definition for a name validation


What I want to do:

I am trying to make a definition that takes an input (name as string) and checks if the name is in a set list.

If it is, the program will continue. If it isn't, it will give the user 2 more chances to enter their name correctly.

Requirements:

I need to use the name variable after the definition. I need the system to exit if the name is wrong 3 times.

Problems:

If the name is correct it works properly However, if the name is wrong, it doesn't allow another name input, printing "You have 2 more tries" and "You have 1 more try" then ends the loop and exits.

Code:

names_allowed_to_play = ["MUM","DAD"]

def val_1 (name_1):

    print("Player 1, you have 3 tries to enter the correct name")
    print("")
    a = 0
    
    while a < 3:

        
        name_1 = name_1.upper()

        if name_1 in names_allowed_to_play:
            print(name_1 + ", you are authorised to play, have fun!")
            print("")
            a = a + 4
            names_allowed_to_play.remove(name_1)
            
        elif name_1 not in names_allowed_to_play:
            
            a = a + 1

            if name_1 not in names_allowed_to_play and a ==1:
                print("You have 2 more tries")
                print("")
                print("")
            elif name_1 not in names_allowed_to_play and a ==2:
                print("You have 1 more try")
                print("")
                print("")

    if a == 3:
        print("")
        print("Sorry Player 2, " + name_1 + " ruined it! " + name_1 + ", you are NOT AUTHORISED!")
        sys.exit()
        


#Run definition
name_1 = input("Player 1, please enter your name to play: ")
val_1(name_1)

Solution

  • I have fixed your code problem.

    names_allowed_to_play = ["MUM", "DAD"]
    def val_1():
       print("Player 1, you have 3 tries to enter the correct name")
       name_1 = input("enter your name")
       a=0
       while a < 3:
           name_1 = name_1.upper()
           if name_1 in names_allowed_to_play:
               print(name_1 + ",you are authorised to play, have fun!")
               a = a + 4
               names_allowed_to_play.remove(name_1)
           elif name_1 not in names_allowed_to_play:
               a = a + 1
               if name_1 not in names_allowed_to_play and a == 1:
                   print("You have 2 more tries")
                   name_1 = input("enter your name")
                   print("")
               elif name_1 not in names_allowed_to_play and a == 2:
                   print("You have 1 more try")
                   name_1 = input("enter your name")
               elifa == 3:
                   print("")
                   print("Sorry Player 2, " + name_1 + " ruined it! " + name_1 + ", you are NOT AUTHORISED!")
                   exit()
    
    val_1()