Python Modules

Python Modules:

A file containing a set of functions which you want to include in your application is known as module.


Creating a Module:

To create a module just save the code you want for program with the file extension .py (dot py).

Example:

def wish(name):
  print("Hello " + name)

# Save this above code in file named "firstmodule" and extension .py


Using a Module:

Now we can call the module we just created by using the import statement.

Example:

import firstmodule
firstmodule.wish("Python")

Output:
Hello Python


Re-naming of a Module:

We can create an alias when you import a module by using the as keyword.

Example:

import firstmodule as fm
fm.wish("Python")

# In the above code we have changed the firstmodule name into fm, now we can use fm instead of firstmodule. 


Calling variables in a Module:

A module can contain functions and also variables of all types like (arrays, list, dictionaries, objects etc):

Example:

human = {
  "name""Lave",
  "age"45,
  "country""China"
}

# save this above code with file named "man" and extension .py

# Now import the module man.py

Example:

import man
a = man.human["name"]
print(a)

Output:
Lave


Import from a Module:

We can choose to import only particular parts from a module, by using the from keyword.

Example:

def wish(name):
  print("Hello " + name)


human = {
  "name""Lave",
  "age"45,
  "country""China"
}

save this above code with file named "man" and extension .py

Now import the part human from module man.py

Example:

from man import human
print (human["name"])

Output:
Lave


Built-in modules in python:

1.abs() function returns the absolute value of the specified number.

Example:

x = abs(-7.25)
print(x)

Output:
7.25


2.all() function returns True if all items are true, otherwise it returns false also if the iterable object is empty, the all() function also returns True.

Example:

list1 = [True, True, True]
x = all(list1)
print(x)

Output:
True


3.any() function returns True if any item in an iterable are true, otherwise it returns false also if the iterable object is empty, the any() function will return false.

Example:

list1 = [True, False, True]
x = any(list1)
print(x)

Output:
True


4.ascii() function returns a readable version of any object (Strings, Tuples, Lists, etc) and it will replace any non-ascii characters with escape characters.

Example:

x = ascii("My name is Femåle")
print(x)

Output:
My name is Fem\e5le


5.bin() function returns the binary version of a specified integer and result will always start with the prefix 0b.

Example:

x = bin(36)
print(x)

Output:
0b100100


6.bool() function returns the boolean value of a specified object.

The object will always return True, unless:
a. object is empty, like [], (), {}
b. object is False
c. object is 0
d. object is None

Example:

x = bool(1)
print(x)

Output:
True


7.bytearray() function returns a bytearray object.

Example:

x = bytearray(3)
print(x)

Output:
bytearray(b'\x00\x00\x00')


8.bytes() function returns a bytes object.

Example:

x = bytes(4)
print(x)

Output:
b'\x00\x00\x00'


9.callable() function returns true if the specified object is callable, otherwise it returns false.

Example:

def x():
  a = 4
print(callable(x))

Output:
True


10.chr() function returns the character that represents the specified uni-code.

Example:

x = chr(97)
print(x)

Output:
a


11.compile() function returns the specified source as a code object, ready to be executed.

Example:

x = compile('print(465)''test''eval')
exec(x)

Output:
465


12.complex() function returns a complex number by specifying a real number and an imaginary number.

Example:

x = complex(24)
print(x)

Output:
2+4j


13.delattr() function will delete the specified attribute from the specified object.

Example:

class Person:
  name = "Lave"
  age = 67
  country = "China"

delattr(Person, 'age')

Output:
# The Person object will no longer contain an "age" property.


14.divmod() function returns a tuple containing the quotient  and the remainder when argument1 (divident) is divided by argument2 (divisor).

Example:

x = divmod(52)
print(x)

Output:
(2, 1)


15.enumerate() function takes a collection (e.g. a list) and returns it as an enumerate object.

Example:

x = ('BMW''MERC''TOYA')
y = enumerate(x)
print(list(y))

Output:
[(0, 'BMW'), (1, 'MERC'), (2, 'TOYA')]


16.eval() function evaluates the specified expression, if the expression is a legal Python statement, it will be executed.

Example:

x = 'print(45)'
eval(x)

Output:
45


17.exec() function executes the specified Python code.

Example:

x = 'name = "Python"\nprint(name)'
exec(x)

Output:
Python


18.filter() function returns an iterator were the items are filtered through a function to test if the item is accepted or not.

Example:

num = [51217182432]

def func(x):
  if x < 18:
    return False
  else:
    return True

numbers filter(func, num)

for x in numbers:
  print(x)

Output:
18
24
32


19.float() function converts the specified value into a floating point number.

Example:

x = float(3)
print(x)

Output:
3.0


20.format() function formats a specified value into a specified format.

Example:

x = format(0.5'%')
print(x)

Output:
50.000000%


21.frozenset() function returns an unchangeable frozenset object which is like a set object.

Example:

mylist = ['BMW''BAW''BCW']
x = frozenset(mylist)
print(x)

Output:
frozenset({'BAW', 'BCW', 'BMW'})


22.getattr() function returns the value of the specified attribute from the specified object.

Example:

class Person:
  name = "Lave"
  age = 64
  country = "China"

x = getattr(Person, 'country')
print(x)

Output:
China


23.globals() function returns the global symbol table as a dictionary.

Example:

x = globals()
print(x)

Output:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
<_frozen_importlib_external.SourceFileLoader object at 0x02A8C2D0>, '__spec__':
None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,
'__file__': 'demo_ref_globals.py', '__cached__': None, 'x'_ {...}}


24.hasattr() function returns true if the specified object has the specified attribute, otherwise false.

Example:

class Person:
  name = "Lave"
  age = 64
  country = "China"

x = hasattr(Person, 'age')
print(x)

Output:
True


25.hex() function converts the number into a hexadecimal value,it returned string always starts with the prefix 0x.

Example:

x = hex(255)
print(x)

Output:
0xff


26.id() function returns a unique id for the specified object.

Example:

x = ('BMW''MERC''FORD')
y = id(x)
print(y)

Output:
65200987

# This value is the memory address of the object and will be different every time you run the program.


27.input() function allows user input.

Example:

x = input()
print('Hello, ' + x)

# The input() method will allow you to enter the value for (x) when you execute the program.


28.int() function converts the specified value into an integer number.

Example:

x = int(3.5)
print(x)

Output:
3 


29.isinstance() function returns true if the specified object is of the specified type, otherwise false.
If the type parameter is a tuple, then function will return true if the object is one of the types in the tuple.

Example:

x = isinstance(4int)
print(x)

Output:
True


30.issubclass() function returns true if the specified object is a subclass of the specified object, otherwise false.

Example:

class age:
  age = 89

class myObj(age):
  name = "Lava"
  ages = age

x = issubclass(myObj, age)

Output:
True


31.iter() function returns an iterator object.

Example:

x = iter(["BMW""MERC""FORD"])
print(next(x))
print(next(x))
print(next(x))

Output:
BMW
MERC
FORD


32.locals() function returns the local symbol table as a dictionary.

Example:

x = locals()
print(x)

Output:
{'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__':
<_frozen_importlib_external.SourceFileLoader object at 0x03A8C2D0>, '__spec__':
None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>,

'__file__': 'demo_ref_locals.py', '__cached__': None, 'x'_ {...}}


33.map() function executes a specified function for each item in a iterable. The item is sent to the function as a parameter.

Example:

def func(n):
  return len(n)

x = map(func, ("BMW""MERC""FORD"))

Output:
<map object at 0x056D44F0>
['5', '6', '6']


34.memoryview() function returns a memory view object from a specified object.

Example:

x = memoryview(b"Hello")

print(x)

#return the Unicode of the first character 
print(x[0])

#return the Unicode of the second character 
print(x[1])

Output:
<memory at 0x03348FA0>
79
120


35.max() function returns the item with the highest value or the item with the highest value in an iterable. If the values are strings, an alphabetically comparison is done.

Example:

x = max(510)
print(x)

Output:
10 


36.min() function returns the item with the lowest value, or the item with the lowest value in an iterable.

Example:

x = min(510)
print(x)
Output:



37.object() function returns an empty object.

Example:

x = object()
print(dir(x))

Output:
['__class__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__',
 '__ge__', '__getattribute__', '__gt__', '__hash__', '__init__',
 '__init_subclass__', '__le__', '__lt__', '__ne__', '__new__',
 '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__',
 '__str__', '__subclasshook__']


38.oct() function converts an integer into an octal string.Octal strings in Python are prefixed with 0o.

Example:

x = oct(12)
print(x)

Output:
0o14


39.next() function returns the next item in an iterator.

Example:

mylist = iter(['BMW''MERC''FORD'])
x = next(mylist)
print(x)
x = next(mylist)
print(x)
x = next(mylist)
print(x)

Output:
BMW
MERC
FORD


40.open() function opens a file, and returns it as a file object.

Example:

f = open("testfile.txt""r")
print(f.read())

Output:
Hello! Welcome to textfile.txt
This file is for testing purposes.
Good Luck!


41.ord() function returns the number representing the unicode code of a specified character.

Example:

x = ord("h")
print(x)

Output:
104 


42.pow() function returns the value of x to the power of y (xy).

Example:

x = pow(43)
print(x)

Output:
64 


43.range() function returns a sequence of numbers, starting from 0 by default, and increments by 1 (by default), and ends at a specified number.

Example:

x = range(5)
for n in x:
  print(n)

Output:
0
1
2
4


44.reversed() function returns a reversed iterator object.

Example:

a = ["a""b""c""d"]
b = reversed(a)
for x in b:
  print(x)

Output:
d
c
b
a


45.round() function returns a floating point number that is a rounded version of the specified number, with the specified number of decimals.

Example:

x = round(5.765432)
print(x)

Output:
5.77  


46.slice() function returns a slice object.

Example:

a = ("a""b""c""d""e""f")
x = slice(2)
print(a[x])

Output:
("a""b")


47.sorted() function returns a sorted list of the specified iterable object.
You can specify ascending or descending order. Strings are sorted alphabetically, and numbers are sorted numerically.

Example:

a = (132)
x = sorted(a)
print(x)

Output:
[1, 2, 3]

Example 2:

a = (132)
x = sorted(a, reverse=True)
print(x)

Output:
[3, 21]

#Note: if reverse=False then ascending,if reverse=True then descending.

Example 3:

a = ("b""g""a""d""f""c""h""e")
x = sorted(a)
print(x)

Output:
['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h']


48.@staticmethod() it convert method into static method.


49.str() fu=nction converts the specified value into a string.

Example:

x = str(9.8)
print(x)

Output:
9.8 # now,this is string


49.int() function converts the specified value into a integer.

Example:

x = int('a')

print(x)

Output:
a # now,this is treated as int.


50.sum() function returns a number which is the sum of all items.

Example:

a = (12345)
x = sum(a, 6)
print(x)

Output:
21 # sum( 1+2+3+4+5+6 = 21 )



51.super() function is used to give access to methods and properties of a parent to base class.

Example:

class Parent:
  def __init__(self, txt):
    self.message = txt

  def printmessage(self):
    print(self.message)

class Child(Parent):
  def __init__(self, txt):
    super().__init__(txt)

x = Child("Hello, and welcome!")
x.printmessage() #calling of function


Output:
Hello, and welcome!


51.type() function returns the type of the specified object.

Example:

a = ('BMW''MERC''FORD')
b = "Python"
c = 99

x = type(a)
y = type(b)
z = type(c)

Output:
<class 'tuple'>
<class 'str'>
<class 'int'>


52.zip() function returns a zip object, which is an iterator of tuples where the first item in each passed iterator is paired together, and then the second item in each passed iterator are paired together etc.

Example:

a = ("Billy""Cadem""Popye")
b = ("Jen""Chis""Mole")

x = zip(a, b)

Output:
(('Billy', 'Jen'), ('Cadem', 'Chis'), ('Popye', 'Mole'))


Post a Comment

0 Comments