Python going through all if statements even if the if doesn’t match [duplicate] - python-3.x

This question already has answers here:
Why does "a == x or y or z" always evaluate to True? How can I compare "a" to all of those?
(8 answers)
Closed 5 months ago.
I have a calculator script, and I have a variable for the operator, number 1 and number 2, this is what it looks like
Operator = input(“operator: “)
Num1 = input(“num1 here: “)
Num2 = input(“num2 here: “)
If Operator == “x” or “*”:
#code
I have one of these for all four main math equations but it’s goes through all the ifs and elifs in order even if the ‘operator’ input doesn’t match. Note I have pyttsx3 installed and a text to speech is in the code. Any help would be appreciated.

Your comparison needs to check both conditions.
It should look like:
If Operator=='x' or Operator=='*'
Right now it's evaluating like:
If (Operator=='x') or ('*'==True)
In python a string (like '*') will evaluate as 'True', so your code is always being executed.

The or operator returns the first element if it is truthy, else the second element. Then if looks at what it gets. In this case (Operator == "x") or "*" evaluates to "*", which in turn is truthy. So the if block is entered.
What you would like to do is probably something like
if ( Operator == "x" ) or ( Operator == "*" ):
# code
To back my claim, you can find the definition of or here.
The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.
The string "*" is not empty, so it evaluates to true. See here.

Related

explanation for this python command in a single line

In a tutorial for developing a processing-plugin for QGIS I found the following Python3-code:
# Compute the number of steps to display within the progress bar and
# get features from source
total = 100.0 / source.featureCount() if source.featureCount() else 0
features = source.getFeatures()
My question: What kind of language construct is this single line:
total = 100.0 / source.featureCount() if source.featureCount() else 0
This looks weird: Frist an assignment , which is followed by an if-else-construct in the same line??
These are called "conditional expressions". From the Python 3 reference:
The expression x if C else y first evaluates the condition, C rather than x. If C is true, x is evaluated and its value is returned; otherwise, y is evaluated and its value is returned.
You can read it as "return x if C otherwise return y."
When a conditional expression is used in the assignment to a variable, that variable will take on the value returned by that conditional expression.
This concept is usually referred to as a "ternary" in many other languages.

Why += is considered as an assignment operator while >= is not?

I was thinking why the '=' in '+=' is considered as assignment while '=' in '>=' is not considered as such. There is no importance behind this question but some random thought of a beginner. For example purpose, you can consider that
a = np.array([1,2,3,4,5])
a += 2 # array updated and assigned to a
a>=2 # becomes a boolean indexing filter
a += 2 changes the value of a. It reassigns it's value to be two more than it was before. By the way, += as a whole is the assignment operator, not just the =.
a>=2 does not change the value of a. Yes, it becomes true or false. But 'true' or 'false' is all it is. It does not get assigned to anything. The value of a is as it was before.
You can do b = a>=2. But in that case, = is the assignment operator because it is what assigns the value to b.

How To Understand THE Following Code Snippet?

i came up with understanding confusion , what will be the right explanation for this code?
a = [(0,1),(1,2),(2,3)]
result = sum(n for _,n in a)
print(result)
I guess that your confusion is coming from the , and the fact that sum also accepts a second argument.
In this case, only one argument is passed to sum because that line is evaluated as
result = sum(n for (_, n) in a)
This line simply sums all the second elements in the list of tuples, and it is equivalent to the following:
list_of_tuples = [(0,1),(1,2),(2,3)]
total = 0
for (first_element, second_element) in list_of_tuples:
total += second_element
print(total)
Technically _ is a normal, valid identifier name, but the convention is to use it for values that are disregarded in the next part of the code.
I think another way of thinking of it is:
result=0
for _,n in a:
result += n
You can substitute "_,n" for any other two variables like "x,y" for example.

What value for x will cause math.isfinite(x) to return False? [duplicate]

This question already has answers here:
Alternative methods of initializing floats to '+inf', '-inf' and 'nan'
(5 answers)
Closed 4 years ago.
In Python, the math.isfinite function returns True if the argument passed is a finite number. I want to know expression or equation (equation that generates infinite value) which will return False, other than 'NAN'. Passing a number divided by 0 will give error.
Before asking a question like this, you should always read the documentation. Simply using help(math.isfinite) in a REPL would tell you what values return False.
Help on built-in function isfinite in module math:
isfinite(...)
isfinite(x) -> bool
Return True if x is neither an infinity nor a NaN, and False otherwise.
Like Martijn Peters mentioned, float('inf') and float('-inf') will both produce infinite values. And in Python 3.5+, you also have math.inf as a way to produce those values.
If you want to create value of infinity you should use
float('inf') # positive infinity
These value below are all False
import math
math.isfinite(float('inf'))
math.isfinite(float('-inf'))
math.isfinite(float('nan'))

x>y && z==5 - how are parts of this expression called?

I know && is the logical operator here, also conditions on the left and on the right are operands, right?
Like:
1+1 is an expression where + is the operator and the numbers are operands. I just do not know whether the condition itself is called the operand as well because it get compared by an operator. I guess so.+
Thanks
What are the parts called?
>, &&, and == are all operators. Operands are the values passed to the operators. x, y, and z are the initial operands. Once x > y and z == 5 are evaluated, those boolean results are used as the operands to the && operator which means the expressions themselves are not the operands to &&, the results of evaluation those expressions are the operands.
When you put operands and an operator together, you get an expression (i.e. x > y, z == 5, boolResult == boolResult)
How are they evaluated?
In most (if not all) languages x > y will be evaluated first.
In languages that support short circuiting, evaluation will stop if x > y is false. Otherwise, z == 5 is next.
Again, in languages that support short circuiting, evaluation will stop if z == 5 is false. Otherwise, the && will come last.
>, &&, and == are all operators. Operands are the values passed to the operators. x, y, and z are the initial operands. Once x > y and z == 5 are evaluated, those boolean results are used as the operands to the && operator.
One alternative would be to turn to the grammar of C#
It states the following:
conditional-and-expression && inclusive-or-expression
Just generalizing it as "expressions" is probably accurate enough :)
If your question is really what the parts left and right of the && are called, I’d say “expression”, maybe “boolean expression”.
Conditions, or in case of ||: Alternatives
In c# the && is an operator and the left and right are expressions. In an if statement, if the left evaluates to true the right will never be evaluated.
It's a boolean comparison expression that's comprised of two separate boolean comparison expressions.
Depending on the language, how this is interpreted depends on operator precedence. Since it looks like a C-like dialect, I'll assume && is short-circuit AND. (More explanation here).
Order of operations would be left to right as the equality testers (>, >=, <=, ==, !=) have equal precedence to boolean operations (&&, ||).
x > y would be evaulated, and if true, z == 5 would be evaluated, and then the first and second results would be ANDed together. However, if x > y was false, the expression would immediately return false, due to short-circuiting.
You're correct that x>y and z==5 are operands, and && is an operator. In addition, both of these operands in turn contain their own operands and operators. These are called complex operands
So:
x>y and z==5 are operands to the operator &&
x and y are operands to the operator >
z and 5 are operands to the operator ==
Regarding the individual component parts and how to name them:
Both == and > are comparison operators, which compare the values of two operands.
== is an equality operator, and evaluates to true if the left operand is equal to the right operand.
> is a greater than operator, and evaluates to true if the left operand is greater than the right operand.
&& is a logical operator, specifically logical AND. It evaluates to true if both the left and the right operand are true.
When referring to each operand, it's standard to refer to them by their position, i.e. the left operand and right operand - although there's no "official" name - first and second operand work equally well. Note that some operators such as ! have only one operand, and some even have 3 (the ternary operator, which takes the form condition ? true_value : false_value

Resources