python - 为什么我会收到 TypeError : can't multiply sequence by non-int of type 'float'

标签 python types python-3.x int

我正在尝试执行我在 John Zelle 的 Python 编程:计算机科学导论 中找到的这个示例 Python 脚本:

# File: chaos.py
# A simple program illustrating chatic behavior

def main():
    print("This program illustrates a chaotic function")
    x = input("Enter a number between 0 and 1: ")
    for i in range(10):
        x = 3.9 * x * (1 - x)
        print(x)

main()

...但出于某种原因,我不断收到此错误:

Traceback (most recent call last):
  File "C:\...\chaos.py", line 11, in <module>
    main()
  File "C:\...\chaos.py", line 8, in main
    x = 3.9 * x * (1 - x)
TypeError: can't multiply sequence by non-int of type 'float'

我不知道如何解决这个问题。有什么建议吗?

最佳答案

input() 默认返回一个字符串。在使用它之前,您必须将其转换为 float

这是 documentation (看起来你正在使用 Python 3.x)

If the prompt argument is present, it is written to standard output without a trailing newline. The function then reads a line from input, converts it to a string (stripping a trailing newline), and returns that. When EOF is read, EOFError is raised.

罪魁祸首是:

x = input("Enter a number between 0 and 1: ")

尝试

x = input("Enter a number between 0 and 1: ")
x = float(x)

关于python - 为什么我会收到 TypeError : can't multiply sequence by non-int of type 'float' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18389727/

相关文章:

python - 根据给定条件从数据框中过滤特定数据点

arrays - 使用嵌套的 decended 枚举案例作为父枚举案例

python - 如何获得有关 Python 意外 SIGABRT 的更多信息?

python - 在 Ubuntu 机器上安装 Python3.7,dist-packages 为空

python - 如何替换数据框中的索引

python - 稀疏矩阵是否有 numpy/scipy 点积,仅计算结果的对角线条目?

swift - Swift is Operator 的意外结果

python - 我应该在 Python 3.x 的 if 语句中使用 'in' 还是 'or' 来根据多个值检查变量?

python - python 中的 Dateutil 解析错误返回错误的值

c++ - 检查字符串的类型信息时出现奇怪的输出