Basic Calculator Program In Python
I just wrote a simple calculator script in python, generally python should recognize the (-)minus,(*)multiplication,(/)divide sign by default but while considering this script it's
Solution 1:
You need to change your inputs, strings to integer or float. Since, there is division you are better change it to float.
a=int(raw_input("Enter the value of a:"))
a=float(raw_input("Enter the value of a:"))
Solution 2:
When you get the input it is a string. The +
operator is defined for strings, which is why it works but the others don't. I suggest using a helper function to safely get an integer (if you are doing integer arithmetic).
defget_int(prompt):
whileTrue:
try:
returnint(raw_input(prompt))
except ValueError, e:
print"Invalid input"
a = get_int("Enter the value of a: ")
Solution 3:
Billwild said u should change to make your variables integers. But why not float. It is not important if it is integer or float it must be number type. Raw_input takes any input like string.
a=float(raw_input('Enter the value of a: '))
Or for Tim's aproach
defget_float(prompt):
whileTrue:
try:
returnfloat(raw_input(prompt))
except ValueError, e:
print"Invalid input"
a = get_float("Enter the value of a: ")
You can always convert result to float or to int or back. It is just matter what kind of calculator u are programming.
Post a Comment for "Basic Calculator Program In Python"