退出循环时删除变量

2024-05-19 09:48:15 发布

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

我正在做一个代码注册系统的实践,我有问题如何添加一个id和密码列表。你知道吗

print('id = ')
id = input()
while True:
    print('password = ')
    password = input()

    print('Please retype your password = ')
    repassword = input()

    if repassword == pas:
        print('successfully registered.')
        acc = [ ]
        acc.append([(id),(pas)])
        break
    else:
        print('please check your password.')

当这个循环结束时acc列表被删除,我不能使用这个列表。 如何保存列表?你知道吗


Tags: 代码idtrue密码列表inputyour系统
2条回答

唯一阻止代码工作的是在一个地方调用密码变量password,在另外两个地方调用pas。只需将pas更改为password即可正常工作。你知道吗

当循环退出时,在循环中定义的变量仍在作用域中。这是Python工作原理的一个基本部分。下面是一个简单的演示:

Python 3.6.3 (default, Nov 13 2017, 09:55:42)
[GCC 4.9.3] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> while True:
...     x = 5
...     break
...
>>> x
5

不过,除了修复命名错误的变量外,我还想对您的代码做三点修改:

  • 为“id”使用不同的变量名-id是一个内置函数,最好不要使用shadow内置函数。或许可以称之为“用户id”。你知道吗
  • 将提示传递给input而不是打印它—这样更简洁。像这样:

    password = input("password = ")
    
  • acc赋值为一个简单的元组-它不需要是一个列表,也不需要创建它然后实例化它。就这么做吧

    if repassword == password:    
        acc = (user_id, password)
        break
    

    或者,在退出while循环后,只需使用用户id和密码即可。你根本不需要acc

通过所有这些更改,您的代码变得更短、更简单:

user_id = input('id = ')
while True:
    password = input('password = ')
    repassword = input('Please retype your password = ')

    if repassword == password:
        print('successfully registered.')
        break
    else:
        print('please check your password.')
print("User id: {}\nPassword: {}".format(user_id, password))

我对您的代码进行了几处更改,以使其正常工作:

  1. pas重命名为password。你知道吗
  2. 在循环外的开始处实例化acc,这样就不会在每个循环中清除它。你知道吗
  3. 在列表中附加元组而不是列表。你知道吗

试试这个:

acc = []

print('id = ')
id = input()

while True:
    print('password = ')
    password = input()

    print('Please retype your password = ')
    repassword = input()

    if repassword == password:
        print('successfully registered.')
        acc.append((id, password))
        break
    else:
        print('please check your password.')

print(acc)

相关问题 更多 >

    热门问题