在while循环中遇到问题时,它会中断,即使它不应该中断

2024-09-28 03:12:11 发布

您现在位置:Python中文网/ 问答频道 /正文

我有点麻烦了!你知道吗

我想做的是做一个简单的帐户创建系统。我希望用户输入用户名,如果用户名已经存在,应该让我再试一次。你知道吗

但是,即使用户名存在,它也会继续该函数,并向我请求密码,并将用户名和密码写入文件。你知道吗

代码如下:

def create_user():
    passw = open('passwords.txt', 'r+')
    x = 1
    passwr = passw.readlines()
    print "What's your username?"

    while x == 1:
        user = raw_input(">> ")
        for l in passwr:
            a = l.split()  
            if user.lower() not in a[0]:
                x = 0

            else:
                print 'Sorry, that\'s already in use!'

    print "What's your pw?"
    pw = raw_input(">> ")
    passw.seek(0, 2)
    passw.write(user + ' ' + pw + '\n')

文件格式如下:

Username1 Password
Username2 Password

我已经试着找出问题出在哪里了。但似乎找不出解决办法。你知道吗


Tags: in密码inputyourraw系统帐户password
3条回答

你的验证部分可以更简单,试试这样的方法

while x == 1:
    user = raw_input(">> ")
    usernames = [i.split()[0] for i in passwr]
    if user.lower() not in usernames:
            x = 0

    else:
            print 'Sorry, that\'s already in use!'

然后输出

What's your username?
>> Username1
Sorry, that's already in use!
>> Username2    
Sorry, that's already in use!
>> Username3
What's your pw?
>> Password

以及文件内容

username1 Password
username2 Password
Username3 Password

问题是,如果有任何具有不同用户名的用户,则设置x = 0。假设有两个现有用户,foobar。用户输入bar。发生这种情况:

  1. if user.lower() not in a[0]:产生True,因为user"bar"a[0]"foo"。你知道吗
  2. x设置为0。你知道吗
  3. 循环继续执行文件中的下一行,a[0]现在将是"bar"。你知道吗
  4. if user.lower() not in a[0]:产生False,并且Sorry, that's already in use!被打印。你知道吗
  5. 循环退出,因为x已设置为0。你知道吗

您需要检查==而不是in,因此您不需要额外赋值a = l.split(),请将if语句更改为:

if user.lower() == l.split()[0]

由于此操作用于检查一个id,如果您需要检查所有id,您可以在列表中获取所有id并检查:

while x == 1:
    user = raw_input(">> ")
    user-list=[line.split()[0] for line in passwr]  
    if user.lower() not in user-list:
            x = 0

相关问题 更多 >

    热门问题