Showing posts with label function in python. Show all posts
Showing posts with label function in python. Show all posts

Monday, November 16, 2020

, , ,

Example program for super function in python

 super() function in python return the proxy object it's also a temporary object of the superclass and this object help us to access the method of base class.

Super function has two use :-

  • This function Working with Multiple Inheritance
  • Help us to avoid base class name explicitly

Example of super function in python:-

if it use single inheritance then this function help us to refer base class by super()
class Mammal(object):
  def __init__(self, mammalName):
    print(mammalName, 'is a warm-blooded animal.')
    
class Dog(Mammal):
  def __init__(self):
    print('Dog has four legs.')
    super().__init__('Dog')
    
d1 = Dog()

OUTPUT

Dog has four legs.
Dog is a warm-blooded animal.

We can also change the name of base class Let see

# changing base class to CanidaeFamily
class Dog(CanidaeFamily):
  def __init__(self):
    print('Dog has four legs.')

    # no need to change this
    super().__init__('Dog')

Well super function in python is an call method for base class via delegation and that is called indirection and this happen at run then time in between this time we can also use the other base classes at different times.

Example program for super() with Multiple Inheritance

class Animal:
  def __init__(self, Animal):
    print(Animal, 'is an animal.');

class Mammal(Animal):
  def __init__(self, mammalName):
    print(mammalName, 'is a warm-blooded animal.')
    super().__init__(mammalName)
    
class NonWingedMammal(Mammal):
  def __init__(self, NonWingedMammal):
    print(NonWingedMammal, "can't fly.")
    super().__init__(NonWingedMammal)

class NonMarineMammal(Mammal):
  def __init__(self, NonMarineMammal):
    print(NonMarineMammal, "can't swim.")
    super().__init__(NonMarineMammal)

class Dog(NonMarineMammal, NonWingedMammal):
  def __init__(self):
    print('Dog has 4 legs.');
    super().__init__('Dog')
    
d = Dog()
print('')
bat = NonMarineMammal('Bat')

OUTPUT

super function in python
Example program for super function in python

 

 

Method Resolution Order (MRO)For super() function in python

MRO is use to maintain the order at the persence of the multiple inheritance and ir can also view by using the __mro__ attribute.

>>> Dog.__mro__
(<class 'Dog'>, 
<class 'NonMarineMammal'>, 
<class 'NonWingedMammal'>, 
<class 'Mammal'>, 
<class 'Animal'>, 
<class 'object'>)

Saturday, November 7, 2020

, ,

Example Program for complie() function in python - Python Program

 

 The complie() function in python is used to return python code object from a source like (string,AST object,byte string).

Syntax For Complie(): -

compile(source, filename, mode, flags=0, dont_inherit=False, optimize=-1)


Well the return object from the compile function in python can be called by exec() and eval() method.

Parameter : -

  • A source that can be used in compile function that can be normal string, a byte string, or an AST object.

  • A code that can be read from a file. If it doesn't read form a file then you give a name according to you.
  • Either exec,eval or signal method can be used to call a function.
  • Well eval accept only a single expression.
  • exec take block of code with python statement like class function.
  • it contain single interactive statement.

 flags (optional) and dont_inherit : - if any problem stop to compile the source then it raise flag. default value : -0

 optimize (optional) - optimization level with Default value -1 for compiler.

Example Program for complie() function
Example Program for complie() function

 

Example program for compile() function in python : -

codeInString = 'a = 5\nb=6\nsum=a+b\nprint("sum =",sum)'
codeObejct = compile(codeInString, 'sumstring', 'exec')

exec(codeObejct)

OUTPUT

sum = 11

compile function in python convert the string into a python code object and then execute with exec() method

Tuesday, November 3, 2020

, , ,

Example Program For Complex Function In Python - Python Program

  •  Well Python not only handle the real number but also handle the complex numbers with the help of Complex function in python.
  • This complex function is so useful to manipulate mathematics problem's.
  • complex function in python return the real number from complex number or convert the string to a complex number. 
Example Program For Complex Function In Python
Example Program For Complex Function In Python

 

 Parameter : -

  •     real - real part. If real is extinct then it defaults to 0.
  •     imag - imaginary part. If imag is extinct then it defaults to 0.

Return the complex number.

Example of Complex function in Python To Create a complex number:-

z = complex(2, 3)
print(z)

z = complex(2)
print(z)

z = complex()
print(z)

z = complex('4-5j')
print(z)
(2+3j)
(2+0j)
0j
(4-5j)

Monday, November 2, 2020

, ,

Example Program for vars() function in python - Python Example Program

 vars() function in python return the dictionary attribute of an object.

Example Program for vars function in python
Example Program for vars() function in python

 

  • vars() can just take one object that can be module, class, instance, or any object which  having the __dict__ attribute in python program.
  • If the any object passed to vars() function doesn't  have the __dict__ attribute then it give an TypeError exception.
  • If any argument doesn't pass to vars() function then it act like an locals() function.

Example Program For vars function in python : -


class Foo:
  def __init__(self, a = 5, b = 10):
    self.a = a
    self.b = b
  
object = Foo()
print(vars(object))

OUTPUT

{'a': 5, 'b': 10}

Friday, May 29, 2020

,

python built-in function for file handling

Python File Method : - 

These all are the python built-in function which is used to manipulate the python files and update these files in python.

python built-in function for file handling
python built-in function for file handling

close() method in python : - 

close() method in python closes an open file. A file should always be closed because without closing file changes made to a file may not show until you close the file.

Syntax : -

file.close() 

Python File fileno() Method : - 

fileno() function in python returns the file descriptor of the stream, as a number, and an error will occur if the operating system does not use a file descriptor.

Syntax : -

file.fileno()
 

Python flush() Method : - 

flush() function solve the buffer problem this function  cleans out the internal buffer.

Syntax : -

file.fileno()

isatty() function in python : - 

isatty() function in python returns True if the file stream is interactive, example: connected to a terminal.

Syntax : -

file.isatty()

read() function in python : - 

read() method in python gives the number of bytes of the specified file, Default is -1 it means the whole file.

Syntax : -

file.read()

readable() function in python : - 

readable() function in python gives true if the file is readable,or false if the file is not readable.

Syntax : -

file.readable()

readline() function in python : - 

readline() in python returns one line from the file. The programmer can also decide how many bytes from the line to return.

Syntax : -

file.readline(size)

readlines() method in python : - 

readlines() method in python gives a list that contains each line in the file as a list item. You can use the hint parameter to limit the number of lines returned.

Syntax : -

file.readlines(hint)

seek() method in python : - 

seek() method in python set the current file position in a file stream and return the new position of the file.

Syntax : -

file.seek(offset)

seekable() method in python : - 

seekable() in python method returns True if the file is seekable, False if not. A file is seekable if it allows access to the file stream in python.

Syntax : -

file.seekable()

tell() function in python : - 

tell() method in python gives the current file position in a file stream and the file position can be changed with the help of seeks function in python.

Syntax : -

file.tell()

truncate() function in python : - 

truncate() method in python use to resize the file to the given number of bytes.
 If the size is not specified, the current position will be used.

Syntax : -

file.truncate(size)

writable() function in python : - 

writable() method in python gives true if a file is writable and a file is writable so it is opened using "a" for append or "w" for write.

Syntax : -

file.writable()

Python File write() Method

write method in python is used to write specified text into the file.

Where this text will be inserted depends on the file mode and stream position.

"a":  The text will be inserted at the current file stream position, default at the end of the file.

"w": The file will be emptied before the text will be inserted at the current file stream position, and the default will be 0. 

Syntax : -

file.write(byte)

writelines() Method

writelines() function in python writes the items of a list into the specified file.

Where this item will be inserted depends on the file mode and stream position.

"a":  The item will be inserted at the current file stream position, default at the end of the file.

"w": The file will be emptied before the list item will be inserted at the current file stream position, and the default will be 0.

Syntax : -

file.writelines(list)

,

Python In Build Function To Manipulate On Python Set

SET FUNCTION IN PYTHON PROGRAMMING 

 These all are the in-build function in python to manipulate on python set. These functions will reduce the time and program complexity.

Python In Build Function To Manipulate On Python Set
Python In Build Function To Manipulate On Python Set

add() function in python: - 

add() method add the element to the python set. If the element already exists, then add() function does not add the element to the python set.

Syntax : -

set.add(elmnt) 

clear() function in python: -

add() method removes all the elements from the specified python set.

Syntax : -

set.clear()

copy() function in python: -

copy() function copies the set in python programming.

Syntax : -

set.copy()

difference() function in python: -

difference() function returns a set that contains the difference between two sets.

Syntax : -

set.difference(set)

it can also be shown as A ∩ B set A has some element that doesn't exist in set B.

difference update() function in python: - 

difference_update() function in python removes the common element in both sets. it gives you a new without unwanted elements.

Syntax : -

set.difference_update(set)

discard() function in python: -

discard() function in python remove the specified element for the set in python.

Syntax : -

set.discard(value) 

intersection() function in python: - 

As set theory says intersection() function gives a set that contains the similarity between two or more sets.

Syntax : -

set.intersection(set1, set2 ... etc)

intersection update() function in python: -

intersection_update() function in python removes the items that are not present in both sets.

Syntax : -

set.intersection_update(set1, set2 ... etc)

isdisjoint() function: -

isdisjoint() in python gives true if none of the items are present in both sets, otherwise, it returns False.

Syntax : -

set.isdisjoint(set)

issubset(): -

issubset() method for python returns True if all items in the set exist in the specified set otherwise it returns False.

Syntax : -

set.issubset(set)

 issuperset() Method for python set :-

issuperset() method for python returns True if all items of specified set exist in the original set otherwise it returns False.

Syntax : -

set.issuperset(set)

 pop() Method for python set:-

pop() function removes a random item from the set and returns the removed item.

Syntax : -

set.pop()

remove() python set:-

 remove() function removes the specified element from the set and raise an error if the specified item does not exist.

Syntax : -

set.remove(item)

symmetric_difference():-

symmetric_difference() method returns a set that contains all items from both sets, but not the items that are present in both sets.

Syntax : -

set.symmetric_difference(set)

symmetric_difference_update():-

symmetric_difference_update() method in python set function updates the original set by removing items that are present in both sets and inserting the other items.

Syntax : -

set.symmetric_difference_update(set)


Python Set union() Method:-

According to the math set theory union(), method returns a set that contains all items from the original set, and also all elements from the specified sets.

Syntax : -

set.union(set1, set2...)

update() Method in python:-

update() python set function update the set by adding items from another set. If one item is present in both sets, only one appearance of this item will be present in the updated set.

Syntax : -

set.union(set1, set2...)

Wednesday, May 27, 2020

,

Python Dictionary Method's and python built-in function

Python Dictionary Method's

These are all the built-in methods that you can use to manipulate the python dictionary.

Python Dictionary Method's and python built-in function
Python Dictionary Method's and python built-in function

clear() function in python:- 

clear() method in python dictionary use to remove all elements from a dictionary.

Syntax : -

dictionary.clear() 

copy() method in python dictionary:-

As its name says copy() method gives a copy of the specified dictionary.

Syntax : -

dictionary.copy()

fromkeys() Method : - 

formkeys() method helps to return a python dictionary with specified keys and the specified value.

Syntax : -

dict.fromkeys(keys, value)

get() Method : -  

get() method helps to return the value of the item with the specified key.

Syntax : -

dictionary.get(keyname, value)

items() Method : -  

items() in python dictionary gives the view object that contains key-value pairs of the dictionary, and reflect any changes made to the dictionary

Syntax : -

dictionary.items()

key() Method : -  

key() in python dictionary returns the view object that contains the key of the dictionary as a list and reflects any changes made to the dictionary.

Syntax : -

dictionary.keys()

pop() Method in python: -  

pop() in python follows the same method like remove() function the only difference is pop() function remove the specified item from the dictionary.

Syntax : -

dictionary.pop(keyname, defaultvalue)

remove item will be the return value of pop() function.

popitem() Method in python: -  

popitem() in python dictionary removes the last inserted item into the dictionary.  

Syntax : -

dictionary.popitem()

removed value in popitem() will be the return value in a python dictionary.

Python Dictionary setdefault() Method

setdefault() method gives/returns the value from python dictionary the item with the specified key. If any key does not exist, insert the key, with the specified value.

Syntax : -

dictionary.setdefault(keyname, value)

Python Dictionary update() Method:-

update() method use to inserts the specified items to the python dictionary.

Syntax : -

dictionary.update(iterable)

 values() Method in python dictionary:-

values() method used to return the view object that contains the values of the dictionary, as a list.

Syntax : -

dictionary.values()
Reflect any changes make to the python dictionary

Tuesday, May 26, 2020

,

build-in function for list in python and array method

These all are the build-in function which is used to manipulate the list in the python.

Python build-in list function and array method
build-in function for list in python and array method

Python List append Method:-

append() function in python use to add an element at the end of the list.

Syntax : - 

list.append(elmnt) 

clear() method in Python:-

clear() function in python programming helps you to remove all the elements from the list

Syntax : - 

list.clear()

copy() method in list:-

As its name says copy() function gives a copy of the specified list.

Syntax : - 

list.copy()

count() method in python list:-

count() function in python count the number of elements in a specified value and return it.

Syntax : - 

list.count(value)

extend() method in python list:-

extend() method of python list uses to add any specified iterable at the end of the current list.

Syntax : - 

list.extend(iterable)

index() method in python:-

index() method of list returns the address of the first occurrence of the specified value in python.

Syntax : - 

list.index(elmnt)

insert() function in python:-

insert() function uses to insert an element at the specified position in the python list.

Syntax : - 

list.insert(pos, elmnt)

pop() function in python list:-

pop() function uses as it is used in the data structure to remove an element from a list at the specified position so it uses the same in python to remove any element from the python list.

Syntax : - 

list.pop(pos)

the default value is -1 which gives the last element of a list.

remove() function in python list:-

remove() method of python list removes the first occurrence of the element at the specified value.

Syntax : - 

list.remove(elmnt)

reverse() method in python list:-

reverse() method of python list helps to reverse the sorting order of the element in the list.

Syntax : - 

list.reverse()

sort() method:-

sort() method of python list helps to sort the list in ascending by default. 

Syntax : - 

list.sort(reverse=True|False, key=myFunc)

Sunday, May 24, 2020

Build-in function in python programming



learn about all the built-in functions in python and learn about their syntax and how to use them.

Build-in function in python programming
Build-in function in python programming

abs function in python:-

abs() function is also known as python absolute value function it's used to return the absolute value of the specified number.

Syntax : -

abs(n) 

all() function in python :-

abs() function in python return true if all elements of the iterable are true otherwise it return false.
 
all(iterable) 

any() function in python :-

any() function in python return true if all elements of the iterable are true If the iterable is empty, return False.

any(iterable) 

ascii() function in python :-

ASCII() function in python return a readable format of any object (Strings, Tuples, Lists, etc). It also replaces any non-ASCII characters with escape characters.

Syntax : - 

ascii(object) 

bin() function in python :-

bin() function in python programming is used to change any specified number into binary form and return that binary number to the calling function.

Syntax : - 

bin(n)

remember result will start with 0b prefix.

bool() function in python :-

bin() function in python programming return the boolean value of specified objects in the python program.
If the object is not true then it will be : - 

The object is empty, like [], (), {}
The object is False
The object is 0
The object is None


Syntax : - 

bool(object)

bytearray() function in python :-

bytearray() function in python programming uses to return the byte of object. It can convert objects into bytearray objects.

Syntax : -

bytearray(x, encoding, error)

X : - it is a source to create the bytearray().

Encoding: -  encode the string


Error:- Specified what to if any error occurs.


byte() function in python :-

 byte() function in python programming return a byte object and convert the object into byte object same as bytearray() function the only difference between byte and bytearray() function is that byte return an object that can not be modified and bytearray() function return an object that can be modified.

Syntax : - 

bytes(x, encoding, error)

byte() function in python :-

byte() function in python programming returns true if the specified object is callable or return false.

Syntax : - 

callable(object) 

chr() function in python programming:-

chr() function in python returns the character which is represented by the help of Unicode.

Syntax : - 

chr(number) 


compile() function in python :-

compile() function in python return the source as the code object which is ready to be executed or run.

Syntax : - 

compile(source,
    filename, mode, flag, dont_inherit, 
    optimize)
   

complex() function in python :-

the complex() function given a complex number that contains a real number and an imaginary number.

Syntax : -

complex(real, imaginary) 


delattr() function in python :-

delattr() function help you to delete the specified attribute from the specified object.

Syntax : -

delattr(object, attribute)
  

dict() function in python :-

dict() function help you to create the dictionary in python.

Syntax : -

delattr(object, attribute)
  
dict() doesn't return anything.


dir() function in python :-


dir() function in python returns the properties and methods of the specified object, without the values. it means dir() function will tell you what process should apply on the object.

Syntax : -

dir(object)
  
  
divmod() function in python :-

 

divmod() function in python

is used to return the
quotient and the remainder because argument1 (dividend) is divided by argument2 (divisor).

Syntax : -

divmod(divident, divisor)
   
 

enumerate() function in python :-

 enumerate() function in python takes a list of tuples and return it as an enumerate object.Its also used to add a counter to an iterable and give back in a form of enumerate object.

Syntax : -

enumerate(iterable, start)
 

eval

() function in python :-

eval() function in python use to validate the specified expression if the expression is legal Python statement, then it go further execution.

Syntax : -

eval(expression, globals, locals)
 

exec() function in python :-

 exec() function work as same as eval() function but only different is exec() execute a large blocks of code unlike the eval() function in python execute the single expression.

Syntax : -

exec(object, globals, locals)


filter() function in python :-

filter() function in python use to filters the given iterable(set which is going to be filter like list, tuples etc.) with the help of a function which test the every element in given iterable to be true or not.

Syntax : -

filter(function, iterable)
  

float() function :-

filter() function in python converts the given value into a floating point.

Syntax : -

float(value)


format() function :-

format() function in python given value into a specified format.

Syntax : -

format(value, 
    format)


froaenset() function for python :-

frozenset() function in python gives an unchangeable frozenset object which can be define by user.

Syntax : -

frozenset(iterable).
  

getattr() function for python :-

getattr() function in python gives the specified attribute from the specified object in python.

Syntax : -

getattr(object, attribute, default)
  

globals() function for python :-

globals() function in python programming gives a table of the symbol as a dictionary and that symbol table contains necessary information about the current program.

Syntax : -

globals()


hasattr() function for python :-

hasattr() will return true if the specified object in python gives the specified attribute otherwise gives false.

Syntax : -

hasattr(object, attribute)
  

hex() function for python :-

hex() function in python programming uses to convert the specified number into a hexadecimal number. 

Syntax : - 
hex(number)
  

id() function :-

id() function in python gives the unique id for a specified object and id is assigned to object at a time when the object is created.
Well id is a memory address for that specified object and it will be changed every time user run the python program

Syntax : -

id(object)

input() function

input() function in python use to give input to the python program.


Syntax : -

input(prompt)
  
 

int() function

int() function help to convert the specified number into an integer number.

Syntax : -

int(value, base)
python isinstance() function :-

isinstance() function gives true if the specified object is followed by the specified type otherwise false.


Syntax : -

isinstance(object, type)
 

python issubclass() function :-

issubclass() function gives true if the specified object is a subclass of a class object otherwise false.

Syntax : -

issubclass(object, subclass

subclass: - A class of objects.

python iter() function :-


Return the iterator object in python.

Syntax : -

iter(object, sentinel)


python len() function :-

len() function is very helpful to know about the number of items in an object.

Syntax : -

len(object)

python list() function :-

this function does the same as its name says list() function in python use to create an ordered and changeable list of objects.

Syntax : -

list(iterable)
  

python local() function:-

local() function in python returns a symbol table which contains all the necessary information about the python program. 

Syntax : -

locals()
   

map() function

map() function in python is a special function it executes the specified function for every item in iterable. The item is sent to the function as a parameter.

Syntax : -

map(function, iterables)
   

max() function:-

As its name says max() function gives the maximum value item from iterable.

Syntax : -

max(iterable)

memoryview () function:-

 memoryview() object gives a memory view object from a specified object.

Syntax : -

memoryview(obj

min() function:-

As its name says min() function gives the minimum value item within the given iterable.

Syntax : -

min(iterable)

next() function:-

As its name says next() function returns the next value form the given an iterator. Add a default value for the end of the iterable.

Syntax : -

next(iterable, default)

object() function:-


object function in python programming gives you a new object that object can't be changed or update with new properties  because it contains  built-in properties and methods that are default and for all classes.

Syntax : -

object()

oct() function in python:-


oct function in python programming helps to convert an integer into an octal string.

Syntax : -

oct(int)

open() function in python:-


open() function in python use to open a file and returns the file objects.

Syntax : -

open(file,mode)

ord() function in python:-

ord() function in python gives the number in Unicode which is used to representing the specified character. 

Syntax : -

ord(character)

pow() function in python:-

As its name says pow() function returns the value of x to the power of y (xy).if any third parameter is present then it takes as modulus in python.

Syntax : -

pow(x, y, z)

print() function in python:-

print() function is used to print the specified message to the screen and other output devices. The message can be any object.

Syntax : -

print(object(s), sep=separator, end=end, file=file, flush=flush)

range() function in python:-

range() function return the sequence of number which is started by default 0 and increase by 1 and stops before a specified number.

Syntax : -

range(start, stop, step)

reversed() function in python:-

reversed () function in python gives the reverse iteration object in python.

Syntax : -

reversed(sequence)

round() function in python:-

the round() function gives a floating-point number and that number is a rounded version of a specified number in python program. It means it gives the nearest integer number.

Syntax : -

round(number,digits)

set() function in python:-

the set() function used to create a set of objects and the item list in the set is unordered and it will appear in random order.

Syntax : -

set(iterable)

setattr() function in python:-

setattr() function in python programming set the specified attribute for the specified object.

Syntax : -

setattr(object, attribute, value)
  

slice() function in python:-

slice() function in python is used to slice a specified sequence and starting point and endpoint of slicing can also be specified. You can also specify the steps for the slicing process.

Syntax : -

slice(start, end, step)
  

sorted() function in python:-

sorted() function use for data structure in python this function used to sort the list of the specified iterable object. You can also define the ascending or descending order.

Syntax : -

sorted(iterable, key=key, reverse=reverse)  

str() function in python:-

str() function used to convert the specified value into a string.

Syntax : -

str(object, encoding=encoding, errors=errors)  

sum() function in python:-

sum() function returns the number which is the sum of all iterable in python.

Syntax : -

sum(iterable,  start)

super() function in python:-

  super() function in python is used to give access to all the properties and methods of parent and sibling classes.

Syntax : -

super()

tuple() function in python:-

tuple() function is used to creates the tuple object in python. 

Syntax : -

tuple(iterable)
  

type() function in python:- 

it will work as its name says type function in python programming helps to tell about the type of specified object.

Syntax : -

type(object, bases, dict)
  

vars() function in python:- 


vars() function is used to return the __dic__ attribute of an object.

__dic__ attribute containing the object's changeable attributes.

Syntax : -

vars(object)
  

zip() function in python:- 

zip() function in python will work like a zip file which means zip() in python return a zip() object which is a tuple of iterator so the first item in peach passed iterator is paired together, and the next one will do the same process.

if the passed iterator has a different length then the last item from the iterator decides the length of the new iterator.

Syntax : -

zip(iterator1, iterator2, iterator3 ...)
  
  
 these all are the Python Built-in Functions which used in python programs.