简单Python函数Issu

2024-05-19 10:52:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图用Python运行的代码有什么问题?问题不是压痕):

def main():
    print("This program illustrates a chaotic function")
    x = eval(input("Enter a number between 0 and 1: "))
    for i in range(10):
    x = 3.9 * x * (1 - x)
    print(x)
main()

正如你所能想象的,自从我按照课本上的描述输入以来,这一直是相当混乱的。谢谢你的帮助!在


Tags: 代码numberinputmaindefevalfunctionthis
3条回答

需要缩进功能块

def main():
    print("This program illustrates a chaotic function")
    x = eval(input("Enter a number between 0 and 1: "))
    for i in range(10):
        x = 3.9 * x * (1 - x)
        print(x)

main()

另外,我将使用float代替eval

^{pr2}$

样品:

>>> 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: .2
0.624
0.9150336
0.303213732397
0.823973143043
0.565661470088
0.958185428249
0.156257842027
0.514181182445
0.974215686851
0.0979659811419

我认为你的问题是因为你在崇高的文本编辑器中运行它

尝试从命令行运行它

$ python yourscript.py

您将看到脚本正常运行。在

您得到的EOFError是由于当内置的input函数请求输入时,sublimitext没有向程序发送任何输入。在

您对代码做了两件错误的事情。
1号文件: 不能将eval与input方法一起使用,因为eval要求字符串作为输入,而使用input返回浮点值。
如果将float作为输入传递,则可以简单地运行程序。在

x = input("Enter a number between 0 and 1: "))

您需要使用原始输入(原始输入将返回字符串数据)

^{pr2}$

2:对于for循环,您需要提供缩进。在

相关问题 更多 >

    热门问题