【问题标题】:typeerror: can't multiply sequence by non-int of type "floattypeerror:不能将序列乘以“float”类型的非整数
【发布时间】:2012-10-09 03:47:46
【问题描述】:

我是 python 的新手(和一般的编程),我正在学习以下示例 Python编程: 计算机科学导论 John M. Zelle 博士 版本 1.0rc2 2002 年秋季 显然这有点过时了,我使用的是 Python 3.3 我输入的练习与书中显示的完全一样(在打印语句周围添加 ()),但我一直遇到错误。这是我尝试运行程序时输入的内容和结果的副本。我做错了什么?

>>> 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'
>>> 

【问题讨论】:

  • 好吧,即使你得到了这个和其他例子的代码,这本书也可能充满了陈旧和破败的做事方式。买一本更好、更新的书,这样你就不会在习语、语言特性、图书馆等方面落后其他人十年。

标签: python


【解决方案1】:

使用x=float(input ("Enter a number between 0 and 1:")) 作为input() 在python 3k 中返回一个字符串而不是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

【讨论】:

    猜你喜欢
    • 2010-12-30
    • 1970-01-01
    • 2017-02-04
    • 2019-03-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-09
    • 1970-01-01
    相关资源
    最近更新 更多