【问题标题】:Python Square Root Calculator ErrorPython平方根计算器错误
【发布时间】:2017-03-21 06:33:17
【问题描述】:

我想做一个简单的平方根计算器。

num = input('Enter a number and hit enter: ')

if len(num) > 0 and num.isdigit():
    new = (num**0.5)
    print(new)
else:
    print('You did not enter a valid number.')

似乎我没有做错任何事情,但是,当我尝试运行程序并输入数字后,我遇到以下错误消息:

Traceback (most recent call last):
File "/Users/username/Documents/Coding/squareroot.py", line 4, in <module>
new = (num**0.5)
TypeError: unsupported operand type(s) for ** or pow(): 'str' and 'float'

Process finished with exit code 1 

【问题讨论】:

  • 您仔细检查输入是否可以转换为数字,然后实际上不必费心去做
  • 另外,1.51E10 这样的数字将无效 - 为什么? pythonic 方式是try 将输入转换为float 并仅在发生异常时打印错误消息。

标签: python calculator square-root calculation


【解决方案1】:

您可以使用此解决方案。这里的 try and catch 能够处理各种输入。所以你的程序永远不会失败。而且由于输入正在转换为浮点数。您不会遇到任何类型相关的错误。

try:
    num = float(input('Enter a positive number and hit enter: '))
    if num >= 0:
        new = (num**0.5)
    print(new)

except:
    print('You did not enter a valid number.')

【讨论】:

    【解决方案2】:

    输入函数返回字符串值。所以你需要正确解析它

    num = raw_input('Enter a number and hit enter: ')
    
    if num.isdigit():
      if int(num) > 0:
          new = (int(num)**0.5)
          print(new)
    else:
        print('You did not enter a valid number.')
    

    【讨论】:

    • 那么,他的第二行就会失败。
    • 嗯,我试过了,它排除了那个错误。但是,我现在给出另一条错误消息: Traceback (last recent call last): File "/Users/username/Documents/Coding/squareroot.py", line 3, in if len(num) > 0 and num .isdigit(): TypeError: 'int' 类型的对象没有 len()
    • @ShivkumarKondi 我的回答和你的有什么区别?
    • @eyllanesc 我刚刚在第一次尝试中进行了解析并遇到了 isdigit 问题。你可以看到区别。我已经执行然后更新了我的代码。
    • 在原始问题中,该任务已经到位,我不为此而提出。我仍然看到你抄袭了我的答案。
    【解决方案3】:

    使用数学模块进行简单计算。 参考:Math module Documentation.

    import math
    num = raw_input('Enter a number and hit enter: ')
    
    if num.isdigit():
        num = float(num)
        new = math.sqrt(num)
        print(new)
    else:
        print('You did not enter a valid number.')
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-19
      • 1970-01-01
      • 1970-01-01
      • 2021-08-03
      • 2017-04-30
      • 1970-01-01
      • 2023-01-05
      • 2021-02-22
      相关资源
      最近更新 更多