Basic calculator program in python [closed]

时光怂恿深爱的人放手 提交于 2019-12-13 07:32:20

问题


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 fails to identify the signs. please leave your comments to clear me...

#! /usr/bin/python

print("1: ADDITION")
print("2: SUBTRACTION")
print("3: MULTIPLICATION")
print("4: DIVISION")

CHOICE = raw_input("Enter the Numbers:")

if CHOICE == "1":
    a = raw_input("Enter the value of a:")
    b = raw_input("Enter the value of b:")
    c = a + b
    print c

elif CHOICE == "2":
    a = raw_input("Enter the value of a:")
    b = raw_input("Enter the value of b:")
    c = a - b
    print c

elif CHOICE == "3":
    a = raw_input("Enter the value of a:")
    b = raw_input("Enter the value of b:")
    c = a * b
    print c

elif CHOICE == "4":
    a = raw_input("Enter the value of a:")
    b = raw_input("Enter the value of b:")
    c = a / b
    print c

else: 
 print "Invalid Number"
 print "\n"

回答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:"))



回答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).

def get_int(prompt):
    while True:
        try:
            return int(raw_input(prompt))
        except ValueError, e:
            print "Invalid input"

a = get_int("Enter the value of a: ")



回答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

def get_float(prompt):
    while True:
        try:
            return float(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.



来源:https://stackoverflow.com/questions/13509078/basic-calculator-program-in-python

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!