Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a better way to write this "if" boolean evaluation?

I have this small snippet of python code that I wrote. It works, but I think there should be a more streamlined method to achieve the same results. I'm just not seeing it. Any ideas?

if tx_avt >= 100: tx = 1 
elif tx_avt < 100 and tx_avt >= 50: tx = 2 
elif tx_avt < 50 and tx_avt >= 25: tx = 3
elif tx_avt < 25 and tx_avt >= 12.5: tx = 4 
else: tx = 5
like image 752
DavidScott612 Avatar asked Nov 27 '12 17:11

DavidScott612


People also ask

How do you write an if statement for a Boolean?

An if statement checks a boolean value and only executes a block of code if that value is true . To write an if statement, write the keyword if , then inside parentheses () insert a boolean value, and then in curly brackets {} write the code that should only execute when that value is true .

Does an if statement evaluate a boolean expression?

if ( condition ) statement; if is a Java reserved word The condition must be a boolean expression. It must evaluate to either true or false. If the condition is true, the statement is executed.

How do you evaluate a Boolean?

Traditionally, the result of a logical or Boolean expression is considered true if it evaluates to 1 and false if it evaluates to 0. This prints yup because y is evaluated as false. Some D3 implementations additionally evaluate any negative numbers as false, and positive numbers as true.

What operator will I use if I will evaluate a Boolean value?

The “OR” operator is represented with two vertical line symbols: result = a || b; In classical programming, the logical OR is meant to manipulate boolean values only. If any of its arguments are true , it returns true , otherwise it returns false .


2 Answers

You can change it to:

if tx_avt >= 100: tx = 1 
elif tx_avt >= 50: tx = 2 
elif tx_avt >= 25: tx = 3
elif tx_avt >= 12.5: tx = 4 
else: tx = 5

Explanation:

  • If if tx_avt >= 100 is not true, then you can deduce that tx_avt < 100 must be true.
  • This eliminates the need to do the "tx_avt < 100" part in the check "elif tx_avt < 100 and tx_avt >= 50:".

The same logic cascades down & applies to the rest of the elif cases.


Related reading: Why Python Doesn't Have a Switch Statement, and its Alternatives.

like image 188
sampson-chen Avatar answered Oct 23 '22 16:10

sampson-chen


you dont need the upper bounds on the elifs since these are resolved by the clause above them ...

elif tx_avt >= 50 : #do something
elif tx_avt >= 25 : #somthing else

on a side note in python you can do

if 3 < ab < 10 : #check if ab is between 3 and 10
like image 36
Joran Beasley Avatar answered Oct 23 '22 16:10

Joran Beasley