for循环中未使用的变量

Jam*_*OLA 6 python python-3.x

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()
Run Code Online (Sandbox Code Playgroud)

当我在我的 Visual Studio Code 桌面应用程序中键入上面的程序时,它返回问题通知:

W0612: Unused variable 'i'
Run Code Online (Sandbox Code Playgroud)

但是当我使用内置的 python '空闲'解释器运行相同的程序时,程序运行得很好。

sha*_*eed 13

因为您没有i在 for 循环中使用 ' '。将其更改为“ _”,如下所示

def main():
    print ("This program illustrates a chaotic function")
    x = (float(input("Enter a number between 0 and 1: ")))
    for _ in range(10):
        x = 3.9 * x * (1-x)
        print (x)
Run Code Online (Sandbox Code Playgroud)


Joe*_*don 5

这只是您的 IDE 提醒您您定义了一个变量i,而您没有使用该变量。

Python 不关心这个,因为代码运行良好,所以解释器不会抛出任何错误,因为没有错误!

没有什么可说的了,Visual Studio 只是在您打算i在某些时候使用但忘记时通知您。

这是Python的惯例,当你只是用它作为一个占位符使用下划线作为变量名,所以我认为Visual Studio中会认识到这一点,并不会通知你,如果你使用_的不是i