Python Try Else Tutorial – Complete Guide

Diving headfirst into the world of coding, particularly within a language as versatile and feature-rich as Python, can be both an exciting and daunting prospect. In order to properly navigate this expansive landscape, there are several key features and structures that you’ll need to get a firm grasp on. One such feature, which can prove crucial in numerous coding circumstances, is the ‘Python try else’ statement. But what does it do and why is it worth investing your time to learn? Let’s find out!

What is the Python try-else statement?

Python’s ‘try else’ statement is an important control flow tool that helps programmers manage and respond to unforeseen errors or exceptions. When structured correctly, this command tells Python to ‘try’ a certain block of code, and should an exception arise, ‘else’ instructs the program to run a different set of instructions.

Why should I learn it?

The by-word of any good programmer is foresight and a willingness to strategise. It’s all about predicting potential issues and implementing robust and thoughtful solutions. As one of Python’s built-in methods for handling exceptions, understanding and employing ‘try else’ statements allows us to:

  • Write more adaptive and resilient code
  • Better handle and respond to errors
  • Improve the overall user experience by minimising abrupt program interruptions
  • Contribute to cleaner, more readable code structure

Learning to utilise this structure effectively can significantly bolster your Python proficiency, setting you on the path to becoming a capable and confident programmer.

CTA Small Image
FREE COURSES AT ZENVA
LEARN GAME DEVELOPMENT, PYTHON AND MORE
ACCESS FOR FREE
AVAILABLE FOR A LIMITED TIME ONLY

Basic Structure of Python try-else

The basic structure of the Python ‘try else’ statement is straightforward. We’ll start by introducing a ‘try’ block, which includes the code we want to attempt executing. Then, we incorporate an ‘except’ block to specify a response for when Python encounters an exception in the ‘try’ block. Finally, we introduce the ‘else’ block which contains the code that will run if no exceptions were raised.

try: 
    # code to attempt
except:
    # code to execute in case of an error
else:
    # code to execute if no error was raised

The ‘else’ clause is often skipped in beginner Python tutorials, however, its importance cannot be overstated. The ‘else’ clause allows us to segregate the code that has potential exceptions from the code that does not, ultimately leading to cleaner and more readable code.

Examples of Python try-else

Now, let’s delve into some simple yet illustrative examples of Python’s ‘try else’ in action.

Example 1: A simple example where Python’s ‘try else’ statement is used to attempt division operations.

try:
    result = 10 / 2
except ZeroDivisionError:
    print("You tried to divide by zero!")
else:
    print("The result of the division is", result)

In this case, running the code will yield “The result of the division is 5” – no exceptions were raised, so the ‘else’ block ran as planned.

Now, let’s proceed and highlight a few more complex examples.

Example 2: An example where the ‘try else’ statement is used within a function to handle an exception when dividing by zero.

def division(a, b):
    try:
        result = a / b
    except ZeroDivisionError:
        print("You tried to divide by zero!")
    else:
        print("The result of the division is", result)

division(10, 0)

In this example, the error message “You tried to divide by zero!” is printed out because we were attempting to divide by zero – a classic Python exception.

Stay tuned for the next post where we’ll start to explore some even more advanced Python ‘try else’ scenarios, and demonstrate how you can leverage it to elevate your Python programming skills.

In-depth examples of Python try-else

We’ve delved into the basics, now let’s further explore Python’s ‘try else’ structure through more complex and varied examples.

Example 3: Let’s extend the previous function, now catching multiple exceptions. We’ll add a ValueError to the exceptions list.

def division(a, b):
    try:
        result = int(a) / int(b)
    except ZeroDivisionError:
        print("You tried to divide by zero!")
    except ValueError:
        print("You inputted an invalid value!")
    else:
        print("The result of the division is", result)

division('ten', 2)

In this example, the function throws a ValueError with the message “You inputted an invalid value!”. Here we are trying to divide a string (“ten”) by a number, which is not permitted.

Example 4: Using ‘try else’ statement to manage file operations.

try:
    with open('non_existent_file.txt', 'r') as my_file:
        print(my_file.read())
except FileNotFoundError:
    print("File not found!")
else:
    print("File read successfully!")

This program attempts to open a file that doesn’t exist. Python throws a FileNotFoundError, so the message “File not found!” is printed to the console.

Example 5: Combining ‘try else’ statement with a ‘finally’ statement.

try:
    result = 10 / 0
except ZeroDivisionError:
    print("You tried to divide by zero!")
else:
    print("The result of the division is", result)
finally:
    print("This code runs no matter what!")

The ‘finally’ clause is executed no matter if an exception was raised or not. In this case, “You tried to divide by zero!” is printed to console, followed by “This code runs no matter what!”.

Example 6: Outlining a common use case for ‘try else’ - performing an action if no exceptions were raised.

try:
    result = 10 / 2
except ZeroDivisionError:
    print("You tried to divide by zero!")
else:
    result *= 2
    print("The result of the operation is", result)

Here, the exception was not raised, so the number is successfully divided and then multiplied by 2 inside the ‘else’ clause. The result, 10, is then printed.

Example 7: Utilizing the ‘raise’ statement within Python ‘try else’.

try:
    user_input = input("Enter a positive number:")
    if int(user_input) < 0:
        raise ValueError("That is not a positive number!")
except ValueError as e:
    print(e)
else:
    print("Thank you for your input!")

By using ‘raise’, we can generate our own exceptions. If the user inputs a negative number, a ValueError is raised with our custom message.

Remember, mastering Python’s ‘try else’ structure is a pivotal step in your journey to becoming a Python expert! Stick around as we help you understand and maneuver all the intricacies of Python coding at Zenva.

Where to Go Next? Keep Learning with Zenva!

You’ve dipped your toes into the expansive ocean of Python programming, learnt the nifty control flow tool of Python’s ‘try else’ statement, and are now ready to venture further. But then the question arises – where to go next? This is where we, at Zenva Academy, step in to guide you on your journey!

If you want to delve deeper into Python and expand your skills, we suggest you check out our Python Mini-Degree. With a well-rounded collection of courses, it covers not just basics of coding, but other crucial topics like algorithms, Object-Oriented programming, game development, and app development. By completing these courses, you’ll be well on your way to establish yourself as a python programmer with a varied set of coding skills and a portfolio of Python projects.

The best part about our Python Mini-Degree is that it is intended for all levels of learners. Whether you’re a beginner just getting started or a seasoned coder looking to brush up your skills, we’ve got you covered. Our courses feature video lessons, interactive lessons, coding challenges, and upon completion, you’ll be rewarded with a certificate – an accreditation of your hard work and perseverance.

If you are looking for more comprehensive learning options, you can explore our broad collection of Python Courses on Zenva Academy. This collection offers a wealth of resources across multiple Python topics to satiate your learning appetite.

Conclusion

Embarking on your Python journey with the ‘try else’ statement is certainly a leap in the right direction towards better, more adaptive programming and cleaner code architecture. The ‘try else’ command invariably strengthens your toolset, making your code more resilient and your programming journey more efficient. As you advance, these little steps will culminate into great strides, transforming you into a confident and resourceful Python programmer.

Remember, as your faithful mentors in this dynamic coding world, we at Zenva Academy are here to support you along every step of this journey. Check out our Python Mini-Degree and unleash your coding prowess. Go out there and let Python be your brush, the programming world your canvas!

Did you come across any errors in this tutorial? Please let us know by completing this form and we’ll look into it!

FREE COURSES
Python Blog Image

FINAL DAYS: Unlock coding courses in Unity, Godot, Unreal, Python and more.