Some Inbuilt Bugs in Python
Python is regarded as one of the most powerful programming languages. And we all know that "with great power comes great responsibility". Therefore, it is the responsibility of the programmer to ensure they don't run into some of the inbuilt bugs in Python.
Today, I am going to explain and demonstrate how these bugs can cause catastrophes.
1. Arithmetic Operation After Line Break
When the expression in front of a
return statement gets too long, the ideal thing to do is to break the line. This is a good practice that could lead to a potential bug as only the expressions directly on the same line as the return gets evaluated. Look at the codes below:
Therefore, it is advisable that you wrap your code in parenthesis after linebreak. No kidding, this error took days to debug - I was really frustrated.
2. 0.2 + 0.1 = 0.30000000000000004
Launch your Python interpreter and write the code below. You'd be surprised that 0.1 + 0.2 != 0.3.
This bug is not limited to Python but is also rampant in many other programming languages. This is due to the fact that there is no perfect representation of 0.1 + 0.2 in binary. Think of it as 1/3 of a decimal - is it 0.333 or 0.33333333.
Now, your banking app is giving your user extra cash - not much though, but at the end of the year things won't balance up!
To solve this you might need an additional if statement.
return balance - amount
Line breaks in Python or any language assumes that a new statement has started. Python is a dynamic language, so you can't simply check for compilation errors and end of a statement
; is not used in Python. So in the above code
balance is returned. The interpreter never reaches
- amount which never throws a error.
To write a statement in multiple lines you use
\ character to notify the interpreter that the next line is a part of the current statement.
return balance \ # Line below is a part of current statement. - amount
Also floating point is not a bug of python but the underlying platform handling numbers. It happens because it is the way the underlying c platform (on which python works in a sense) handles floating-point numbers. Floating point error is not a bug. Stackoverflow
PS : Apologies. My intensions are not to criticize. Just sharing my opinions.
Thank you very much for the explanation.
I believe we are saying almost the same thing. Check the explanation in the article, I explicitly stated that "This is a good practice that could lead to a potential bug as only the expressions directly on the same line as the return gets evaluated."