我正在尝试创建一个程序来跟踪玩家的胜负率,现在我正在尝试让程序检查某个名称是否列在 txt 文件中,但它始终返回 false。
所以在里面def check_player,当我输入第一个名字时,它说它在列表中,但我输入的所有后续名称都返回为 false。.txt文件的内容是7个名字,我输入的第一个名字也是列表中的第一个名字,为什么它不检查整个文件以查看该名字是否存在?
编辑:我找到了一个更简单的方法来解决这个问题。考虑这个关闭
def NewGame():
print("how many people are in this game?")
people = int(input())
for num in range(people): #does it n times where n is the number of players
print("who is the Player in this game?")
player = input()
file_name = "Player_List.TXT" #initializes the name of the file it is pulled from
check = check_player(file_name, player) #go to def check_player and pass file & player
if check == False:
print("this player is not in the system.")
print("would you like to add them(Y/N)?: ")
add = input()
if add == "Y" or "y":
AddPlayer()
def check_player(file_name, player):
""" Check if any line in the file contains given string """
# Open the file in read only mode
with open(file_name, 'r') as read_obj:
# Read all lines in the file one by one
for line in read_obj:
# For each line, check if line contains the string
if player in line:
return True
else:
return False
函数式编程
相关分类