我正在尝试执行这个示例Python脚本,我在John ielle的 Python Programming:An Introduction to Computer Science 中找到了这个脚本:
# 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'
我不知道如何解决这个问题。有什么建议吗?
答案 0 :(得分:4)
input()
返回一个字符串。在使用之前,您必须将其强制转换为float
。
这是documentation(看起来你使用的是Python 3.x)
如果存在prompt参数,则将其写入标准输出而不带尾随换行符。然后,该函数从输入中读取一行,将其转换为字符串(剥离尾部换行符),然后返回该行。读取EOF时,会引发EOFError。
罪魁祸首是:
x = input("Enter a number between 0 and 1: ")
尝试
x = input("Enter a number between 0 and 1: ")
x = float(x)
答案 1 :(得分:3)
input
始终返回一个字符串:
>>> type(input(":"))
:a
<class 'str'>
>>> type(input(":"))
:1
<class 'str'>
>>>
将输入转换为float:
x = float(input("Enter a number between 0 and 1: "))