Boolean variables can have two values, True or False. In python, boolean variables are mostly used with if statements and while loops. Boolean variables are easy to understand. However, not many people know about Lazy Evaluation.
Lazy Evaluation can help you optimize your code in certain cases. Before moving on to Lazy Evaluation, let's refresh our memory on a few rules related to Boolean Values
The second and the fourth statements are where Lazy Evaluation is relevant.
- If we are combining multiple boolean values with the or operator, as long as one of them is True, the entire expression evaluates to True.
- If we are combining multiple boolean values with the and operator, as long as one of them is False, the entire expression evaluates to False.
Python and other programming languages use this under the hood while evaluating boolean expressions.
Below is the output on running the code
In the first if statement, since the function first_condition() returns False and we are using the and operator, no calls are made to second_condition() and third_condition(). Python basically saved two functions calls.
In the second if statement, calls are made to the first_condition() and second_condition(). The function first_condition() returns False, but since we are using the or operator, Python can not determine the value of the expression. As a result, it calls the function second_condition(), since this function returns True and we are using the or operator, Python can evaluate the expression to True thus saving a function call (Notice it did not call function third_condition())
In more technical terms, during lazy evaluation, operators short circuit
When is this useful
Lazy Evaluation can save us from expensive calls.
The first if statement took 5 seconds to evaluate while the second if statement **took less than a second to evaluate. In the second **if statement, the function expensive_function() wasn't even called thus saving us around 5 seconds.
- In C++, we can perform checks for segmentation fault before performing checks for values.
In the above case, the pointer ptr is not defined and is NULL. Although we check if it's NULL or not, the above code would lead to a segmentation fault since C++ evaluates from left to right. However, if check for NULL pointer first, the second function won't even be called.
The above code won't return any error.
I recently started a modified version of the #100daysofcode challenge. I aim to write content related to Python, Data Science, or Programming every day. Follow my progress on Twitter, Medium, Dev.to, Hashnode, or my WordPress Blog.
Top comments (0)