0

I am new to Python and would like to know what is the difference between Try and assert and situations where each one is more suitable. Thanks.

2

1 Answer 1

1

Welcome to Stack Overflow.

You can read the documentation for try here: https://docs.python.org/3/tutorial/errors.html

You can read the documentation for assert here: https://docs.python.org/3/reference/simple_stmts.html

Essentially, try means try the following block of code, and if there is an error, it is handled in the except part.

For example:

try:
   print(1/0) #a division by 0, should raise an error.
except ZeroDivisionError:
   print("You tried to divide by zero!")

So instead of the program crashing, it prints "you tried to divide by zero" instead.

assert means "make sure the following is true".

So imagine if we had a function that did division, and we wanted to make sure that the denominator was never zero, we could do:

def divide(a, b):
    assert b != 0
    return a/b

This is a pretty bad example, but basically what's happening here is that if b is ever equal to 0, the assertion raises an exception, which prevents the program from continuing unless that exception is handled.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.