Please ignore secret bonuses. Secret tests do NOT award bonus. Max hw grade is 30+2 bonus efficiency

Do you need help?

from x import y || import x

G
GokhanCeylan (1970 points)
9 22 27
in Programming in Python by (2.0k points)
closed by
If we use "import x", does it mean we are ready to use any method or functions from library x?

But if we just use "from x import y", does it also mean we could use only y function from library x?
184 views
closed

1 Answer

Best answer
s
sen_596 (5800 points)
0 0 6
by (5.8k points)
selected by

If you write import x, you have imported all the module x and you can use functions y only as x.y().

By writing from x import y, you are importing only the function y of the module x in your program and you can access it by simply writing y(). The same is valid when you write from x import* (the asterisk allows you to import all the functions from a certain library).

Let's take an example: We want to calculate the square root of a number.

1st option:

import math

print(math.sqrt(x))

2nd option:

from math import sqrt

print(sqrt(x))

3rd option:

from math import*

print(sqrt(x))

As you see, you only need to specify the library on the first option. Anyways, you should choose which method to use depending on the type of code you want to write. It's not the smartest move to import all the module when you need only a function and vice versa it's not a good idea to import different functions n-times if you need several ones.

P.s: By the way, your question reminded me of an issue that I've noticed at the beginning of the course when programming the GuessTheNumber program, in which the user had to guess a random number. When importing the random library with import random, Python used to use the same numbers to guess, but by switching to from random import randint, i managed to solve the problem. Can anyone give me an explanation of this strange behavior?