Click here to Skip to main content
15,891,846 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hey i made a basic calculator program but i am not getting correct output from it this is my code

Python
def add(first,second):
    return  first+second

def multiply(first,second):
    return  first*second

def subtract(first,second):
    return  first-second

def divide(first,second):
    return  first/second

print("1.division")
print('2.multiplication')
print('3.subraction')
print('4.addition')

user_input = input('enter your choice:')
first_num = float(input('enter first number:'))
second_num = float(input('enter another number:'))

if user_input==1:
    print(divide(first_num,second_num))

elif user_input==2:
    print(multiply(first_num,second_num))

elif user_input==3:
    print(subtract(first_num,second_num))
else:
    print(add(first_num,second_num))

the output i am getting is like this

1.division
2.multiplication
3.subraction
4.addition
enter your choice:2
enter first number:8
enter another number:5
13.0
Can Someone help please?

What I have tried:

I tried using different numbers
Posted
Updated 4-Jun-18 22:06pm
v2

Your input choice is not a number, but a string. It will therefore directly go to the else statement. (addition)

Hope this helps.
 
Share this answer
 
Change your code to:
PHP
if user_input==1:
    print(divide(first_num,second_num))

elif user_input==2:
    print(multiply(first_num,second_num))

elif user_input==3:
    print(subtract(first_num,second_num))

elif user_input==4:
    print(add(first_num,second_num))

else:
    print(add('Error: wrong choice'))

This way, you don't get wrong result, you are told that the user choice was not recognized.
Quote:
I tried using different numbers

As for the problem in code, solution 1 give you the reason.
All input is a string, so you need to convert to integer or compare with string.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900