是否有更好的方法来更改评估字符串

时间:2017-01-21 20:02:32

标签: python-2.7 tkinter eval calculator

是否有更好的方法可以将一个数字更改为浮动分区? 我目前有一个循环扫描我的等式' /'标志和第二个在' /'之后取数字并将其更改为浮动。我该如何改进呢?

#!/usr/bin/env python2.7

import Tkinter as tk


main = tk.Tk()
main.title('Calculator')


def insert_variable(i):
    """Inserts the user defined sign and puts it on the end the entry widget"""
    END = len(calc_entry.get())
    calc_entry.insert(END,i)

def calculate():
    ''' deletes all characters in the entry and inserts evaluation of the equation '''
    equation = calc_entry.get()
    try:
        calc_entry.delete(0, len(equation)) # deletes all characters in the entry
        for i in range(len(equation)-1):# loop for checking for special signs


            if equation[i] == '/': #if there is '/' sign change one of numbers to float
                for j in range(i+1,len(equation)): # loop for number of digits after '/' sign
                    if equation[j] == '.': # if there is dot go ones more
                        pass
                    else:
                        try:
                            int(equation[j])# if there is something other than digit go to exception
                        except ValueError:
                            equation = equation[:i+1] + str(float(equation[i+1:j])) + equation[j:]# change number after / to float and join all strings
                            break

            if equation[i] == '^': # if there is ^ sign change it for '**'
                equation = equation[:i] +'**'+ equation[i+1:]
                print equation


        calc_entry.insert(0, str(round(eval(equation), 3))) # evaluates (calculates) the equation after loop

    except SyntaxError:
        calc_entry.insert(0,'<ERROR>')
    except ZeroDivisionError:
        calc_entry.insert(0,'ERROR DIVISION BY 0')

calc_entry = tk.Entry(main) # creates an entry
calc_entry.grid(row =1, columnspan = 6)


bEquate = tk.Button(main, text="=", command = calculate)
bEquate.grid(row=5, column=3)

bDivision = tk.Button(main, text="/", command = lambda : insert_variable("/"))
bDivision.grid(row=3, column=5)

main.mainloop()

如果我有sqrt()函数给出最后一个数字的sqrt符号怎么办?如何将其实现到calculate()函数?

sqrtChr = unichr(0x221A)
def insert_sqrt():
    """inserts sqrt sign"""
    global sqrtChr
    END = len(calc_entry.get())
    equation = calc_entry.get() # takes the whole user's equation from the entry
    for i in range(-1,-END-1,-1): # loop that goes from -1,-2,-3 to end-1
        if i == -END: # if there are no exceptions like '.' or special sign, inserts sqrt character at beginning of string in the entry
            calc_entry.insert(0,sqrtChr)
        elif equation[i] == '.': # if there is a dot in equation go to next character in equation
            pass
        else:
            try: # if there is a sign insert sqrt character after it and break loop
                int(equation[i])
            except ValueError:
                calc_entry.insert((END+i+1),sqrtChr)
                break

1 个答案:

答案 0 :(得分:0)

使用

from __future__ import division

1/2将为您0.5提供相同的eval("1/2")