Python 平方根计算器错误

Python Square Root Calculator Error

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

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 

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

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.')

您可以使用此解决方案。这里的 try 和 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.')

使用数学模块进行简单的计算。 参考: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.')