python - 为什么我显示 "TypeError: a float is required"?

标签 python

我的主要问题是显示此错误:

TypeError: a float is required

我没有尝试太多,因为我真的不知道自己在做什么,而且对编码等方面还很陌生,所以我希望能就此事提供一些耐心的建议。

from math import sqrt

n = raw_input('Type number here: ')

def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%d square rooted is %d." % (n, square_rooted)
  return square_rooted

square_root(n)

我希望能够输入一个数字并显示它的平方根。

最佳答案

代码的一些问题/修复

  • 您需要转换从 raw_input 获得的字符串

  • 要显示 float ,请使用 %f 字符串格式

因此代码将更改为

from math import sqrt
#Convert string obtained from raw_input to float
n = float(raw_input('Type number here: '))
def square_root(n):
  """Returns the square root of a number."""
  square_rooted = sqrt(n)
  print "%f square rooted is %f." % (n, square_rooted)
  return square_rooted

square_root(n)

输出将如下所示

Type number here: 4.5
4.500000 square rooted is 2.121320.

关于python - 为什么我显示 "TypeError: a float is required"?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56380520/

相关文章:

python - 使用带有 Pmw 模块的 pyinstaller 创建 python 3 exe

python - 计算非零值的平均值

python - Pandas 分组 : TOP 3 values in each group and store in DataFrame

python - 使用 Python 连接到 SQL Server 的 AWS Lambda 函数

python - 在python中计算单词相似度分数

python - 如何使用 python 中的分页从 API 创建有效的 json 文件?

python - dict python的URL查询参数

python - Raspberry Pi 3B 和 RFID RC522 - Python TypeError

python - sys._current_frames() 中的孤立堆栈跟踪

python - 一维列表索引 python : enhance MaskableList