1

我是 python 的新手(和一般的编程),我正在遵循 Python Programming: An Introduction to Computer Science John M. Zelle, Ph.D. 中的示例。版本 1.0rc2 2002 年秋季 显然这有点过时了,我使用的是 Python 3.3,我正在输入练习中的内容,完全按照书中的说明(在 print 语句周围添加 ()),但我一直遇到错误。这是我尝试运行程序时输入的内容和结果的副本。我究竟做错了什么?

>>> 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()
This program illustrates a chaotic function.
Enter a number between 0 and 1:1
Traceback (most recent call last):
  File "<pyshell#12>", line 1, in <module>
    main()
  File "<pyshell#11>", line 5, in main
    x= 3.9*x*(1-x)
TypeError: can't multiply sequence by non-int of type 'float'
>>> 
4

1 回答 1

4

使用x=float(input ("Enter a number between 0 and 1:"))asinput()在 python 3k 中返回一个字符串 not float

>>> def main():
...     print ("This program illustrates a chaotic function.")
...     x=float(input ("Enter a number between 0 and 1:"))
...     for i in range(10):
...         x= 3.9*x*(1-x)
...         print (x)
... 
>>> main()
This program illustrates a chaotic function.
Enter a number between 0 and 1:.45
0.96525
0.13081550625
0.443440957341
0.962524191305
0.140678352587
0.47146301943
0.971823998886
0.106790244894
0.372005745109
0.911108135788
于 2012-10-18T16:03:41.440 回答