【问题标题】:Why am I getting TypeError: can't multiply sequence by non-int of type 'float'为什么我得到 TypeError: can't multiply sequence by non-int of type 'float'
【发布时间】:2013-08-25 17:33:36
【问题描述】:

我正在尝试执行我在 John Zelle 的 Python Programming: An Introduction to Computer Science 中找到的这个 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'

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

【问题讨论】:

  • 你用的是什么版本的python?这在 2.7 中完美运行。它甚至可以在我输入真正的 jank 数字时工作......好吧,我得到它来做错误,但只有在我尝试输入一个字符串之后......当它说“输入一个介于 0 和 1 之间的数字:”时你在打字吗?

标签: python types python-3.x int


【解决方案1】:

input 总是返回一个字符串:

>>> type(input(":"))
:a
<class 'str'>
>>> type(input(":"))
:1
<class 'str'>
>>>

将输入转换为浮点数:

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

【讨论】:

  • 不是整数。它介于 0 和 1 之间。
  • @user2357112 - 很好。不知道我是怎么错过的。
  • &gt;&gt;&gt; x = input() 3 &gt;&gt;&gt; x 3 &gt;&gt;&gt; type(x) &lt;type 'int'&gt; input() 返回你输入的任何类型
  • @TehTris - OP 使用的是 Python 3.x。因此,我的代码适用于 3.x。
  • @iCodez 然后我拿走了那个-1 :),当我问的时候,OP 从来没有回答过
【解决方案2】:

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

这是documentation(看起来您使用的是 Python 3.x)

如果提示参数存在,则将其写入标准输出,不带尾随换行符。然后该函数从输入中读取一行,将其转换为字符串(去除尾随的换行符),然后返回。读取 EOF 时,会引发 EOFError。

罪魁祸首是:

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

试试

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-27
    • 2016-01-27
    • 2021-01-06
    • 2011-04-02
    • 2020-05-10
    • 2022-11-18
    • 2021-10-01
    相关资源
    最近更新 更多