0

I'm trying to enter two player names and have the program recognise when there is anything other than alphabetical characters in the names. The names should loop until they are entered correctly; currently, I get the error local variable 'player1' referenced before assignment.

def player():

    while (player1.isalpha()):
        player1 = input("What is the name of our first player? \n")
        print("Welcome " + player1)
        return
    else:
        print("Please enter a name without integers or spaces")
        return False


    while (player2.isalpha()):
        player2 = input("What is the name of our first player? \n")
        print("Welcome " + player2)
        break
    else:
        print("Please enter a name without integers or spaces")
        return True
player()

I'm reading about global assignment and that sounds bad in this case; any other suggestions?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
  • You're testing `player1.isalpha()` **before** `player1 = input(...)`... – jonrsharpe Apr 21 '15 at 12:13
  • possible duplicate of [Asking the user for input until they give a valid response](http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – jonrsharpe Apr 21 '15 at 12:13
  • Well, `player1` is not defined or assigned before you call the `isalpha()` method on it, causing this error. BTW, your code does not do what you think it is supposed to do. – MasterAM Apr 21 '15 at 12:13

3 Answers3

2

You must define player1 before performing a method on it.

player1=""
player2=""
while...

its not global because its in a function

hilcharge
  • 1,515
  • 3
  • 12
  • 18
1
def player(x):
    player=''
    pass=0
    while (not player.isalpha()):
        if pass != 0:
            print("Please enter a name without integers or spaces")
        pass += 1 
        player = input("What is the name of our player No.{}?\n".format(x))
    print("Welcome {} No.{}".format(player,x))
    return player

player1=player(1)
player2=player(2)
Costas
  • 343
  • 1
  • 6
1

You're getting this error because you're using player1 and player2 before you define them. This is easy to resolve:

def player():
    player1 = ''
    player2 = ''

    # The rest of your code here...

There are a few other issues with your code as well, though. For instance:

while (player1.isalpha()):
    player1 = input("What is the name of our first player? \n")
    print("Welcome " + player1)
    return
else:
    print("Please enter a name without integers or spaces")
    return False

This return in your while loop will exit the function as soon as you've welcomed player1. However, you said that you want to prompt for a second player, so it should be a break. Next, when I make those corrections and then drop the function into the interpreter, this is what I get:

>>> def player():
...     player1 = ''
...     player2 = ''
...     while (player1.isalpha()):
...         player1 = input("What is the name of our first player? \n")
...         print("Welcome " + player1)
...         break
...     else:
...         print("Please enter a name without integers or spaces")
...         return False
...     while (player2.isalpha()):
...         player2 = input("What is the name of our first player? \n")
...         print("Welcome " + player2)
...         break
...     else:
...         print("Please enter a name without integers or spaces")
...         return True
...
>>> player()
Please enter a name without integers or spaces
False
>>>

Your empty player1 & player2 are not coming back as alpha, so you're never going to get prompted for input. See the following:

>>> player1 = ''
>>> assert player1.isalpha()
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
AssertionError
>>>

Update

By the time I thought of this next piece, somebody else had also posted a similar answer. I'll include mine to take a look at a different way of doing it.

I would actually use something like the following:

>>> def get_player(n=1):
...   player = input("What is the name of player %d? " % n)
...   if not player.isalpha():  # Ask again, if non-alpha characters.
...     print("Please enter a name without integers or spaces!")
...     player = get_player(n)
...   return player
...
>>> player1 = get_player(1)
What is the name of player 1? Bob1
Please enter a name without integers or spaces!
What is the name of player 1? Bob
>>> assert player1 == 'Bob'
>>>

This will allow you to request an arbitrary number of players, such as:

>>> players = []
>>> try:
...   num = int(input("How many players? "))
... except ValueError:
...   print("Number of players must be an integer!")
... else:
...   for i in range(num):
...     players.append(get_player(i + 1))
...
How many players? 3
What is the name of player 1? Frodo
What is the name of player 2? Sam
What is the name of player 3? Merry
>>> assert players == ['Frodo', 'Sam', 'Merry',]
>>>   

That way, if your current game of tic-tac-toe (or whatever) someday becomes a game of hyper tic-tac-toe in an n-dimensional playing field with n players, you don't have to totally rewrite and re-debug your player() function. Or you're ready to drop that same function into your next game.

Deacon
  • 3,615
  • 2
  • 31
  • 52