所以最近我一直在做一个编码项目,我想使用一个包含所有有效用户名的外部文件(.txt文件(。在这段代码中,我正在验证P1Username是否有效。如果用户名有效,它将继续到代码的后面部分。如果用户名无效(不在.txt文件中(,它会询问他们是否希望在用户可以选择注册的地方注册(name添加到.txt文件(或不注册(用户称为Player 1(
问题是,此代码允许将所有名称输入为有效名称,并且不输出任何打印语句。有人知道该怎么办吗?
valid=False
username=open("username.txt","r")
lines=username.readlines()
P1Username=input("Enter your username Player 1: ")
for counter in range(len(lines)):
if P1Username==str(lines[counter]):
print("Valid usernamenHello "+str(P1Username))
valid=True
break
elif valid==False and counter<len(lines):
next
elif valid==False and counter>=len(lines):
enter=""
while enter!="yes" and enter!="no":
enter=input("Would you like to register "+P1Username+"? (yes or no) ")
if enter=="yes":
username=("username.txt","a")
username.write(P1Username)
username.write("n")
print(P1Username+" is now a registered loginnHello "+P1Username)
break
elif enter=="no":
P1Username="Player 1"
print("You did not register the usernamenI will refer to you as Player 1")
break
else:
print("Enter yes or no")
我建议使用for each
循环,而不是像使用计数器那样通过索引进行for
循环迭代:
valid=False
usernames=open("username.txt","r")
P1Username=input("Enter your username Player 1: ")
for line in usernames.readlines():
if P1Username in line:
valid = True
{go on with your code}
在你的代码中,你会让用户创建他的用户,次数与你在文件中的名字一样多。使用上面的代码,您可以将验证与之后的过程分开。
我认为这将简化您的代码,允许更快更容易的修复。
本部分
if P1Username==str(lines[counter]):
print("Valid usernamenHello "+str(P1Username))
valid=True
break
将永远不会执行,因为lines[counter]
在末尾有换行符"\n",而用户输入没有。因此,即使名称已经在文本文件中,if条件也将被评估为False(即"username"one_answers"username\n"不相同。
本部分
elif valid==False and counter>=len(lines):
enter=""
while enter!="yes" and enter!="no":
enter=input("Would you like to register "+P1Username+"? (yes or no) ")
if enter=="yes":
username=("username.txt","a")
username.write(P1Username)
username.write("n")
print(P1Username+" is now a registered loginnHello "+P1Username)
break
elif enter=="no":
P1Username="Player 1"
print("You did not register the usernamenI will refer to you as Player 1")
break
else:
print("Enter yes or no")
将永远不会被执行,因为在for循环中,您使用的计数器将取从0到len(行(-1的值,因此counter>=len(lines)
永远不会为True。
所以我想要
with open("username.txt","r") as f:
usernames = [line.strip() for line in f]
player1 = input("Enter your username Player 1: ")
if player1 in usernames:
print(f"Valid usernamenHello {player1}")
else:
while True:
enter=input(f"Would you like to register {player1}? (yes or no) ").lower()
if enter == "yes":
with open("username.txt","a") as f:
f.write(f'{player1}n')
print(f"{player1} is now a registered loginnHello {player1}")
break
elif enter == "no":
player1="Player 1"
print("You did not register the usernamenI will refer to you as Player 1")
break
else:
print("Enter yes or no")