导入影响循环的`random`

时间:2019-07-01 13:35:59

标签: python random import

我想用for循环打印数字1到10,但是import random正在影响我的for循环,并且循环运行了两次。这是screenshot of my editor。输出如下所示。你能告诉我为什么会这样吗?

import random
for i in range(1,10):
    print(i)

我的输出:

1
2
3
4
5
6
7
8
9
1
2
3
4
5
6
7
8
9

2 个答案:

答案 0 :(得分:1)

这将永远不会发生。

确保您正在运行最新版本的程序,并确保没有将相同的代码粘贴到同一文件中的其他位置。例如确保没有预编译版本。 (例如,更改文件名,然后重试)。

更新:

根据matthias的评论,如果将文件另存为random.py,则可以复制以上结果。

# if you save the code below as random.py
import random
for i in range(1,10):
    print(i)



# your output could be reproduced as below.
>>> python random.py

 1
 2
 3
 4
 5
 6
 7
 8
 9
 1
 2
 3
 4
 5
 6
 7
 8
 9

解决方案:更改文件名,或者如果您必须导入文件,请确保在您random.py的for循环之前包含编码if __name__ == "__main__"

答案 1 :(得分:-2)

11我看不到任何问题,我做了示例,它很完美。

我的输出: 1个 2 3 4 5 6 7 8 9

可能是您两次调用了文件?这是我找到的唯一请求。