5 – Complex Boolean Expressions

All the if and elif statements we’ve seen so far have been followed by a single Boolean expression that checks only one condition. However, more complicated Boolean expressions can be useful as well. If the condition is working with the numerical variable, you might want to check whether a value lies in a certain range or even do some calculation in order to make a comparison. Notice this condition uses logic and algebra, and will still run correctly in Python. Storing values for height and weight, we can quickly print the result for any individual. Some situations may call for logical operators. If it’s rainy and sunny, I might look for a rainbow. Notice that the if statement here requires that both of these individual variables hold true to evaluate as true. If either is false, then this line will evaluate as false, and our print statement will not run. Let’s say I want to send a promotional email to a customer, if they have not requested to be taken off the email list, and they’re in a location where they’ll be able to redeem the offer. For really complicated conditions, you might need to combine some ands, ors, and nots together. Use parentheses if you need to make the combinations clear. However, simple or complex, the entire line in an if statement must be a Boolean expression that evaluates to either true or false, and it is this value that decides whether the indented block in an if statement executes or not.

Dr. Serendipity에서 더 알아보기

지금 구독하여 계속 읽고 전체 아카이브에 액세스하세요.

Continue reading