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.