0

i have been following tutorials on W3Schools and have decided to make a calculator with Python. I have used a input for the input and a if statement to register whether it says "quit" to stop the calculator or if it is a number to add it to an array. But every single time i run it, it will return the Quitting message which is only in the if statement even if i put a result that should be in the else code. Thanks for the help btw! Here's my code.

print("Calculator")

NumberArray = []
InputNumber = input()
if InputNumber == "Quit" or "quit":
    #Calculate()
    print("Quitting... ")
    exit()
else:
    print(InputNumber) #Just to debug it!
Pheonix VX
  • 29
  • 8
  • `InputNumber == "Quit" or InputNumber == "quit":` or `InputNumber in ["Quit", "quit]`. `or "quit"` evaluates to true so your if statement is always true. – Loocid Mar 07 '19 at 02:35
  • Thank u, Loocid! Post it as an answer and i'll mark it. – Pheonix VX Mar 07 '19 at 02:36
  • Since its locked I cant post answers. It's ok though, glad to know it helped. – Loocid Mar 07 '19 at 02:38
  • `if InputNumber.lower() == "quit":` I would be tempted to just convert the string to lower and then compare, so it is case insensitive. – Adan Rehtla Mar 07 '19 at 02:41

1 Answers1

0

The two choices in your if statement are evaluated independently, and "quit" evaluates to true. What you wanted to do was:

print("Calculator")

NumberArray = []
InputNumber = input()
if InputNumber in ("Quit", "quit"):
    #Calculate()
    print("Quitting... ")
    exit()
else:
    print(InputNumber) #Just to debug it!
rgk
  • 985
  • 8
  • 16
  • Thanks rgk, Loocid also suggested the same idea. – Pheonix VX Mar 07 '19 at 02:37
  • Also i don't see how this works as the string is not in the InputNumber but instead is the InputNumber, it'd be great if they had some documentation on that. Also how does "quit" automatically return true? – Pheonix VX Mar 07 '19 at 02:42
  • Because strings *are* true! `bool("False") -> True` – rgk Mar 07 '19 at 02:46
  • @PheonixVX It is already documented, have you done any research? See https://docs.python.org/2/library/stdtypes.html#truth-value-testing: `All other values are considered true — so objects of many types are always true.` – Selcuk Mar 07 '19 at 02:46
  • I don't see how they got the logic of strings have to be true unless programmed to not be. Well anyway thanks. Oh their i see the other values always return true. Thankls btw – Pheonix VX Mar 07 '19 at 02:47
  • Only empty strings are false: `bool("")`, that way you can do things like `if mystring: etc...` – rgk Mar 07 '19 at 02:47
  • Under the hood, bool is actually doing `bool("".__len__())`, which happens to return '0' for empty strings and `>1` for everything else. Which is why most objects will return True unless len(obj) = 0 – rgk Mar 07 '19 at 02:53