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
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 .
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.
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.
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 .
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 tx_avt >= 100
is not true, then you can deduce that tx_avt < 100
must be true.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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With