你,因爲你使用player1
和player2
定義之前收到此錯誤。這很容易解決:
def player():
player1 = ''
player2 = ''
# The rest of your code here...
雖然你的代碼還有一些其他問題。例如:
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
這return
在while
循環將作爲你的歡迎player1
儘快退出功能。但是,你說你想提示第二個玩家,所以它應該是break
。接下來,當我做這些更正,然後刪除該函數入解釋,這是我得到:
>>> 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
>>>
你空player1
& player2
都不會回來了α,所以你永遠不會得到提示用於輸入。請參閱以下內容:
>>> player1 = ''
>>> assert player1.isalpha()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AssertionError
>>>
更新
通過我以爲這下一塊的時候,別人也發佈了類似的回答。我將包括我的看看在做不同的方式。
我真的使用類似以下內容:
>>> 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'
>>>
這將允許你要求的球員,比如任意數:
>>> 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',]
>>>
這樣,如果你目前的遊戲tic-tac-toe(或其他)有朝一日會成爲一個有n個玩家的n維遊戲場的超級井字遊戲,你不必完全重寫和重新調試你的player()
函數。或者您已準備好將相同的功能放入您的下一個遊戲中。
您正在**'player1 = input(...)'之前測試'player1.isalpha()'** ... – jonrsharpe
[詢問用戶輸入信息直到他們給出有效響應]( http://stackoverflow.com/questions/23294658/asking-the-user-for-input-until-they-give-a-valid-response) – jonrsharpe
那麼,'player1'沒有被定義或分配,然後再調用' isalpha()'方法,導致這個錯誤。順便說一句,你的代碼不會做你認爲它應該做的事。 – MasterAM