如何使所有条件if,elif,else在for循环中工作,并尝试使用Python除外

问题描述

我们有一个字典列表。

根据用户输入,我们有4种可能的结果:

  1. 帐户已正确插入->显示所有信息。
  2. 如果输入的长度不等于5(所有帐户均由5位数字组成)->停止输出为f“的程序,该帐户中有5位数字,您插入了{len(acc)}”。
  3. 如果输入的不是整数->停止输出为“帐户中没有字母!请输入5位数字”的程序。
  4. 如果输入的是整数,则长度为5位数字,但是在我们的词典列表中没有类似的帐户->停止输出为f的程序“对不起,找不到{acc}!”

请,请参见下面的代码

test_dict = [{"account_number": 12345,"Name" : "Nick"},{"account_number": 76531,"Name" : "Carl"},{"account_number": 75321,"Name" : "Mary"}]

acc = input("Insert Account Number: ")

try:
    for i in test_dict:
        try:
            if int(acc) == i["account_number"]:
                print(i)
            elif len(acc) != 5:
                print(f"There are 5 digits in the account,you inserted {len(acc)}")
                break
        except:
            print("There are no letters in the account! Please insert 5 digits")
            break
except:
    print(f"Sorry,Could not find {acc}!")

我的目标是确保所有条件都能正常工作。

到目前为止,我能够使前三个条件起作用,但我停留在最后一个条件上-如果输入是整数,则长度为5位数字,但是在我们的列表中没有类似的帐户字典->停止程序,输出为f“对不起,找不到{acc}!”

它不会引发任何错误,只是没有输出,例如一个空字符串或类似的东西。

希望你能帮助我。

解决方法

似乎您快到了,只是有一些其他不必要的元素。

外部try循环似乎可以省略,因此您的最终条件可以只是else条件。

在第一个break语句之后还包含一个if,以避免同时使ifelse语句同时产生输出。

看看这对您有用吗!

test_dict = [{"account_number": 12345,"Name" : "Nick"},{"account_number": 76531,"Name" : "Carl"},{"account_number": 75321,"Name" : "Mary"}]

acc = input("Insert Account Number: ")


for i in test_dict:
    try:
        if int(acc) == i["account_number"]:
            print(i)
            break
        elif len(acc) != 5:
            print(f"There are 5 digits in the account,you inserted {len(acc)}")
            break
    except:
        print("There are no letters in the account! Please insert 5 digits")
        break
else:
    print(f"Sorry,Could not find {acc}!")
,

您几乎明白了。干得好。

except子句仅在出现错误时运行。您的代码无效,因为如果没有错误,最后的除外对象将不会运行。

在此处了解有关try-except的更多信息: https://realpython.com/python-exceptions/

以下是供您考虑的另一种方法。 该方法尝试尽快捕获尽可能多的错误,然后才对test_dict起作用。这样做的好处是,它将对带有几个1000个帐户的test_dict快速执行。首先进行验证,最后进行处理。

test_dict = [{"account_number": 12345,"Name" : "Mary"}]

account = input("Insert Account Number: ")

match_found = False
try:
    account = int(account)
except:
    print("Invalid characters entered for the account. Please enter numbers only.")
else:
    if len(str(account)) != 5:
        print(f"There are 5 digits in the account,you inserted {len(str(account))}")
    else:
        for i in test_dict:
            if i["account_number"] == account:
                print(i)
                match_found = True
                break
        if not match_found:
            print(f"Sorry,Could not find {account}!")