Python built-in basic functions bytes([97])
b'a'
_____________________________________
abs() ____
returns absolute value of integer
abs(-2)
2
_____________________________________
____
all()
callable()
return True if all items of iterable are ture
print(all([0,1,3,8,0])) # False returns true if specified object is callable
print(all([1,3,8])) # True ll = [1,2]
print(all([True,True])) # True callable(ll)
print(all([True,False])) # False False
_____________________________________ _____________________________________
____ ____
any() chr()
returns true if any item in iterable is true returns character value of integer
print(any([0,1,3,8,0])) # True chr(97)
print(any([0,0])) # False 'a'
print(any([True,True])) # True _____________________________________
print(any([False,False])) # False ____
_____________________________________
____ classmethod(function)
returns a classmethod for the given function
ascii() classmethod() is considered un-Pythonic so in
returns readable version of any object newer Python versions, you can use the
ascii("ab") @classmethod decorator for classmethod
"'ab'" definition.
_____________________________________ class Person:
____ age = 25
bin()
def printAge(cls):
returns binary version of integer
print('The age is:', [Link])
bin(32)
'0b100000'
_____________________________________ # create printAge class method
____ [Link] =
classmethod([Link])
bool()
returns boolean value of object [Link]()
print(bool([])) # False The age is: 25
print(bool([2,3])) # True _____________________________________
_____________________________________ ____
____
compile(source,filemane,mode)
bytearray()
returns a python code object from the source
returns byte array file
bytearray('97',encoding='utf-8') codeInString = 'a = 5\nb=6\nmul=a*b\
bytearray(b'97') nprint("mul =",mul)'
_____________________________________ codeObject = compile(codeInString,
____ 'sumstring', 'exec')
bytes() exec(codeObject)
returns immutable byte object mul = 30
_____________________________________ [1, 2, 3]))
____ print('numbers3 =',numbers3)
numbers = {'x': 5, 'y': 0}
complex() <class 'dict'>
returns complex number numbers3 = {'x': 1, 'y': 2, 'z': 3}
complex(2,4) _____________________________________
(2+4j) ____
_____________________________________
____ dir()
returns all properties and methds ( without the
value) of specified object
dir(Coordinate)
delattr() _____________________________________
deletes specified attribute from the object ____
class Coordinate:
x = 10
y = -5
z = 0
divmod(divident,divisor)
point1 = Coordinate() returns tuple that contains quotient and remainder
abc = divmod(100,5)
print('x = ',point1.x) print(abc)
print('y = ',point1.y) (20, 0)
print('z = ',point1.z) _____________________________________
____
delattr(Coordinate, 'z')
enumerate(iterable , start)
print('--After deleting z adds a counter to iterable object and returns it
attribute--') languages = ['Python', 'Java',
print('x = ',point1.x) 'JavaScript']
print('y = ',point1.y)
enumerate_prime =
# Raises Error enumerate(languages)
print('z = ',point1.z)
x = 10 print(list(enumerate_prime))
y = -5 [(0, 'Python'), (1, 'Java'), (2,
z = 0 'JavaScript')]
--After deleting z attribute-- _____________________________________
x = 10 ____
y = -5
------------------------------------- eval()
---- evaluates the specified python expression and
AttributeError
executes if its correct python code
number = 9
AttributeError: 'Coordinate' object square_number = eval('number *
has no attribute 'z' number')
_____________________________________ print(square_number) # 81
____ _____________________________________
____
dict()
creates a dictionary exec()
numbers = dict(x=5, y=0) executes a dynamically created program, which is
print('numbers =', numbers)
either a string or a code object.
print(type(numbers))
program = 'a = 5\nb=10\nprint("Sum
=", a+b)'
# zip() creates an iterable in Python exec(program)
3 Sum = 15
numbers3 = dict(zip(['x', 'y', 'z'],
_____________________________________ 1100
____ # integer
print(format(1234, "4,d")) # 1,234
filter() # float number
extracts element from the iterable where the print(format(123.4567,"^-09.3f"))
fuction returns TRUE #0123.4570
_____________________________________
numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9,
____
10]
frozenset()
# returns True if number is even
def check_even(number): returns an immutable frozen set from given
if number % 2 == 0: iterable
return True # tuple of vowels
vowels = ('a', 'e', 'i', 'o', 'u')
return False
fSet = frozenset(vowels)
# Extract elements from the numbers print('The frozen set is:', fSet)
list for which check_even() returns print('The empty frozen set is:',
True frozenset())
even_numbers_iterator =
filter(check_even, numbers) # frozensets are immutable
[Link]('v')
print(list(even_numbers_iterator)) The frozen set is: frozenset({'i',
[2, 4, 6, 8, 10] 'a', 'e', 'o', 'u'})
_____________________________________ The empty frozen set is: frozenset()
____ -------------------------------------
----
float() AttributeError
_____________________________________
returns a floating point number for given number
____
or string
print(float(10)) # 10.0
print(float(11.22)) # 11.22
print(float("-13.33")) # -
13.33
print(float(" -24.45\n")) # -24.45
# print(float("abc")) #string float getattr(object,attribute,default)
error returns value of specified attribute
print(float("nan")) # nan class Student:
print(float("NaN")) # nan marks = 88
print(float("inf")) # inf name = 'Sheeran'
print(float("InF")) # inf
print(float("InFiNiTy"))# inf person = Student()
print(float("infinity"))# inf
_____________________________________ name = getattr(person, 'name')
____ print(name)
format() marks = getattr(person, 'marks')
formats a specified value into a specified format print(marks)
# integer Sheeran
print(format(123, "d")) # 123 88
_____________________________________
# float arguments ____
print(format(123.45678,"f”)) #
123.45678 globals
# binary format returns global symbol table as a dictionary
print(format(12, "b")) # # globals()
_____________________________________ int(value)
____
convets to integer
hasattr(object,attribute) int('123')
_____________________________________
returns true if an object has the given named ____
attribute and false if it does not.
class Person: isinstance(object , classinfo)
age = 23 returns True if the object is an instance or subclass
name = "Adam"
of a class or any element of the tuple
class Foo:
person = Person() a = 5
print("Person's age:", fooInstance = Foo()
hasattr(person, "age"))
print("Person's salary:", print(isinstance(fooInstance, Foo))
hasattr(person, "salary")) #True
Person's age: True print(isinstance(fooInstance,
Person's salary: False (Foo)))#True
_____________________________________ _____________________________________
____ ____
hash(object) issubclass(object , classinfo)
returns hash value of object returns True if the object is a subclass of a class or
a = 'smit'
hash(a)
any element of the tuple
class Polygon:
8512339495237734125
def __init__(polygonType):
_____________________________________
print('Polygon is a ',
____
polygonType)
help(object)
class Triangle(Polygon):
The help() method calls the built-in Python help def __init__(self):
system.
# help(print) Polygon.__init__('triangle')
_____________________________________
____ print(issubclass(Triangle, Polygon))
#True
hex(object) print(issubclass(Triangle, list))
converts inbterger value to hexadecimal value #False
hex(22) print(issubclass(Triangle,
'0x16' (list,Polygon)))
_____________________________________ #True
____ print(issubclass(Polygon, (list,
Polygon)))
id(object) # True
_____________________________________
returns identity of object
____
a = 6
id(5)
4519963504
_____________________________________
____
_____________________________________
input('') ____
takes input from user
x = input('enter value for x')
iter(object,sentinel)
_____________________________________ returns iterator from given object
____ phones = ['apple', 'samsung',
'oneplus']
phones_iter = iter(phones) map( function , iterable , ~~*iterable~~ )
o It applies a given function to each item of given
print(next(phones_iter))
print(next(phones_iter)) iterable and returns an iterable.
apple o The item is sent to fucntion as parameter
samsung o we can pass more than one iterable
_____________________________________ def calculateSquare(n):
____ return n*n
numbers = (1, 2, 3, 4)
len(object) result = map(calculateSquare,
return number of items in given object numbers)
ll = [ 's' , 'm' , 'i' , 't'] print(result)
len(ll)
4 # converting map object to set
_____________________________________ numbersSquare = set(result)
____ print(numbersSquare)
<map object at 0x112cfa760>
list(iterable) {16, 1, 4, 9}
_____________________________________
returns a list of the given iterable
____
# empty list
print(list()) max(iterable ,~~*iterable , key , value~~)
# vowel string Returns the largest item in the iterable
vowel_string = 'aeiou' • key - key function (like a lambda function
print(list(vowel_string))
can be passed and comparison is made
based on its return value )
# vowel tuple
vowel_tuple = ('a', 'e', 'i', 'o', • default - default value if iterable is empty
'u') square = {2: 4, -3: 9, -1: 1, -2: 4}
print(list(vowel_tuple))
# the largest key
# vowel set key1 = max(square)
vowel_set = {'a', 'e', 'i', 'o', 'u'} print("The largest key:", key1) #
print(list(vowel_set)) 2
# vowel dictionary # the key whose value is the largest
vowel_dictionary = {'a': 1, 'e': 2, key2 = max(square, key = lambda k:
'i': 3, 'o':4, 'u':5} square[k])
print(list(vowel_dictionary)) print("The key with the largest
[] value:", key2) # -3
['a', 'e', 'i', 'o', 'u']
['a', 'e', 'i', 'o', 'u'] # getting the largest value
['i', 'a', 'e', 'o', 'u'] print("The largest value:",
['a', 'e', 'i', 'o', 'u'] square[key2]) # 9
_____________________________________ _____________________________________
____ ____
locals() min( iterable ,~~*iterable , key , value~~ )
Returns the smallest item in iterable
The locals() method returns a dictionary with all result = min(4, -5, 23, 5)
the local variables and symbols for the current print("The minimum number is:",
program. result)
# locals() The minimum number is: -5
_____________________________________ _____________________________________
____ ____
# the next element is the first
element
marks_1 = next(iterator_marks)
print(marks_1)
# find the next element which is the
memoryview( object ) second element
marks_2 = next(iterator_marks).
Returns a memory view object of the given #65
argument. print(marks_2) #72
#random bytearray _____________________________________
random_byte_array = bytearray('ABC', ____
'utf-8')
open( file,mode=' ',buffering=
mv = memoryview(random_byte_array) 1,encoding=None,errors=None)
o Opens a file andf returns it as a file object
# access memory view's zeroth index
print(mv[0])
o file path and name of file
mode = 'r' , 'w' , 'x' , 'a' , 't' , 'b' , '+'
# create byte from memory view f = open("[Link]") # # opens
print(bytes(mv[0:2])) [Link] file of the current
directory
# create list from memory view f = open("C:/Python33/[Link]") #
print(list(mv[0:3])) # specifying the full path
65 -------------------------------------
b'AB' ----
[65, 66, 67] FileNotFoundError
_____________________________________
object() ____
o Returns a featureless object which is base for pow(x,y,z)
all classes Retuen x^y
o you cannot add new properties or methods to
If third parameter is given it returns x^y mod z
this object
print(pow(2, 2)) # returns 2^2 #
test = object()
4
print(type(test))
print(pow(-2, 2)) # returns -2^2 #
<class 'object'>
4
_____________________________________
print(pow(2, -2)) # returns 1/2^2
____
#0.25
print(pow(-2, -2))# returns -1/-2^2
oct( ch )
#0.25
Returns an integer representing Unicode _____________________________________
Character. ____
character = 'P'
print(object , ~~sep=' ' ,end='' ,file=file ,
unicode_char = ord(character)
print(unicode_char) flush=Fasle ~~)
80 o prints givewn object to stdout
_____________________________________ o sep : objects separator.
____ o if file is given it write to that file.
next( iterator , default )
o flush : if set true stream is forcibly flushed.
returns next item in iterator returns default if a = 5
iterator is exhausted print("a =", a, sep='x0x', end='')
marks = [65, 71, 68, 74, 61] a =x0x5
_____________________________________
____
iterator_marks = iter(marks) #
convert list to iterator
Range(start = 0,stop = , step = 1) Getting name
Adam
Retuens sequence
Setting name to John
r1 = range(4)
Deleting name
print(r1) # range(0, 4)
Instead of using property(), you can use the Python
r2 = range(2, 5) decorator @property to assign the getter, setter,
print(list(r2)) # [2, 3, 4] and deleter.
class Person:
r3 = range(-2, 4) def __init__(self, name):
print(list(r3)) # [-2, -1, 0, 1, self._name = name
2, 3]
@property
r4 = range(4, 2) # returns empty def name(self):
print(list(r4)) # [] print('Getting name')
return self._name
r5 = range(-4)
print(list(r5)) # [] @[Link]
range(0, 4) def name(self, value):
[2, 3, 4] print('Setting name to ' +
[-2, -1, 0, 1, 2, 3] value)
[] self._name = value
[]
_____________________________________ @[Link]
____ def name(self):
print('Deleting name')
property( ) del self._name
Returns the property atribute from the given getter
, setter , deleter. p = Person('Adam')
class Person: print('The name is:', [Link])
def __init__(self, name): [Link] = 'John'
self._name = name del [Link]
Getting name
def get_name(self):
The name is: Adam
print('Getting name')
Setting name to John
return self._name
Deleting name
def set_name(self, value):
print('Setting name to ' +
reversed( iterable_object )
value)
self._name = value Reverses the given iterable and returns it in
form of list.
def del_name(self): # reverse of a list
print('Deleting name') seq_list = [1, 2, 4, 3, 5]
del self._name print(list(reversed(seq_list)))
# Set property to use get_name, # reverse of a tuple object
set_name seq_tuple = ('P', 'y', 't', 'h')
# and del_name methods print(list(reversed(seq_tuple)))
name = property(get_name, [5, 3, 4, 2, 1]
set_name, ['h', 't', 'y', 'P']
del_name, 'Name property') _____________________________________
____
p = Person('Adam')
print([Link])
round(number , ndigits=0)
[Link] = 'John' returns floating point number rounded upto
del [Link] ndigits(default=0)
print(round(10)) # 10 Smit
print(round(5.4)) # 5 _____________________________________
print(round(5.5)) # 6 ____
print(round(2.665, 2)) # 2.67
print(round(2.675, 2)) # 2.67 sum( iterable , start)
_____________________________________ Returns the sum of items in iterable
____ marks = [65, 71, 68, 74, 61]
total_marks = sum(marks)
set( iterable )
print(total_marks) # 339
Creates a set object from the given iterable _____________________________________
print(set()) # empty set ____
print(set('PythonpPyoO')) # from
string super()
print(set(('a', 'e', 'i', 'o', Returns a proxy object(temporary object of
'u','e'))) # from tuple
superclass) that allows us to access methods of
print(set(['a', 'e', 'i', 'o',
'u','e'])) # from list base class
set() class Mammal(object):
{'O', 'n', 'y', 'o', 't', 'h', 'P', def __init__(self, mammalName):
'p'} print(mammalName, 'is a warm-
{'i', 'a', 'e', 'o', 'u'} blooded animal.')
{'i', 'a', 'e', 'o', 'u'}
_____________________________________ class Dog(Mammal):
____ def __init__(self):
print('Dog has four legs.')
slice ( start, end , step ) super().__init__('Dog')
returns sliced object from a iterable d1 = Dog()
text = 'Python Programing' Dog has four legs.
sliced_text = slice(9) Dog is a warm-blooded animal.
print(text[sliced_text]) _____________________________________
Python Pr ____
setattr( object , attribute , value )
sets the value of specified attribute of specified
tuple( iterable )
object
class Student: used to create tuples
name = 'Sheeran' t1 = tuple()
marks = 88 print('t1 =', t1)
# creating a tuple from a list
person = Student() t2 = tuple([1, 4, 6])
print([Link] , [Link]) print('t2 =', t2)
# creating a tuple from a string
t3 = tuple('Python')
setattr(person, 'name', 'Adam')
print('t3 =',t3)
setattr(person, 'marks', 78)
# creating a tuple from a dictionary
setattr(person,'subject','Maths')
t4 = tuple({1: 'one', 2: 'two'})
print([Link],[Link],person
print('t4 =',t4)
.subject)
t1 = ()
Sheeran 88
t2 = (1, 4, 6)
Adam 78 Maths
t3 = ('P', 'y', 't', 'h', 'o', 'n')
_____________________________________
t4 = (1, 2)
____
_____________________________________
str(object , encoding= , error=) ____
Returns string representation of given object. type()
(the encoding and error paramets are only to be returns type of object
used when object type is byte or bytearray) prime_numbers = [2, 3, 5, 7]
print(str('Smit')) type(prime_numbers)
list _____________________________________
_____________________________________ ____
____
vars()
retuns dictionary form of given attribute.
class Fruit:
def __init__(self, apple = 5,
banana = 10):
[Link] = apple
[Link] = banana
eat = Fruit()
print(vars(eat))
{'apple': 5, 'banana': 10}
_____________________________________
____
zip( *iterable )
takes iterable and aggregates into a tuple
• The * operator can be used in conjunction
with zip() to unzip the list.
languages = ['Java', 'Python',
'JavaScript']
versions = [14, 3, 6]
result = zip(languages, versions)
result_list = list(result)
print(result_list)
l , v = zip(*result_list)
print(l)
print(v)
[('Java', 14), ('Python', 3),
('JavaScript', 6)]
('Java', 'Python', 'JavaScript')
(14, 3, 6)