我正在尝试执行我在 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/