【发布时间】: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