0

Currently working on my first program and my Else statement isn't working in the following code:

info = input("<Y/N>")

if (info == "Y" or "y"):
   print("Calculating...")

else:
   raise SystemExit

The program just continues to

print("Calculating...")

even if the input isn't "Y" or "y"

petezurich
  • 9,280
  • 9
  • 43
  • 57
Evan
  • 49
  • 4

4 Answers4

5
if (info == "Y" or "y"):

is equivalent to saying

if ((info == "Y") or ("y"))

Since y is not zero, null, or equivalent, it evaluates to true. The either of the following will do:

if (info == "Y" or info == "y")
if (info in ("y", "Y"))
if (info.lower() == "y")
Vadim
  • 642
  • 1
  • 4
  • 19
1

You should write something like this:

info = input("<Y/N>")

if (info == "Y" or info == "y"):
   print ("Calculating...")

else:
   raise SystemExit

In your statement:

info == "Y" or info == "y"

"y" is always True

Phoenix
  • 3,996
  • 4
  • 29
  • 40
1

What's happening is that the or operator is treating the left and right side as boolean (True and False) statements. What it's looking to see on the left side is info == "Y" which might be true or false depending on the input. On the right side it's seeing "y" and checking if "y" is true. In python non-empty strings count as true when evaluated as booleans. To fix this here are two ways to check.

  1. if info == "Y" or info == "y":
  2. if info in ["y", "Y"]:
Misha Melnyk
  • 409
  • 2
  • 5
0

Let me just add this to the above answers: a more pythonic way of checking

if (info == 'Y' or info == 'y')

is done by

if info.lower() == 'y'.

Of course, info needs to be a string.

GRquanti
  • 527
  • 8
  • 23