Python 平方根
Python squarerooting
我有一个使用 Tkinter 的计算器(程序的整个代码是 here)但是平方根函数不起作用。
def calculate(self):
""" Calculates the equasion """
calculation = self.out_box.get("1.0", tk.END)
try:
eval(calculation)
except:
ans = "Error"
else:
ans = eval(calculation)
self.clear()
self.out_box.insert(tk.END, ans)
def calc_root(self):
""" Calculates an equasion with a root """
import math
self.calculate()
num = self.out_box.get("1.0", tk.END)
try:
math.sqrt(num)
except:
ans = "Error"
else:
ans = math.sqrt(num)
self.clear()
self.out_box.insert(tk.END, ans)
我有一个链接到 calc_root() 按钮的按钮。似乎无论什么数字(有效或无效)在平方根之前,它 returns "Error" 通过 except 子句。
您需要转换类型:
num = float(self.out_box.get("1.0", tk.END))
self.out_box.insert(tk.END, str(ans))
你的try
-except
-else
也没有意义:
try:
math.sqrt(num)
except:
ans = "Error"
else:
ans = math.sqrt(num)
不应该是:
try:
ans = math.sqrt(num)
except:
ans = "Error"
我有一个使用 Tkinter 的计算器(程序的整个代码是 here)但是平方根函数不起作用。
def calculate(self):
""" Calculates the equasion """
calculation = self.out_box.get("1.0", tk.END)
try:
eval(calculation)
except:
ans = "Error"
else:
ans = eval(calculation)
self.clear()
self.out_box.insert(tk.END, ans)
def calc_root(self):
""" Calculates an equasion with a root """
import math
self.calculate()
num = self.out_box.get("1.0", tk.END)
try:
math.sqrt(num)
except:
ans = "Error"
else:
ans = math.sqrt(num)
self.clear()
self.out_box.insert(tk.END, ans)
我有一个链接到 calc_root() 按钮的按钮。似乎无论什么数字(有效或无效)在平方根之前,它 returns "Error" 通过 except 子句。
您需要转换类型:
num = float(self.out_box.get("1.0", tk.END))
self.out_box.insert(tk.END, str(ans))
你的try
-except
-else
也没有意义:
try:
math.sqrt(num)
except:
ans = "Error"
else:
ans = math.sqrt(num)
不应该是:
try:
ans = math.sqrt(num)
except:
ans = "Error"