python - Calculator code problems: 10 + 5 results in 105 -
i'm new forum , new python after c++.
i have problem python calculator. when run , + example : 10 + 5 gives 105, wanted 15.
other operations don't work (i error).
print("\ncalculator in python") print("\nchose operation :") print("\na)+\n\nb)-\n\nc)/\n\nd)*") answer = input("\n\n: ") result = int  if answer == 'a':     = input("\n\nfirst number : ")     b = input("\n\nsecond number : ")     print(a, "+", b, "=", a+b) elif answer == 'b':     = input("\n\nfirst number : ")     b = input("\n\nsecond number : ")     print(a, "-", b, "=", a-b) elif answer == 'c':     = input("\n\nfirst number : ")     b = input("\n\nsecond number : ")     print(a, "/", b, "=", a/b) elif answer == 'd':     = input("\n\nfirst number : ")     b = input("\n\nsecond number : ")     print(a, "*", b, "=", a*a)      
a+b '10'+'5', '105'. happening because  input() gives string. need convert number first. 
float(input())   additionally, ensure user gives valid numbers, can use:
while true:     = input('\ngive a:')      try:         = float(a)         break     except valueerror:         print('try again.')      
Comments
Post a Comment