1

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.

Cabbage
  • 17
  • 7

2 Answers2

1

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.

0

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.

lucidbrot
  • 5,378
  • 3
  • 39
  • 68