1

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

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

4

2 回答 2

4

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

这是文档(看起来您使用的是 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)
于 2013-08-22T19:59:15.950 回答
3

input总是返回一个字符串:

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

将输入转换为浮点数:

x = float(input("Enter a number between 0 and 1: "))
于 2013-08-22T19:59:09.817 回答