1

I have coded a simple game where I need the name of two players at the beginning. I want to see whether or not they have duplicate names and if they do, I want to repeat both of the inputs until they do not have duplicate names. Anyone know how to do this?

# Names
player_one = str(input("Enter P1's name")
player_two = str(input("Enter P2's name")

if player_one == player_two:
    print("Please enter a different name. ")
    # Code here that says 'repeat player_one and player_two'
Strohhut
  • 490
  • 1
  • 6
  • 22
HelpMePlz
  • 31
  • 1
  • You will need to put your ```IF``` inside a loop and after ```print("Please enter a different name. ")```, prompt for player_two name again. – alexherm Oct 23 '19 at 18:54

2 Answers2

0

You can do it with a function you can call again, you can even check for not allowed names etc.:

player_one = ""
player_two = ""

def getNames():
       # Names
       player_one = str(input("Enter P1's name")
       player_two = str(input("Enter P2's name")

def checkNames():
   if player_one == player_two:
      print("Please enter a different name. ")
      getNames()

def main():
  getNames()
  checkNames()

if __name__== "__main__":
  main()

Output:

Enter P1's name test
Enter P2's name test
Please enter a different name. 
Enter P1's name test
Enter P2's name ja
Strohhut
  • 490
  • 1
  • 6
  • 22
  • I am calling main() but it keeps coming up with 3 errors. Here are the errors: Traceback (most recent call last): File "U:\---\tictactoerr.py", line 28, in main() File "U:\--\tictactoerr.py", line 26, in main checkNames() File "U:\--\tictactoerr.py", line 20, in checkNames if player_one == player_two: NameError: name 'player_one' is not defined EDIT: Is there a neater way for displaying comments? I'm new to this website. – HelpMePlz Oct 23 '19 at 18:51
  • getNames() is the first time you use player_one and player_two ? Because then ofc. they are not defined in the other function. Edit: now it should work Global Vars are not best practice but if you need them everywhere in your game anyways its ok – Strohhut Oct 23 '19 at 18:58
  • @Strohhut: `getNames` still won't define them though; without a `global` declaration at the top of the function, it will have a local definition of `player_one` and `player_two` that has no relationship to the globals. Beyond that, recursion is generally an inferior solution to a simple loop; needing to build stack frames up indefinitely until the user finally gives a valid response can crash the interpreter, and even when it doesn't, it's wasteful when it's providing no benefit. – ShadowRanger Oct 23 '19 at 19:33
0

You could use while instead of if:

while player_one == player_two:
    print("Please enter a different name. ")
    # Code here that says 'repeat player_one and player_two'

You would then repeatedly prompt for new names until the names are different.

Strohhut
  • 490
  • 1
  • 6
  • 22
Adam
  • 3
  • 5