0
나누기에서 부동 소수점 숫자로 변경하는 더 좋은 방법이 있습니까? 현재 '/'기호에 대한 내 방정식을 스캔하는 루프가 하나 있고 '/'다음에 숫자를 가져 와서 float으로 변경하는 두 번째 루프가 있습니다. 어떻게 개선 할 수 있습니까?평가를 위해 문자열을 변경하는 더 좋은 방법이 있습니까
#!/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
당신은 무엇을하려고 하는가? 'split ('/')'또는 직접'eval ("1/2")'을 사용할 수 없습니까 (일부 문자 만 사용하도록 텍스트를 필터링 할 수 있으며 안전하지 않은 코드로는 문제가 없습니다). – furas
BTW :''2^3^4 '. replace ('^ ','** ')' – furas
"2 + 2/2 + 2"와 같은 방정식을 취한 계산기를 만들었습니다. 그것은 작동하지 않을 것이다,'replace' 함수를 주셔서 감사합니다. – ProsTedi