0

I wanted to make a simple square root calculator.

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

It doesn't seem as if I have done anything wrong, however, when I attempt to run the program and after I have input a number, I am confronted with the following error message:

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 
4

3 回答 3

3

您可以使用此解决方案。这里的 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.')
于 2017-03-21T07:02:30.183 回答
0

使用数学模块进行简单计算。参考:数学模块文档。

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.')
于 2017-03-21T07:50:39.497 回答
0

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

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.')
于 2017-03-21T06:34:29.863 回答