less than 1 minute read

Python modules can get access to code from another module by importing the file/function using the keyword import. You can do it in different ways:

  • Example - Using the original module name:

  • Syntax - import [module]

import random
print(random.randint(0, 5))

# Output - Alt number:
3
  • Example - Import a specific function from a specific module:

  • Syntax - from [module] import[function].

from random import randint
print(randint(0, 5))

# Output - Alt number:
2
  • Example- Using an alias name

  • Syntax - import [module] as [alias]

import random as r
print(r.randint(0, 5))

# Output - Alt number:
5
  • Example - imports everything present in the module:

  • Syntax - from [module] import *

from random import *
print(randint(0, 5))

# Output - Alt number:
44

Reference

Import module - Examples