所以我需要这个来检查他们想要的用户名是否已经被采用但是我认为它不是最有效的方式而且它打印出3" USERNAME TAKEN"想要知道最有效的方法来检查它是否已经在文本文件中,然后再次询问用户名。
z = "I"
while z == "I" :
print ("What would you like your username to be?")
username = input()
u = open ("USERNAME.txt", 'r')
for line in enumerate(u, 1):
if username in line :
u.close()
z = "A"
break
else :
print ("USERNAME TAKEN")
z = "I"
答案 0 :(得分:0)
z = "I"
while z == "I" :
print ("What would you like your username to be?")
username = raw_input()
if username in open('example.txt').read():
print "Username taken"
else:
print "Username available"
z='A'
答案 1 :(得分:-1)
Shijo在这里有最紧凑的答案,但我认为值得提出使用一种方法来检查是否已经使用了用户名,因为检查它的代码可以在以后重用,并且它会使更大的程序更具可读性
def username_taken(username):
u = open("USERNAME.txt", "r")
if username in u.read().splitlines():
return True
else:
return False
while True:
print ("What would you like your username to be?")
username = input()
if username_taken(username) == True:
print ("Username Taken, please choose again.")
else:
print ("Username is valid.")
break