Refactor Most Common Issue¶
Here is classic beginner code. There is way too much in the try
portion of the code. We don’t need to try lines of code that have zero chance of raising an error.
try:
# Display menu options
print("1 - Option One")
print("2 - Option Two")
print("3 - Option Three")
print()
# get choice
choice = int(input("> "))
# handle choice
if choice == 1:
print("You chose OPTION ONE.")
elif choice == 2:
print("You chose OPTION ONE.")
elif choice == 3:
print("You chose OPTION ONE.")
else:
print("Invalid option.")
except ValueError:
print("Invalid option.")
What you should do¶
Refactor the code to include ONLY the single line of code that could possibly raise an error. Some code needs to go outside before the
try/except
and some other code needs to go outside after thetry/except
.
©2021 Daniel Gallo
This work is licensed under Attribution-NonCommercial-ShareAlike 4.0 International