I'm studying CS50p and the tutor says it's best practice to have as few lines as possible, ideally one, in a Try, but I really struggle to do this.
How could I write the following code so that I only try the input?
while True:
try:
# How to have just 1 line in try??
order = input("Order: ").title().strip()
if order in menu:
price += menu[order]
print(f"Total: ${price}")
except (EOFError, KeyError):
break
The reason why it's generally a best practice to have as few lines as possible in the body of a try
statement is to make sure there is only one possible source that produces the exception being handled so that the logics of the exception handler can be tailored specifically to the nature of the error.
In your case, EOFError
can only be raised by the input
function, and KeyError
can only be raised by a missing key from accessing menu[order]
, so you can enclose those two specific statements in try
statements instead:
while True:
try:
order = input("Order: ").title().strip()
except EOFError:
break
if order in menu:
try:
price += menu[order]
except KeyError:
break
print(f"Total: ${price}")
But KeyError
is unlikely to occur since you already put menu[order]
in an if
condition of order in menu
, so you can remove the if
condition to adopt an EAFP code pattern:
while True:
try:
order = input("Order: ").title().strip()
except EOFError:
break
try:
price += menu[order]
except KeyError:
break
print(f"Total: ${price}")