簡體   English   中英

如何使所有條件(if、elif、else)在 for 循環中工作,在 Python 中使用 try 除外

[英]How to make all conditions (if, elif, else) work, in for loop, with try except in 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}!")

我的目標是確保所有條件都有效。

到目前為止,我能夠使前 3 個條件起作用,但我堅持最后一個 -如果輸入是整數,則長度為 5 位數字,但在我們的字典列表中沒有這樣的帳戶 -> 停止帶有輸出 f 的程序“抱歉,找不到 {acc}!”

它不會引發任何錯誤,只是沒有輸出,例如空字符串或類似的東西。

希望您能夠幫助我。

似乎你快到了,只是有一些不必要的額外元素。

外部try循環似乎可以省略,因此您的最終條件可以只是一個else條件。

還包括在第一個if語句之后的break ,以避免if語句和else語句同時產生輸出。

看看這是否適合你!

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 子句才會運行。 您的代碼不起作用,因為如果沒有錯誤,則最后一個 except 不會運行。

在此處閱讀有關 try-except 的更多信息: https : //realpython.com/python-exceptions/

下面是另一種方法供您考慮。 該方法嘗試盡可能快地捕獲盡可能多的錯誤,然后才對 test_dict 起作用。 這樣做的好處是它可以快速執行一個只有 1000 個帳戶的 test_dict。 先驗證,最后處理。

test_dict = [{"account_number": 12345, "Name" : "Nick"},
             {"account_number": 76531, "Name" : "Carl"},
             {"account_number": 75321, "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}!")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM