Python平方根
我有一个使用Tkinter的计算器(程序的全部代码是),但是平方根函数不起作用Python平方根,python,calculator,Python,Calculator,我有一个使用Tkinter的计算器(程序的全部代码是),但是平方根函数不起作用 def calculate(self): """ Calculates the equasion """ calculation = self.out_box.get("1.0", tk.END) try: eval(calculation) except: ans = "Error" else: ans = eva
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()按钮。似乎无论平方根前面是什么数字(有效或其他),它都会通过except子句返回“Error”。您需要转换类型:
num = float(self.out_box.get("1.0", tk.END))
self.out_box.insert(tk.END, str(ans))
此外,您的尝试
-,除了
-之外
没有意义:
try:
math.sqrt(num)
except:
ans = "Error"
else:
ans = math.sqrt(num)
难道不是:
try:
ans = math.sqrt(num)
except:
ans = "Error"
我的意思是它转到except子句,因此返回“Error”需要将num设为浮点。我想你现在把它当成了一个字符串。
num
是一个字符串。你不能取字符串的平方根。旁白:使用裸,除了:
基本上意味着“不管出什么问题,不要告诉我,我不想知道问题出在哪里”。那几乎从来都不是个好主意。谢谢,我试试看。为什么我需要转换输出。insert允许传递非字符串类型。但它不知道所给出的不应该是字符串。