Issue
So I'm having a strange issue with Python which is related to the try and except function. It is supposed to allow me to reinput the customer which in this case is c2 as c1 is transferring funds to c2. However it gives me a keyerror instead of saying that the user is not in the database and asking me to reinput the customer name. The second use of try and except in the below code works though although there is a visual bug and not functional bug.
I've tried changing where I use try and except and have tried searching online but have not found a solution. I've only been doing Python for a few months and it is on and off at that.
elif option == 3:
print("Option", 3)
try:
c2 = input("Customer 2")
customer2 = BankSystem.c[c2]
except ValueError:
print("\n>>>An exception occured ~ invalid i/p")
print("\t~Customer not in database")
print()
if "c2" in BankSystem.c: ## check for valid account id
print(customer2)
try:
amount = float(input("Amount to transfer "))
self.tranfer(customer2, amount)
except ValueError:
print("\n>>>An exception occured ~ invalid i/p")
print("\t~Non-numeric data entered")
else:
print("\n>>>>>>>account:{} does not
exist".format("c2"))
print(self)
print(customer2)
Solution
From the docs, "Python raises a KeyError whenever a dict() object is requested (using the format a = adict[key]) and the key is not in the dictionary." So, you should check for keyerror in your except block:
try:
c2 = ....
except KeyError:
print("\n>>>An exception occured ~ invalid i/p")
print("\t~Customer not in database")
Edit: You can restructure your try/except as:
try:
c2 = input("Customer 2")
customer2 = BankSystem.c[c2]
if "c2" in BankSystem.c: ## check for valid account id
print(customer2)
amount = float(input("Amount to transfer "))
self.tranfer(customer2, amount)
else:
print("\n>>>>>>>account:{} does not exist".format("c2"))
print(self)
print(customer2)
except KeyError:
print("\n>>>An exception occured ~ invalid i/p")
print("\t~Customer not in database")
except ValueError:
print("\n>>>An exception occured ~ invalid i/p")
print("\t~Non-numeric data entered")
Answered By - sk_462
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.