Home > Software design >  this code always go to else I tried to put if in if to force code to go to it but still go to else
this code always go to else I tried to put if in if to force code to go to it but still go to else

Time:11-22

def add(x, y):
    return x   y
def multiple(x, y):
    return x * y
def subtrack(x, y):
    return x - y
def divide(x, y):
    return x / y
print('select your operation please')
print('1-Add')
print('2-Multiple')
print('3-subtrack')
print('4-Divide')
chose=int(input('enter your selection please: '))
num1=int(input('enter your first num please: '))
num2=int(input('enter your second num please: '))

if chose == '1':
    print(num1,' ',num2,'=',add(num1,num2))
elif chose == '2':
    print(num1,'*',num2,'=',multiple(num1,num2))
elif chose == '3':
    print(num1, '-', num2, '=', subtrack(num1,num2))
elif chose == '4':
    print(num1,'/',num2,'=',divide(num1,num2))
else:
    print("invalid number operation")

this code always go to else I tried to put if in if to force code to go to it but still go to else some solutions please

CodePudding user response:

When doing:

if chose == '1'

You're comparing to a char in python. If you do if chose == 1 you're actually comparing to a int. Which is also what you enter in the inputs. removing the "'" around the right hand side of your if comparison operators, you will not keep getting pushed to the 'else' statement!

CodePudding user response:

I don't know what language this is but chose is an int an your if checks on an string(or char depending the language).

if you change your comparison to:

if chose == 1:
    print(num1,' ',num2,'=',add(num1,num2))
elif chose == 2:
    print(num1,'*',num2,'=',multiple(num1,num2))
elif chose == 3:
    print(num1, '-', num2, '=', subtrack(num1,num2))
elif chose == 4:
    print(num1,'/',num2,'=',divide(num1,num2))
else:
    print("invalid number operation")

It should work as expected

CodePudding user response:

You are receiving user input and converting to int and while comparison you are comparing it with string i,e. if chose == '1':

the solution is:

1.you receive user input in int or compare the integer value

chose=int(input('enter your selection please: '))
if chose == 1:
    print(num1,' ',num2,'=',add(num1,num2))
elif chose == 2:
    print(num1,'*',num2,'=',multiple(num1,num2))
elif chose == 3:
    print(num1, '-', num2, '=', subtrack(num1,num2))
elif chose == 4:
    print(num1,'/',num2,'=',divide(num1,num2))
else:
    print("invalid number operation")

2.You receive user input in str and compare the string value

chose=str(input('enter your selection please: '))'=
if chose == '1':
    print(num1,' ',num2,'=',add(num1,num2))
elif chose == '2':
    print(num1,'*',num2,'=',multiple(num1,num2))
elif chose == '3':
    print(num1, '-', num2, '=', subtrack(num1,num2))
elif chose == '4':
    print(num1,'/',num2,'=',divide(num1,num2))
else:
    print("invalid number operation")
  • Related