+ 1
Can someone explain me the error operations in Python3 course in basic concepts?
3 Answers
+ 5
If you are calculating this situation can happen:
5 * 0 = 3 * 0 means 0 = 0 which is correct
5 * 0 = 3 * 0 now lets divide this term by 0 |:0
5 = 3 so this will be the result after last operation
Because of this behavior computer systems and software raise an error if a division by 0 will be performed. This can lead to a computer crash with a possible lost of data that are processed at that time.
At this point an exception handling can prevent problems. To handle this 'zero division error' all operations that can cause this error should be put in a try ... exception block:
value1 = 5
value2 = value1 - value1
result = value2 / value2 # this will stop the execution of the program
# should be done like this:
value1 = 1
try:
value2 = value1 - value1
result = value2 / value2
except ZeroDivisionError:
print('Last calculation causes an ZeroDivisionError.')
print('... do something...')
The way it works is: If an exception in try-block appears, the code in exception-block will be executed. But as also other exceptions can raise, a more generic approach is better, because this can handle all kinds of exceptions:
# a more generic approach:
value1 = 1
try:
value2 = value1 - value1
result = value2 / value2
except Exception as e:
print('Last calculation causes an ZeroDivisionError.')
print('Error: ',e)
Feel also free to have a look at this very helpful tutorial: https://realpython.com/JUMP_LINK__&&__python__&&__JUMP_LINK-exceptions/
+ 3
Do you mean exception handling? Can you show us the code you are talking about?
+ 1
No zero division error