Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import as statement working differently for different modules?

Tags:

python

import

I am learning Python, and right now I am learning about the import statements in Python. I was testing out some code, and I came across something unusual. Here is the code I was testing.

from math import pow as power
import random as x

print(pow(2, 3))
print(power(2, 3))
print(x.randint(0, 5))
print(random.randint(0, 5))

I learned that in Python, you can reassign the names of modules using as, so I reassigned pow to power. I expected both pow(2, 3) and power(2, 3) to output the exact same stuff because all I did was change the name. However, pow(2, 3) outputs 8, which is an integer, while power(2, 3) outputs 8.0, which is a float. Why is that?

Furthermore, I imported the random module as well, and set its name to be x. In the case of the pow and power, both the old name, pow, and the new name, power, worked. But with this random module, only the new name, x, works, and the old name, random, doesn't work. print(x.randint(0, 5)) works, but random.randint(0, 5) doesn't work. Why is this so?

Can anyone please explain to a Python newbie such as myself why my code is not working the way I expect it to? I am using Python version 3.62, if that helps.

like image 727
parrot15 Avatar asked Mar 18 '26 09:03

parrot15


1 Answers

That's because when you import pow from math as power and then you call pow, the pow you are calling is a built-in function, not the pow from the math module.

For random there is no built-in function in python so you only import the x one.

The pow built-in function documentation

like image 106
Martin Alonso Avatar answered Mar 19 '26 22:03

Martin Alonso



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!