Introduction
Importing specific items lets you bring only the parts you need from a module. This keeps your code clean and uses less memory.
Jump into concepts and practice - no test required
Importing specific items lets you bring only the parts you need from a module. This keeps your code clean and uses less memory.
from module_name import item1, item2, ...
sqrt function from the math module.from math import sqrt
date and time classes from the datetime module.from datetime import date, time
randint but renames it to random_int for easier use.from random import randint as random_int
This program imports sqrt and pi from the math module. It calculates the square root of 16 and then uses that as the radius to find the area of a circle.
from math import sqrt, pi number = 16 root = sqrt(number) circle_area = pi * (root ** 2) print(f"Square root of {number} is {root}") print(f"Area of circle with radius {root} is {circle_area}")
Importing specific items helps avoid loading the whole module, which can save memory.
You can rename imported items using as to avoid name clashes or for convenience.
If you import many items, consider if importing the whole module might be clearer.
Use from module import item to bring in only what you need.
This keeps your code clean and can improve performance.
You can import multiple items and rename them for clarity.
from math import sqrt do in Python?from module import item imports only the specified item from the module.sqrt function is imported from the math module, not the whole module.sqrt function from the math module. -> Option Bchoice and shuffle functions from the random module?from module import item1, item2 separated by commas.from random import choice, shuffle.from math import sqrt print(sqrt(16))
sqrt function returns the square root of the number, so sqrt(16) returns 4.0.sqrt was imported directly, calling sqrt(16) works without prefix.from os import path
print(os.path.exists('file.txt'))path from os, not the whole os module.os.path.existsos.path.exists, but os is not defined, causing a NameError.os is not imported -> Option Adatetime and timedelta classes from the datetime module but rename timedelta to td for clarity. Which is the correct import statement?as, e.g., timedelta as td.datetime and renames timedelta to td using from datetime import datetime, timedelta as td.