 # My if statement isnt working

Hello fellow coders!

Here is my situation: I have to create a calculator and so far all of my IF statements are working except for the last one. I’m not sure why it goes into the one before it but I would appreciate some help as I have been trying to do this for a few hours now.

Whenever I type “E” it does the operations for “D”. All of the other operations work except for this one and I am unsure why. Please help and thank you in advance!

print(“")
print(" Welcome to the Calculator Project!!!")
print("
”)

``````print("A.) Addition")
print("B.) Subtraction")
print("C.) Multiplication")
print("D.) Division")
print("E.) Roots (only positive numbers)")
print("F.) Power (only positive numbers)")
print("G.) Percentage")
print("H.) Least Common Multiplier")
print("I.) Greatest Common Divisor")
print("J.) Modulus")
print("K.) Display Function Execution*")
print("L.) Quit")
print("____________________________________________________________________________________________________")
print("Please select an operation. Type quit to quit ")
``````

sum= first + second
return sum;

def subtraction (first, sec):
diff = first - sec
return diff

def multiplication (first, second):
prod = first * second
return prod

def division (first, sec):
quot = first / sec
return quot

def power(x, n):
numProduct = 1.0
while i < n:
numProduct *= x
i=i+1
return numProduct

def root(roots, index):
low = 0.0
high = roots
mid = (low + high) / 2
if (power(mid, index) > roots):
high = mid
else:
low = mid
mid = (low + high) / 2
tp = (power(mid, index) - roots)
if (tp < 0):
tp = -tp
return mid

def GCD(a, b):
while (a != b):
if (a > b):
a -= b
else:
b -= a
return a

def LCM(a,b):
f= ((a * b) / GCD(a, b))
return f

def displayFunctionExecution():

``````    return "Go team!"
``````

userInput = input()

while (userInput != “quit”):

``````if userInput is "A" or userInput is 'a':
firstNum = float(input())
print("Enter second number")
secondNum = float(input())
print("Operation: %f + %f = " % (firstNum, secondNum), end='')
print(displayFunctionExecution())

elif userInput is "B" or userInput is "b":
num1 = float(input())
print("Enter the second number")
num2= float(input())
print("Operation: %f - %f = " % (num1, num2), end="")
print(subtraction(num1,num2))

elif userInput is "C" or userInput is "c":
print("Enter the first number")
nums1 = float(input())
print("Enter second number")
nums2 = float(input())
print("Operation: %f * %f = " % (nums1, nums2), end="")
print(multiplication(nums1,nums2))

elif userInput is "D" or "d":
print("Enter first number")
div1 = float(input())
div2= float(input())
print("Operation: %f / %f = " % (div1, div2), end="")
print(division(div1,div2))

elif userInput is "E" or "e":
print("Enter the first number")
n1 = float(input())
while(n1 < 0):
print("Error: Enter only positive numbers!")
n1= float(input())
print("Enter the second number")
n2 = float(input())
while(n2 <0):
print("Error: Enter only positive numbers!")
n2= float(input())
print("Operation: %f root %f = " % (n1, n2), end="")
print(root(n1, n2))

elif userInput is "F" or "f":
print("Enter the first number")
p1 = float(input())
while(p1 < 0):
print("Error: Enter only positive numbers!")
p1= float(input())
print("Enter the second number")
p2 = float(input())
while(p2 <0):
print("Error: Enter only positive numbers!")
p2= float(input())
print("Operation: %f to the power of %f = " % (p1, p2), end="")
print(power(p1, p2))

userInput = input()``````
1 Like

Hello hachemm,

I looked at your code and i don’t see a reason why it would go to D instead of E. I don’t think the bug is inside the code you posted.

Could you post the whole code maybe ?

Also posting your code as an image has some drawbacks. for example: We wont be able to quote the parts where the bug is located and we can’t try out the code our self’s.

A good way to post in code is to just litterly copy paste the code or (in case of python) make a jupyter notebook and make a hyperlink to there.

2 Likes

https://hub.mybinder.org/user/ipython-ipython-in-depth-iy1h6yxg/notebooks/binder/.ipynb

I’ve never used this before so please let me know if you need anything else. Thank you. When you output it, A goes to A function,…D to D function. But when user input is E,F,etc it will enter the D if statement. Any and all advice is appreciated.

Reverse Polish Notation is popular in HP calculators for scientists (or at least was at one time). One types in a value for A, then a value for B, then chooses an operation.

We could do the same here and collect all inputs in one place, instead of four.

``````def get_a_b():
def get_n(symbol):
return float(input("Enter a value for %s" % symbol))
return get_n('A'), get_n('B')
``````

We can discuss weaknesses later. For now use valid inputs to test the code.

The return from `get_a_b` will be a tuple, so it would be unpacked to expose the values.

``````a, b = get_a_b()
``````

Now we get into the operations.

``````>>> def a_b_op(x):
def get_f():
return input('[+|-|*|/|**|^|√=r]')
return a + b
def sub():
return a - b
def mul():
return a * b
def div():
return a / b
def pow():
return a ** b
def exp():
return b ** a
def root():
return a ** (1 / b)
def ops(f):
return [add, sub, mul, div, pow, exp, root][\
['+','-','*','/','**','^','r'].index(f)]
a, b = x
return ops(get_f())()

>>>
``````
``````>>> a_b_op(get_a_b())
Enter a value for A: 6
Enter a value for B: 7
[+|-|*|/|^|√=r]*
42.0
>>> a_b_op(get_a_b())
Enter a value for A: 27
Enter a value for B: 3
[+|-|*|/|^|√=r]r
3.0
>>> a_b_op(get_a_b())
Enter a value for A: 2
Enter a value for B: 10
[+|-|*|/|**|^|√=r]**
1024.0
>>> a_b_op(get_a_b())
Enter a value for A: 10
Enter a value for B: 2
[+|-|*|/|**|^|√=r]^
1024.0
>>>
``````

I hope you’re not dissappointed there are no if’s there. We’ve made this rather declarative. It is, or it isn’t. The isn’t part we still need to sort out.

1 Like

thank you that helped so much!!

1 Like

A slight paradigm shift from what you had, no doubt. I trust you are following the logic, okay? Did you discover the weaknesses I spoke of earlier?

For instance, we are not verifying number input. Below we address that.

``````>>> def get_a_b():
def get_n(symbol):
while True:
try:
return float(input("Enter a value for %s: " % symbol))
except ValueError:
print("Try again...")
return get_n('A'), get_n('B')

>>> a_b_op(get_a_b())
Enter a value for A: k9
Try again...
Enter a value for A: 729
Enter a value for B: d7
Try again...
Enter a value for B: 3
[+|-|*|/|**|^|√=r]r
8.999999999999998
>>> a_b_op(get_a_b())
Enter a value for A: 9
Enter a value for B: 3
[+|-|*|/|**|^|√=r]**
729.0
>>>
``````

This is a preliminary cure for a weakness, the operator input.

``````>>> def a_b_op(x):
def get_f():
return input('[+|-|*|/|**|^|√=r]')
return a + b
def sub():
return a - b
def mul():
return a * b
def div():
return a / b
def pow():
return a ** b
def exp():
return b ** a
def root():
return a ** (1 / b)
def fn(f):
return [add, sub, mul, div, pow, exp, root][\
['+','-','*','/','**','^','r'].index(f)]
a, b = x
while True:
try:
return fn(get_f())()
except ValueError:
print ("Try again...")

>>>
``````
``````>>> a_b_op(get_a_b())
Enter a value for A: 9
Enter a value for B: 3
[+|-|*|/|**|^|√=r]n
Try again...
[+|-|*|/|**|^|√=r]**
729.0
>>>
``````