Home > Blockchain >  Why doesn't it work I'm trying to make a simple calculator
Why doesn't it work I'm trying to make a simple calculator

Time:12-03

def add(a, b):
    return a   b

print("choose 1 to add and 2 to subtract")
select = input("enter choice 1/2")

a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))

if select == 1:
    print(a, " ", b, "=", add(a, b))

I don't know why it doesn't wanna add

CodePudding user response:

You need to convert select into an int

def add(a, b):
    return a   b

print("choose 1 to add and 2 to subtract")
select = int(input("enter choice 1/2"))

a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))

if select == 1:
    print(a, " ", b, "=", add(a, b))

CodePudding user response:

You need to convert the select variable to integer. By default, the input is taken as string value. You can also use f-string (see more at Formatted String Literals documentation) for printing values from variables in the print statement which gives you much more flexibility to format the string:

def add(a, b):
    return a   b


print("choose 1 to add and 2 to subtract")
select = int(input("enter choice 1/2: "))
a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))
if select == 1:
    print(f"{a}   {b} = {add(a, b)}")

Output:

choose 1 to add and 2 to subtract
enter choice 1/2: 1
enter 1st nunber: 21
enter 2nd number: 3
21.0   3.0 = 24.0

CodePudding user response:

input returns a string, but in the line if select == 1 you are comparing it to an int. There are several solutions to this, but the solution I would go with is to use only strings, i.e. if select == "1". 1 and 2 are arbitrary values, so it isn't really necessary for them to be converted to numbers. You could just as easily use a and b to accomplish the same goal.

Another useful thing you can do is validate the user input. I would do that with something like this:

while select not in ["1", "2"]:
    print(f"you entered {select}, which is not a valid option")
    select = input("enter choice 1/2")

This will continue to ask the user to select one of the choices until they enter a valid one, and also has the added bonus of helping you catch errors in your code like the int vs str issue.

CodePudding user response:

As others mentioned, since input returns a str, it should be compared with an object of same type. Just changing 1 to str(1) on line 10 will solve the issue.

def add(a, b):
    return a   b

print("choose 1 to add and 2 to subtract")
select = input("enter choice 1/2")

a = float(input("enter 1st nunber: "))
b = float(input("enter 2nd number: "))

if select == str(1):
    print(a, " ", b, "=", add(a, b))
  • Related