- 1

Real life usage of Assertion and try/except in program.

def d2w(n): dicts = { 1 : "One", 2 : "Two", 3 : "Three", 4 : "Four", 5 : "Five", 6 : "Six", 7 : "Seven" } return dicts[n] while True: ui = input("Enter a number: ") try: assert 0 < int(ui) <= 7 print(d2w(int(ui))) except AssertionError: print("Number should be between 1 and 7") except ValueError: try: assert ui.lower() == "stop" print("Bye!") break except AssertionError: print("U didn't Entered INT or Stop") # This program takes number as input converter it to words and when it stop when user input "stop". # While writing this code i realised that if-else conditions can be replaced with Assertion and try/except at least for checking user input. ***You query or suggestions is highly appreciated.

27th Dec 2021, 4:35 PM
Alim Ansari
Alim Ansari - avatar
5 ответов
+ 1
No, you are right, the second code is much better, assertions are made for debugging, they are used to throw errors about things which aren't suspicious to happen, after you finished your program, they are either replaced with if-else or removed depending of how you used it
27th Dec 2021, 5:31 PM
VCoder
VCoder - avatar
0
Try-catch vs if-else : If-else is used for conditions that can't throw errors, even if they are true or false (example check if a number is beetween range and output yes or no depending on the condition) Try-catch provides easier syntax for programs that might throw errors and as d2w(8) will throw an error, you used the right statement
27th Dec 2021, 5:11 PM
VCoder
VCoder - avatar
0
VCoder , i wrote this program using if-else too... but here i would like to highlight that if-else can be replaced with Assertion. check the below code with if-else without any Assertion. def d2w(n): dicts = { 1 : "One", 2 : "Two", 3 : "Three", 4 : "Four", 5 : "Five", 6 : "Six", 7 : "Seven" } return dicts[n] while True: ui = input("Enter a number: ") try: if 0 < int(ui) <= 7: print(d2w(int(ui))) else: print("Number should be between 1 and 7") except ValueError: if ui.lower() == "stop": print("Bye!") break else: print("U didn't entered Integer or "stop")
27th Dec 2021, 5:15 PM
Alim Ansari
Alim Ansari - avatar
0
VCoder please correct me if i am wrong.
27th Dec 2021, 5:16 PM
Alim Ansari
Alim Ansari - avatar
0
Thanks
27th Dec 2021, 5:34 PM
Alim Ansari
Alim Ansari - avatar