jeudi 22 octobre 2020

How to make all conditions (if, elif, else) work, in for loop, with try except in Python

We have a list of dictionaries.

On users input we have 4 possible results:

  1. Account inserted correctly -> show all info.
  2. If the length of the input is not equal to 5 (all accounts are consists of 5 digits) -> stop the program with output f"There are 5 digits in the account, you inserted {len(acc)}".
  3. If the input is not an integer -> stop the program with output "There are no letters in the account! Please insert 5 digits".
  4. If the input is an integer, the length is 5 digits, but there is no account like that in our list of dictionaries -> stop the program with output f" Sorry, Could not find {acc}!"

Please, see code below:

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}!")

My goal is to make sure all conditions work.

So far I was able to make the first 3 conditions work, but I stuck at the final one - If the input is an integer, the length is 5 digits, but there is no account like that in our list of dictionaries -> stop the program with output f" Sorry, Could not find {acc}!"

It doesn't raise any error, there is just no output, like an empty string or something like that.

Hope you can help me.

Aucun commentaire:

Enregistrer un commentaire