Python creating a calculator

后端 未结 4 1208
傲寒
傲寒 2020-12-22 12:50

I am fairly new to python.

I have been asked to create a calculator using only string commands, conversions between int/string/float etc.(if needed), and using funct

4条回答
  •  孤城傲影
    2020-12-22 13:12

    I have an alternative to your code. The user can enter stuff like: 8*6/4-3+3 and this will still work. It also will not crash if a letter (d, a, s) is entered. Very compact.

    Code (Python v3.3.0):

    valid_chars = "0123456789-+/* \n";
    while True:
        x = "x="
        y = input(" >> ")
        x += y
        if False in [c in valid_chars for c in y]:
            print("WARNING: Invalid Equation");
            continue;
        if(y == "end"):
            break
        exec(x)
        print(x)
    

提交回复
热议问题