【问题标题】:Why is my if statement not executing properly?为什么我的 if 语句没有正确执行?
【发布时间】:2019-08-18 02:42:44
【问题描述】:

我正在尝试练习我的 Python 技能,我知道我对如何处理文件有点不熟悉,所以我决定自学。该代码基本上是创建一个帐户,登录并检查用户并存储在文件中。我知道我的用户并且 pass 正在附加和读取文件。我遇到的问题在我的 if 语句中。我正在使用 if i == user 但 == 表示字面意思。所以我尝试只使用一个=来检查一个变量是否=用户输入的变量,当我这样做时,我得到一个语法错误。我的最后一个问题是当我运行代码时,在他们说用户名不正确的其他语句中,它在控制台中说了 2 或 3 次。这让我感到困惑,因为 else 语句之外没有任何地方是它们的 while 或 for 循环。如果有人可以解释当用户和密码字符串正确时如何让我的 if 语句执行。那太好了。另外,如果您知道我的控制台为什么无缘无故地执行 else: print('username wrong) 3 次。我很想知道

我尝试在我的 for 循环中打印出变量,它确实打印了文件中的字符串。

u = open('users.txt', 'a+')
p = open('pass.txt', 'a+')

does_acc = input('Do you have a account? ')

if does_acc == 'no' or does_acc == 'No':
    new_user = input('Username: ')
    u.write(new_user + '\n')
    new_pass = input('Password: ')
    p.write(new_pass + '\n')

sign_in = input('Would you like to sign in? ')

if sign_in == 'yes' or sign_in == 'Yes':
    n = open('users.txt', 'r')
    m = open('pass.txt', 'r')
    lines = n.readlines()
    line = m.readlines()
    user = input('Username: ')
    for i in lines:
        print(i)
        if i = user:
            password = input('Password: ')
            for x in lines:
                if password == x:
                    print('secret file opened')
                else:
                    print("{} is not a valid password.").format(password)
        else:
            print('Username incorrect.')
else:
    print('Have a nice day.')

u.close()
p.close()


Do you have a account? yes
Would you like to sign in? yes
Bob
Username: Bob
Username incorrect.
Username incorrect.

【问题讨论】:

  • 你的字符串中可能有你看不到的换行符。
  • @MarkRansom 是对的。 readlines() 在每一行的末尾留下一个换行符,但 input() 没有。 'Bob' 不等于 'Bob\n'

标签: python file readlines


【解决方案1】:
  1. if i = user: 应替换为:if i == user:(双等号)
  2. 创建新帐户后,您应该关闭文件,因为您将在它们已经打开时再次打开它们。这可能会也可能不会导致错误地读取/写入数据。
  3. 一旦用户输入了他们的姓名,整个密码文件与输入的密码相匹配的想法似乎不正确——您只需为每个用户检查一个密码。李>
  4. for x in lines: 尝试将密码与用户名进行匹配。看起来很奇怪。
  5. print("{} is not a valid password.").format(password) 括号顺序错误,应该是"string".format(parm) 括在print( .... ) 中,反之则不然。

总而言之,我宁愿像这样重写你的密码匹配部分:

with open( 'passwords.txt' ) as fin :
    passwords = [p.strip() for p in fin.readlines()]

with open( 'users.txt' ) as fin :
    users = [u.strip() for u in fin.readlines()]

user = input( 'User: ' )
password = input( 'Password: ' )

if [user, password] in zip( users, passwords ) :
    print( "You're welcome!" )
else :
    print( "Go away!" )

或者类似的东西。

【讨论】:

  • 除非他们运行的是 Python 的实验版本,否则if i = user 应该会产生语法错误。我怀疑复制/粘贴错误。
【解决方案2】:

if i = user 应该是if i == user 并且您打开同一个文件两次,一个在开头,第二个在if sign_in == 'yes' or sign_in == 'Yes': 之后

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2012-06-08
    • 2021-08-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-07-02
    • 1970-01-01
    • 2016-08-10
    相关资源
    最近更新 更多