简体   繁体   中英

Why does my if statement say that two strings are in a list when its not?

Basically I am creating a calculator, and the program so far asks the user for an operation involving addition, subtraction, multiplication and/or division. Then the program proceeds in creating two list, one containing the full numbers and another one containing the operators. The next part of the code is supposed to check if the list containing the operators contains multiplication or division in the form of an if statement, but the if statement is failing and it's saying that the list contains "*" and "/" when it doesn't, here's the code that's not working. Any Help?

if ("*") or ("/") in Oper_NAN:
 print("POSITIVE")
else
  print("NEGATIVE")

The problem is that the if statement always returns positive and never negative, even when the two operators are not in the list Oper_NAN (all the items in Oper_NAN are strings btw). Am I labeling the if statement wrong? Thank-you for reading!

Given:

if ("*") or ("/") in Oper_NAN: print("POSITIVE") else print("NEGATIVE")

Each side of your or is evaluated individually. So you are considering whether either of these is true:

("*")
("/") in Oper_NAN

The first, being a non-zero-length string, is always evaluated as True in a Boolean context. So your if statement is always True , because True or'd with anything is always True .

The simplest way to fix this is:

 if ("*") in Oper_NAN or ("/") in Oper_NAN:

You could also write it using any() and a generator expression, though this is probably overkill for two characters:

if any(c in Oper_NAN for c in "*/"):

This if statement basically breaks down to the following:

if True or (condition): #code

Everything in python has a truth value and a non-empty string will evaluate to True .

Your if condition is evaluated lazily. The left side is evaluated first and the right-hand side will be evaluated only if the left side is False . But, a non-empty string is always True so your code inside the if condition will always be executed.

Boolean logic / truth value stuff: P or Q for two statments P and Q will evaluate to True in the following cases. P is True , regardless of whether Q is true or false, or P is False and Q is True every other case is False .

If interested here's the more "mathy" side of it, using what's known as a truth table.

| P | Q | P v Q |
-----------------
| T | T |   T   |
-----------------
| T | F |   T   |
-----------------
| F | T |   T   |
-----------------
| F | F |   F   |
-----------------

You could use:

if "*" in Oper_NAN or "/" in Oper_NAN

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM