-1

I tried to create a simple calculator using python.

My code is this:

def add(x, y):
   return x + y

def subtract(x, y):
 return x - y

def multiply(x, y):
 return x * y

def divide(x, y):
  return x / y
   invalid_input = True

print("Available operations")
print("1.Add")
print("2.Subtract")
print("3.Multiply")
print("4.Divide")

choice = input("Choose one of the available operations:")
if choice >= '1' and choice <= '4':

num1 = int(input("First Number:"))
num2 = int(input("Second Number:"))

if choice == '1':
    print(num1,"+",num2,"=", add(num1,num2))

elif choice == '2':
    print(num1,"-",num2,"=", subtract(num1,num2))

elif choice == '3':
     print(num1,"*",num2,"=", multiply(num1,num2))

elif choice == '4':
    print(num1,"/",num2,"=", divide(num1,num2))
else:
    print ("invalid number")

It works perfectly fine except of one thing.

I assume the problem is here:

if choice >= '1' and choice <= '4':

When i enter 5, I get the invalid number output but when I enter a number like 12 or any number with 1,2,3 or 4 it goes inside the if and asks First number.I know how to fix it but I want to understand why this happens.Thanks in advance

Mr Singh
  • 3,936
  • 5
  • 41
  • 60
static_cast
  • 23
  • 1
  • 4
  • You're comparing strings, and they are compared [lexicographically][1], '12' < '4' is `True`. So the solution is to convert your choices to integers.[1]: https://en.wikipedia.org/wiki/Lexicographical_order – Chris_Rands Feb 16 '18 at 11:00
  • "I know how to fix it but I want to understand why this happens" so there shouldn't be an issue just do some research on it – L_Church Feb 16 '18 at 11:01
  • This might help [Comparing Numbers in string](https://stackoverflow.com/questions/3270680/how-does-python-compare-string-and-int) – Sociopath Feb 16 '18 at 11:02

2 Answers2

1

You have to convert your string input to a int before compairing. Try:

int(choice) >= 1 and int(choice) <= 4

Or you can directly take the user input as int like mentioned here. May be you can inprove it with combining two conditions like,

1 <= int(choice) <= 4

Ref:

Chamath
  • 2,016
  • 2
  • 21
  • 30
1
if choice >= '1' and choice <= '4':

you are comparing strings in that line and therefore '12' > '1' and '12' <= '4' is both true because you are not comparing the numbers, but the single characters. It becomes more clear when we convert the example to comparing characters:

'ab' > 'a' and 'ab' < 'd'
FlyingTeller
  • 17,638
  • 3
  • 38
  • 53