0
0
Pythonprogramming~5 mins

Import statement behavior in Python

Choose your learning style9 modes available
Introduction

We use import statements to bring code from other files or libraries into our program so we can use it without rewriting it.

When you want to use functions or classes written in another file.
When you want to use built-in Python tools like math or random.
When you want to organize your code into smaller parts and use them together.
When you want to reuse code someone else wrote by importing their module.
When you want to keep your main program clean and simple by importing helpers.
Syntax
Python
import module_name

# or
from module_name import specific_name

# or
from module_name import *

import module_name brings the whole module so you use module_name.item.

from module_name import specific_name brings only that item directly.

Examples
This imports the whole math module and uses the sqrt function with math.sqrt.
Python
import math
print(math.sqrt(16))
This imports only the sqrt function from math, so you can use it directly.
Python
from math import sqrt
print(sqrt(25))
This imports all names from math, so you can use sin without prefix.
Python
from math import *
print(sin(0))
Sample Program

This program imports the math module, calculates the square root of 9, and prints the result.

Python
import math

number = 9
root = math.sqrt(number)
print(f"The square root of {number} is {root}")
OutputSuccess
Important Notes

When you import a module, Python runs the code inside it once and remembers it.

If you import the same module again, Python does not run it again but reuses it.

Use from module import * carefully because it can overwrite names in your program.

Summary

Import statements let you use code from other files or libraries.

You can import the whole module or just parts of it.

Importing runs the module code once and reuses it on later imports.