Hidden Functionality of Try and Accept Blocks in Python

<p>If you code in Python than, you have probably already worked with a lot of&nbsp;<code>try</code>&nbsp;and&nbsp;<code>except</code>&nbsp;blocks. In this blog, we will explore some of the hidden functionality of these blocks. We will demonstrate this by creating a function called&nbsp;<code>divide</code>, which divides&nbsp;<code>a</code>&nbsp;by&nbsp;<code>b</code>&nbsp;and returns a string. We will handle two specific exceptions:&nbsp;<code>ZeroDivisionError</code>&nbsp;if the user divides by zero, and&nbsp;<code>TypeError</code>&nbsp;if they enter a non-numeric value. Let&#39;s run the program to test it out.</p> <pre> def divide(a, b): try: result = a / b return str(result) except ZeroDivisionError: return &quot;Error: Division by zero&quot; except TypeError: return &quot;Error: Invalid input&quot; print(divide(10, 4)) # Output: 2.5 print(divide(10, &#39;a&#39;)) # Output: Error: Invalid input print(divide(10, 0)) # Output: Error: Division by zero</pre> <h1>Hidden Functionality:&nbsp;<code>else</code>&nbsp;Block</h1> <p>Now, let&rsquo;s explore the&nbsp;<code>else</code>&nbsp;block in a&nbsp;<code>try</code>&nbsp;and&nbsp;<code>except</code>&nbsp;block. If the code in the&nbsp;<code>try</code>&nbsp;block runs successfully without encountering any exceptions, everything in the&nbsp;<code>else</code>&nbsp;block will be executed. This provides an opportunity to add additional functionality. For example, we can print a success message. Let&#39;s modify our code to include the&nbsp;<code>else</code>&nbsp;block.</p> <p><a href="https://python.plainenglish.io/hidden-functionality-of-try-and-accept-blocks-in-python-e28b32fea2ea">Read More</a></p>