-3

the function i have written....

def calculate_price(Thickness, Width, Price, Timbmet):
    foo = Thickness * Width;
    bar = foo * Price;
    if Timbmet == "n" or "N":
        foobar = ((bar / 100) * 15) + 100
        print foobar
    else:
        print bar



calculate_price(5., 4., 3., "y");

the console output is 109 which is wrong because it shouldn't have executed the code in the if statement because the Timbmet parameter does not match "n" or "N". What am I doing wrong and why is the code not running the else part?

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
  • 1
    Short answer: `Timbmet == "n" or "N"` is not the same as `Timbmet == "n" or Timbmet == "N"`, and will always evaluate `True` – jonrsharpe Jun 10 '14 at 17:12
  • To elaborate on jonrsharpe's comment, you have two conditions in the `or`: `(Timbmet == "n")`, which might be true or false, and `("N")`, which is nonzero and therefore always true. You must understand the syntax to write good code. – Tom Zych Jun 10 '14 at 17:22

2 Answers2

1

Change condition to -

if Timbet in ["n", "N"]:

Programming does not work like natural language...

Tom Ron
  • 5,906
  • 3
  • 22
  • 38
0

The condition Timbmet == "n" or "N" returns always True because the second subexpression "N" is always True. You need to either check if Timbet is in a list/set:

if Timbet in ("n", "N"):
if Timbet in {"n", "N"}:  # even better but more confusing if we are not aware of the set construction syntax

... or check without the case sensitivity:

if Timbet.lower() == "n":
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97