【问题标题】:Why does my if statement activate even though the conditions aren't met?为什么即使条件不满足,我的 if 语句也会激活?
【发布时间】:2021-03-04 03:05:15
【问题描述】:

这里的问题很简单,做了一个小程序,要求用户创建用户名和密码。在我添加这个“if user”语句之前,每件事都有效。如果我输入“x”或“X”,它应该重新启动循环,但无论我输入什么,它都会重新启动它。这里发生了什么?

db = {}
num_of_entries = 0


def addToDict(a, b):
    db[a] = b
    print(f"User created: '{a}'")


def removeFromDict(key):
    del db[key]
    print()
    print(f"User '{key}' has been removed.")


while True:
    clear = "\n" * 100
    print()
    print("""
Hi there!     
Would you like to create a new account or delete an existing one?
          ('Create' to create, 'Delete' to delete)
""")

    choice = input("> ").upper()

    if choice == 'CREATE':
        print(f'{choice} mode selected.')
        print()
        user = input("Please enter a username: ")
        if user == 'X' or 'x':
            continue
        else:
            if user not in db:
                passW = input("Please enter a password: ")
                print(clear)
                print()
                addToDict(user, passW)

【问题讨论】:

  • 将其更改为:if user == 'X' or user == 'x':。这是一个常见的问题。
  • 你也可以做if user.lower() == 'x':(我通常在进行字符串比较时使用lower/upper来避免头疼)

标签: python-3.x dictionary if-statement


【解决方案1】:

这里的问题是您提出了两个单独的条件user == 'X''x'。 由于'x' 不是 null 或 false,因此它始终为 true,因此 if 语句始终为 true,因为它在两个条件之间使用了 or 运算符。

您需要按照上面的建议做的是:

if user == 'X' or user == 'x':

你也可以这样做:

if user.lower() == 'x':

甚至:

if user in ['X', 'x']:

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-07-12
    • 2015-08-08
    • 2021-06-19
    • 2020-10-04
    • 2018-06-25
    • 2020-12-24
    • 1970-01-01
    相关资源
    最近更新 更多