【问题标题】:Python squarerootingPython平方根
【发布时间】:2015-12-23 14:55:14
【问题描述】:

我有一个使用 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() 按钮的按钮。似乎无论平方根之前是什么数字(有效或其他),它都会通过 except 子句返回“错误”。

【问题讨论】:

  • 我的意思是它进入了 except 子句,因此返回“错误”
  • 您需要将 num 设为浮点数。我想你现在把它当作一个字符串..
  • num 是一个字符串。你不能取字符串的平方根。
  • 旁白:使用一个空的except: 基本上意味着“不管出了什么问题,不要告诉我,我不想知道问题是什么”。这几乎不是一个好主意。

标签: python calculator


【解决方案1】:

你需要转换类型:

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"

【讨论】:

  • 谢谢,我会试试的。为什么我需要转换输出? .insert 允许传递非字符串类型。
  • 但它不知道给出的内容不应该是字符串。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-01
  • 2019-05-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多