Python abs() and Python all() built in functions

The Python abs() function and all() functions are two built-in functions.Here we will see how to to use them in our program.

i)abs()
ii)all()

Python abs()

The Pyhton abs() function return the absolute value of any number passed as it’s argument.

If the number is an integer or a floating point value the abs() return it’s +ve value.

If the argument passed is a complex number the abs() return the magnitude of the complex number.The magnitude of complex number is calculated as :
 
√ a2 + b2

A code example is given below.

>>> abs( 2.3546 )
2.3546
>>> abs( -2.3546)
2.3546
>>> abs( -6473)
6473
>>> abs( 0.64647 )
0.64647

We cannot pass string to abs() ,a code example is given below when string and complex number is passed.

>>> abs( 23+78j )
81.3203541556479
>>> abs( 2+2j )
2.8284271247461903
>>> abs( 4+4j )
5.656854249492381
>>> abs( 4+3j)
5.0
>>> #Passing string
>>> abs( 'string')
Traceback (most recent call last):
  File "<pyshell#42>", line 1, in <module>
    abs( 'string')
TypeError: bad operand type for abs(): 'str'


Python all()

The Python all() builit-in functions return true if all the elements of the iterable pass to the all() are True.An element is considered as false only when it 0(zero).

The all() function also returns True if the iterable pass to all() is empty.

If you are wondering what iterable means,it refers to string,list ,tuple, set and dictionary data type.

Link : Python dictionary data type

A code example is given below.

>>> #Passing tuple
>>> all( () ) #Passing empty tuple
True
>>> all( (10, 34 , 'Text') ) #Passing tuple with all True elements
True
>>> all( (23 , 0, 'New') ) #The 2nd element is false
False
>>> #Passing set
>>> st=set()
>>> all( st ) #Empty set
True
>>> all( {23 , 89} )
True
>>> all( { 0 , 90} )
False
>>> #Passing dictionary
>>> all( {} ) #Empty dictionary
True
>>> all( {23:'Text' , 0:'New'} ) #One key 0 element
False
>>> all( {23:0 , 'New':89 , 'Heap':0} ) 
True

In passing dictionary as argument the element is treated as False only when the key is 0 not the value.

You try it out for list and string type.

all() function is somewhat similar to any() function.

Link :Python any


*Side note

Calling all() function is similar to executing the code shown below.

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True



Leave a Reply

Your email address will not be published. Required fields are marked *