Here is the code
import random
print("Hello", end="")
print("twice")
and a screenshot of the code
When I execute this code it for some reason is running twice. The problem seems to be from the import random statement, because if I either remove that statement or import some other module it works fine.
What could be the reason for this, should I reinstall Python on my system.
your python script is named random.py so when you import random it import itself, in python when you import module it will run it. therefor you get print twice. rename your script or remove the import
It appears the i loop executes twice in a row because it doesn't. The inner j loop executes but range returns an array of values from i - 1 to 0, with the upper limit of 0 being non-inclusive. On the first iteration of i, that would be range (1 - 1, 0, -1), which will return no values for the j loop. This is the expected behavior.
This leads to the script executing the same statements twice (and also leads to other ugly errors if you tried and import something from random, like from random import randrange .) Renaming the script leads to normal behavior. Because your scripts is called random.py, so when you import random you are executing your script as well.
There's nothing wrong with python.
The reason is simple:
Your module is importing itself (because it is also named random
) - this has to do with the lookup mechanics of python. python will try to import from your root folder first, before modules from pythonpath are imported.
From the docs:
When a module named spam is imported, the interpreter first searches for a built-in module with that name. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:
- The directory containing the input script (or the current directory when no file is specified).
- PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).
- The installation-dependent default.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With