我编写了一个简单的游戏,在游戏开始时需要两个玩家的名字。我想看看它们是否有重复的名称,如果有,我想重复这两个输入,直到它们没有重复的名称。有人知道怎么做吗?
# 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'
您可以使用一个可以再次调用的函数来完成此操作,甚至可以检查不允许的名称等:
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()
输出:
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
您可以使用while
而不是if
:
while player_one == player_two:
print("Please enter a different name. ")
# Code here that says 'repeat player_one and player_two'
然后,您将反复提示输入新名称,直到名称不同为止。