Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this python code running twice [duplicate]

Here is the code

import random

print("Hello", end="")
print("twice")

and a screenshot of the code

enter image description here

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.

like image 818
Knight Avatar asked Nov 28 '17 12:11

Knight


People also ask

Why is my random Python script printing twice when imported?

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

Why does the i loop execute twice in a row?

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.

What happens when you rename a python script with random?

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.


1 Answers

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.
like image 98
Mike Scotty Avatar answered Oct 01 '22 02:10

Mike Scotty