Google News
logo
Python Program to Use the else keyword to define a block of code to be executed if no errors were raised
In the following example of a Python program that demonstrates how to use the `else` keyword to define a block of code to be executed if no errors were raised :
Program :
try:
    # Your code goes here
except Exception as e:
    print(f"An error occurred: {e}")
else:
    print("No errors were raised")
In this example, the `try` block contains the code that you want to execute. If an error occurs, the program will jump to the `except` block and execute the code inside it. If no errors occur, the program will execute the code in the `else` block.

For example, here's a program that attempts to divide two numbers :
Program :
try:
    x = 10
    y = 5
    z = x / y
except ZeroDivisionError as e:
    print("Cannot divide by zero")
except Exception as e:
    print(f"An error occurred: {e}")
else:
    print(f"The result is {z}")
Output :
The result is 2.0
This is because the `x / y` operation is valid, and it returns the result of 2.0. Since no errors occurred, the program executes the code in the `else` block and prints the result.

If the value of `y` was set to zero, then the program would raise a `ZeroDivisionError` exception, and the code in the `except` block would be executed instead.