Reputation: 11
im trying to make a calculator but for some reason when it comes to picking an operation it will only do add the elif statements do not execute even if i input the right command for it
print("welcome to the simple calculator please type in a number")
#user enters 1st number
Num1=int(input("type a number between 0-9"))
#user enters 2nd number
Num2=int(input("please type in your second number"))
#user enters the operation that is used
Ope=input("would you like to divde,add,subtract or times")
#adds the numbers
if Ope=="add"or"Add":
print(Num1+Num2)
#subtracts the numbers
elif Ope=="subtract" or "Subtract":
print(Num1-Num2)
elif Ope=="times" or "Times":
print(Num1*Num2)
elif Ope=="divide" or "Divide":
print(Num1/Num2)
Upvotes: 0
Views: 72
Reputation: 16993
Two weird things you are doing here that will cause you problems:
When comparing a single variable against multiple values, there are many ways to do it, but to keep things simple, you should change:
if Ope=="add"or"Add":
to
if Ope == "add" or Ope == "Add":
This is not the best way to compare against multiple values, but it is a simple way to do what you are trying to do. However, you will achieve unexpected results with the way you have it now. Ope == "add" or "Add"
will always be True
because what this actually does is checks the truth value of Ope == "add"
and of "Add"
and returns the first one that evaluates to True
, or the second one if neither is True
. In this case bool("Add")
will always be True
, so you will always get the if
block. If that doesn't make sense to you, don't worry; it really is confusing in my opinion. It is something that you will eventual just start to get if you work with Python long enough.
You are checking for case, when you could just .lower()
the value of Ope
and test against the lowercase version:
Ope = input("would you like to divide,add,subtract or times").lower()
if Ope=="add": # and do the same for the elif statements
...
Upvotes: 0
Reputation: 19352
Code Ope=="add"or"Add"
is evaluated in the order defined by operator precedence: first ==
, then or
.
So, for any Ope
other than "add", it evaluates to:
(Ope == "add") or "Add"
=> False or "Add"
=> "Add"
and for Ope
equal to "add", it evaluates to:
(Ope == "add") or "Add"
=> True or "Add"
=> True
Therefore, the value is either "Add"
or True
, and both of them are true (see truth value testing) and the first if
will always be satisfied.
(see also how or
works)
if Ope.lower() == "add":
...
elif Ope.lower() == "subtract":
...
Upvotes: 1