解决方案
users = []
print("Welcome to The 'Create New User' Interface")
x = input("Enter Name to Use for Account Access\n*Name is Case Sensitive to Access Account*: ")
while x in users:
x = input("That User Already Exists! Enter a New Name: ")
users.append(x)
print("Your Account Access Name is: " + str(x))
只需将您的 if 循环更改为 while 循环,该循环将一直持续到给出唯一名称为止。
建议
users = []
print("Welcome to The 'Create New User' Interface")
while True:
user_name = '' #now users can not enter a empty user_name
while not user_name:
user_name = input("Enter Name to Use for Account Access: ")
for i in range(0, len(users)): #different loop to enable use of lower()
while user_name.lower() == users[i].lower(): #removes need for unique cases
print("That User Already Exists!")
user_name = '' #again stopping empty fields
while not user_name:
user_name = input("Enter Name to Use for Account Access: ")
users.append(user_name)
print("Your Account Access Name is: " + user_name)
首先,我们可以创建一个循环来拒绝任何空白user_name。
接下来我们可以在检查user_name 是否存在于users[] 时使用.lower()。通过这样做,我们可以保留用户想要用来存储其姓名的唯一大小写格式(可能用于显示目的),但同时我们可以检查user_name 是否已经存在,无论大小写格式如何。
清理它,我们可以这样做:
def ask_user(message=''): #create function to check for blank inputs
user_name = ''
while not user_name:
user_name = input(message)
return user_name
users = []
print("Welcome to The 'Create New User' Interface")
while True:
user_name = ask_user("Enter Name to Use for Account Access: ")
for i in range(0, len(users)):
while user_name.lower() == users[i].lower():
print("\nThat User Already Exists!") #newline for clarity
user_name = ask_user("Enter Name to Use for Account Access: ")
users.append(user_name)
print("\nYour Account Access Name is: " + user_name) #newline for clarity
在这里我创建了处理空白输入的ask_user。然后在几个地方添加了\n 以帮助提高可读性。
输出
(xenial)vash@localhost:~/pcc/10$ python3 helping.py
Welcome to The 'Create New User' Interface
Enter Name to Use for Account Access:
Enter Name to Use for Account Access: vash
Your Account Access Name is: vash
Enter Name to Use for Account Access: VASH
That User Already Exists!
Enter Name to Use for Account Access:
Enter Name to Use for Account Access: p0seidon
Your Account Access Name is: p0seidon
Enter Name to Use for Account Access: P0SEidoN
That User Already Exists!
希望这会有所帮助!