Category: Python Built-in Functions

  • Python any() Function

    The python any() function returns True if any item in an iterable is true, otherwise it returns False.

    Note : If the iterable is empty, then it returns False.

    Python any() Function Syntax

    It has the following syntax:

    any(iterable)  

    Parameters

    Iterable: It takes an iterable object such as list, dictionary etc.

    Return

    It returns true if at least one element of an iterable is true.

    Different Examples for Python any() Function

    Here, we are going to take several examples for Python any() function.

    Python any() Function Example 1

    Let’s see how any() works for lists?

    l = [4, 3, 2, 0]                              
    
    print(any(l))                                   
    
      
    
    l = [0, False]  
    
    print(any(l))  
    
      
    
    l = [0, False, 5]  
    
    print(any(l))  
    
      
    
    l = []  
    
    print(any(l))

    Output:

    True
    False
    True
    False
    

    Explanation: In the above example, we take some list (l) that contains some items, and then check the output of the code. In first case, a list containing all true values so it returns TRUE.

    In second case, both items contains a false value. So, it returns FALSE.

    In third case, two items contain false and one item contains true. So, it returns TRUE.

    In the last case, there is an empty list. So, it returns FALSE.

    Python any() Function Example 2

    The below example shows how any() works with strings.

    s = "This is awesome"  
    
    print(any(s))  
    
      
    
    # 0 is False  
    
    # '0' is True  
    
    s = '000'  
    
    print(any(s))  
    
      
    
    s = ''  
    
    print(any(s))

    Output:

    True
    True
    False
    

    Explanation: In the above example, a string returns True value.

    In second case, ‘000’ behaves like a string so, it returns True value.

    In third case, a string is empty. So, it returns False value.

    Python any() Function Example 3

    The below example shows how any() works with dictionaries.

    d = {0: 'False'}                   
    
    print(any(d))  
    
      
    
    d = {0: 'False', 1: 'True'}  
    
    print(any(d))  
    
      
    
    d = {0: 'False', False: 0}  
    
    print(any(d))  
    
      
    
    d = {}  
    
    print(any(d))  
    
      
    
    # 0 is False  
    
    # '0' is True  
    
    d = {'0': 'False'}  
    
    print(any(d))

    Output:

    False
    True
    False
    False
    True
    

    Explanation: In the above example, we take some dictionaries that contain some items. In the first case, 0 returns False value.

    In the second case, one item is a false value and other value is true value. So, it returns true value.

    In the third case, both the values are false values, so it returns false value.

    In the fourth case, a dictionary is empty. So, it returns a False value.

    In the fifth case, ‘0’ behaves like a string. So, it returns a True value.

  • Python sum() Function

    As the name says, python sum() function is used to get the sum of numbers of an iterable, i.e. list.

    Python sum() Function Syntax

    It has the following syntax:

    sum(iterable, start)  

    Parameters

    • iterable: iterable can be list, tuples, and dictionaries, but an iterable object must contain numbers.
    • start: The start is added to the sum of numbers in the iterable. If start is not given in the syntax, it is assumed to be 0.

    Different Examples for Python sum() Function 

    Let’s see some examples of sum() function are given below:

    Python sum() Function Example 1

    This example shows sum of the list of numbers:

    s = sum([1, 2,2 ])  
    
    print(s)  
    
      
    
    s = sum([1, 2, 2], 10)  
    
    print(s)

    Output:

    5
    15
    

    Python sum() Function Example 2

    This example shows sum of floating point numbers:

    s = sum([2.5, 2.5, 3])  
    
    print(s)

    Output:

    7.0
    

    Python sum() Function Example 3

    This example shows sum of complex numbers:

    s = sum([1 + 2j, 3 + 4j])  
    
    print(s)  
    
      
    
    s = sum([1 + 2j, 3 + 4j], 2 + 2j)  
    
    print(s)  
    
      
    
    s = sum([1 + 2j, 2, 1.5 - 2j])  
    
    print(s)

    Output:

    (4+6j)
    (6+8j)
    (4.5+0j)
  • Python exec() Function

    The python exec() function is used for the dynamic execution of Python program which can either be a string or object code and it accepts large blocks of code, unlike the eval() function which only accepts a single expression.

    Python exec() Function Syntax

    It has the following syntax:

    exec(object, globals, locals)  

    Parameters

    • object: It should be either string or code object.
    • globals (optional): It is used to specify global functions.
    • locals (optional): It is used to specify local functions.

    Different Examples for Python exec() function

    Let’s see some examples of exec() function which are given below:

    Python exec() Function Example 1

    This example shows working of exec() function.

    x = 5  
    
    exec('print(x==5)')  
    
    exec('print(x+4)')

    Output:

    True
    9
    

    Python exec() Function Example 2

    This example shows exec() dynamic code execution

    from math import *  
    
    for l in range(1, 3):  
    
        func = input("Enter Code Snippet to execute:\n")  
    
        try:  
    
            exec(func)  
    
          except Exception as ex:  
    
            print(ex)  
    
            break  
    
    print('Done')

    Output:

    Enter Code Snippet to execute:
    print(sqrt(16))
    4.0
    Enter Code Snippet to execute:
    print(min(2,1))
    1
    Done
  • Python compile() Function

    The python compile() function takes source code as input and returns a code object which can later be executed by exec() function.

    Python compile() Function Syntax

    It has the following syntax:

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

    Parameters

    • source – normal string, a byte string, or an AST (Abstract Syntax Trees) object.
    • filename – File from which the code is read.
    • mode – mode can be either exec or eval or single.
      • eval – if the source is a single expression.
      • exec – if the source is block of statements.
      • single – if the source is single statement.
    • flags and dont_inherit – Default Value= 0. Both are optional parameters. It monitors that which future statements affect the compilation of the source.
    • optimize (optional) – Default value -1. It defines the optimization level of the compiler.

    Return

    It returns a Python code object.

    Different Examples of Python compile() Function

    Let’s see some examples of compile() function which are given below:

    Python compile() Function Example 1

    This example shows to compile a string source to the code object.

    # compile string source to code  
    
    code_str = 'x=5\ny=10\nprint("sum =",x+y)'  
    
    code = compile(code_str, 'sum.py', 'exec')  
    
    print(type(code))  
    
    exec(code)  
    
    exec(x)

    Output:

    <class 'code'>
    sum = 15
    

    Python compile() Function Example 2

    This example shows to read a code from the file and compile.

    Let’s say we have mycode.py file with following content.

    x = 10  
    
    y = 20  
    
    print('Multiplication = ', x * y)

    We can read this file content as a string ,compile it to code object and execute it.

    # reading code from a file  
    
    f = open('my_code.py', 'r')  
    
    code_str = f.read()  
    
    f.close()  
    
    code = compile(code_str, 'my_code.py', 'exec')  
    
    exec(code)

    Output:

    Multiplication =200
  • Python callable() Function

    A python callable() function in Python is something that can be called. This built-in function checks and returns True if the object passed appears to be callable, otherwise False.

    Python callbale() Function Syntax

    It has the following syntax:

    callable(object)  

    Parameters

    object – The object that you want to test and check, it is callable or not.

    Return

    Returns True if the object is callable, otherwise False.

    Different Examples for Python callable() Function

    Let’s see some examples of callable() function in Python.

    Python callable() Function Example 1

    Check if a function is callable:

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

    Output:

    True
    

    Python callable() Function Example 2

    Check if a function is not callable (such as normal variable).

    x = 5  
    
    print(callable(x))

    Output:

    False
  • Python bytes() Function

    The python bytes() function in Python is used for returning a bytes object. It is an immutable version of bytearray() function.

    It can create empty bytes object of the specified size.

    Python bytes() Function Syntax

    It has the following syntax:

    bytes(source)  
    
                bytes(encoding)  
    
                bytes(error)

    Parameters

    • source is used to initialize the bytes object. It is an optional parameter.
    • encoding is optional unless source is string type. It is used to convert the string to bytes using str.encode() function
    • errors is also an optional parameter. It is used when the source is string type. Also, when encoding fails due to some error.

    Return

    It returns a bytes object.

    Different Examples for Python bytes() Function Example

    Let’s see some examples of bytes() function to understand it’s functionality.

    Python bytes() Function Example 1

    This is a simple example of converting string into bytes.

    string = "Hello World."  
    
    arr = bytes(string, 'utf-8')  
    
    print(arr)

    Output:

    b ' Hello World.'
    

    Python bytes() Function Example 2

    This example creates a byte of a given integer size.

    size = 5  
    
    arr = bytes(size)  
    
    print(arr)

    Output:

    b'\x00\x00\x00\x00\x00'
    

    Python bytes() Function Example 3

    This example converts iterable list to bytes.

    List = [1, 2, 3, 4, 5]  
    
    arr = bytes(List)  
    
    print(arr)

    Output:

    b'\x01\x02\x03\x04\x05'
  • Python bool() Function

    The bool() function is one of the built in methods in python which outputs the Boolean value depending on the input parameters. The Boolean values True or False are returned from the single argument. The python bool() method converts value to boolean (True or False) using the standard truth testing procedure.

    Python bool() Function Syntax

    It has the following syntax:

    bool([value])  

    Parameters

    It is not mandatory to pass value to bool(). If you do not pass the value, bool() returns False.

    In general , bool() takes a single parameter value.

    Return

    The bool() returns:

    • Returns False if the value is omitted or false and the condition is not met.
    • Returns True if the value is true and condition is met.

    Python bool() Function Example 1

    Let us take an example to demonstrate the bool() function in Python.

    # Python program example for bool() Function  
    
    # Creating an empty list  
    
    test = []  
    
    # Printing the value of the list and its boolean value  
    
    print(test, 'is', bool(test))   
    
      
    
    # Creating a list with one item (0)  
    
    test = [0]  
    
    # Printing the value of the list and its boolean value  
    
    print(test, 'is', bool(test))  
    
      
    
    # Creating a float value of 0.0  
    
    test = 0.0  
    
    # Printing the value of the float and its boolean value  
    
    print(test, 'is', bool(test))  
    
      
    
    # Creating a None value  
    
    test = None  
    
    # Printing the value of None and its boolean value  
    
    print(test, 'is', bool(test))  
    
      
    
    # Creating a boolean value of True  
    
    test = True  
    
    # Printing the value of True and its boolean value  
    
    print(test, 'is', bool(test))  
    
      
    
    # Creating a string value  
    
    test = 'Easy string'  
    
    # Printing the value of the string and its boolean value  
    
    print(test, 'is', bool(test))

    Output:

    [] is False
    [] is False
    [0] is True
    0.0 is False
    None is False
    True is True
    Easy string is True
    

    Python bool() Function Example 2

    Let’s take anothe example to demonstrate the bool() function with if-else statements in Python.

    num = 12  
    
    if num > 15:  
    
        print(" number is greater than 15")  
    
    else:  
    
        print(" number is less than or equal to 15")

    Output:

    number is less than or equal to 15
    

    Explanation:

    In the above code, If the condition is true or false, the respective block is executed.

    Now, lets see the explicit conversion of value into Boolean value in the below example.

    # Using bool() function to convert the condition to a boolean value

    Example:

    num = 12  
    
    if bool(num > 15):  
    
        print(" number is greater than 15")  
    
    else:  
    
        print(" number is less than or equal to 15")

    Output:

    number is less than or equal to 15
    

    Python bool() Function Example 3

    1. Using bool() function to check if a value is True or False

    Example:

    val = " Javatpoint "  
    
    if bool(val):  
    
        print("True")  
    
    else:  
    
        print("False")

    Output:

    True
    

    2. To Check if an empty string is True or False

    Example:

    emp_str = ""  
    
    if bool(emp_str):  
    
        print("True")  
    
    else:  
    
        print("False")

    Output:

    False
    

    3. To Check if a zero value is True or False

    Example:

    zero_val = 0  
    
    if bool(zero_val):  
    
        print("True")  
    
    else:  
    
        print("False")

    Output:

    False
    

    Conclusion:

    All in all, the bool() function is a useful asset in Python for working with boolean values. It very well may be utilized to switch any value over completely to a boolean value expressly, and it can likewise be utilized to check in the event that a value is true or false.

  • Python bin() Function

    The python bin() function is used to return the binary representation of a specified integer. A result always starts with the prefix 0b.

    Python bin() Function Syntax

    It has the following syntax:

    bin(n)

    Parameters

    • n: It represents an integer.

    Return

    It returns the binary representation of a specified integer.

    Python bin() Function Example 1

    Let us take an example to demonstrate the python bin() function.

    x =  10  
    
    y =  bin(x)  
    
    print (y)

    Output:

    0b1010
    

    Note: The result will always be prefixed with ‘0b’.

  • Python all() Function

    The python all() function accepts an iterable object (such as list,dictionary etc.). It returns True if all items in passed iterable are true, otherwise it returns False. If the iterable object is empty, the all() function returns True.

    Python all() Function Syntax

    It has the following syntax:

    all (iterable)  

    Parameters

    • iterable – The objects which contain the elements i.e. list, tuple and dictionary, etc.

    Return

    • True: If all the elements in an iterable are true.
    • False: If all the elements in an iterable are false..

    Python all() Function Example 1

    Let us take an example to demonstrate the all() function in Python.

    # all values true  
    
    k = [1, 3, 4, 5]  
    
    print(all(k))  
    
      
    
    # all values false  
    
    k = [0, False]  
    
    print(all(k))  
    
      
    
    # one false value  
    
    k = [1, 3, 4, 0]  
    
    print(all(k))  
    
      
    
    # one true value  
    
    k = [0, False, 5]  
    
    print(all(k))  
    
      
    
    # empty iterable  
    
    k = []  
    
    print(all(k))

    Output:

    True
    False
    False
    False
    True
    

    Python all() Function Example 2

    The below example shows how all() works for dictionaries.

    # Both the keys are true  
    
    dict1 = {1: 'True', 2: 'False'}  
    
    print(all(dict1))  
    
      
    
    # One of the key is false  
    
    dict2 = {0: 'True', 1: 'True'}  
    
    print(all(dict2))  
    
      
    
    # Both the keys are false  
    
    dict3 = {0: 'True', False: 0}  
    
    print(all(dict3))  
    
      
    
    # Empty dictionary  
    
    dict4 = {}  
    
    print(all(dict4))  
    
      
    
    # Here the key is actually true because  
    
    #  0 is non-null string rather than a zero  
    
    dict5 = {'0': 'True'}  
    
    print(all(dict5))

    Output:

    True
    False
    False
    True
    True
    

    Python all() Function Example 3

    The below example shows how all() works for tuples.

    # all true values  
    
    t1 = (1, 2, 3, 4, 5)  
    
    print(all(t1))  
    
      
    
    # one false value  
    
    t2 = (0, 1, "Hello")  
    
    print(all(t2))  
    
      
    
    # all false values  
    
    t3 = (0, False , 0)  
    
    print(all(t3))  
    
      
    
    # one true value, all false  
    
    t4 = (True, 0, False)  
    
    print(all(t4))

    Output:

    True
    False
    False
    False
  • Python abs() Function

    The Python abs() function is used to return the absolute value of a number. The absolute function returns a positive number if the original number is negative.

    Syntax:

    abs (num)  

    Parameters

    num: A number whose absolute value is to be returned, such as an integer, a floating number, or a complex number.

    Return: It returns the absolute value of the specified number.

    Python abs() Function Examples

    abs() Function with an Integer Argument

    We can use the abs() function to convert a negative integer into a positive integer.

    Example

    Let’s see an example, where we will see, a negative integer getting converted to a positive integer.

    #integer number    
    
    neg_integer = -100    
    
    #finding the absolute value using the abs() function  
    
    print('Absolute value of -100 is:', abs(neg_integer))

    Output:

    Absolute value of -100 is: 100

    abs() Function with a Floating-Point Number

    Similarly, we can convert a negative floating number into a positive floating number by using the abs() function.

    Example

    Let’s see an example, where we will see, a negative floating-point number getting converted to a positive floating-point number.

    # below is a floating-point number  
    
    float_number = -69.96  
    
    #finding the absolute value using the abs() function  
    
    print("Absolute value of float number", float_number, "is: ",abs(float_number))

    Output:

    Absolute value of float number -69.96 is: 69.96

    abs() Function with a Complex Number

    The complex number consists of a real part and an imaginary part. We can pass the complex number through the abs() function, and we will get an absolute value returned.

    Example

    Let’s see an example, where we will pass a complex number through abs() function and get an absolute value.

    # complex number  
    
    complex_num = (5 + 12j)  
    
    #finding the absolute value using abs() function  
    
    print("Magnitude of complex number", complex_num,"is: ", abs(complex_num))

    Output:

    Magnitude of complex number (5+12j) is: 13.0

    Time-Distance Calculation Using Python abs() Function

    As we already know, the abs() function returns the positive value, and we are also aware that speed, distance, and time can’t be negative. So, we can use the abs() method to calculate the exact time, distance, and speed.

    The formula we are going to use is as follows:

    1. Distance  = Speed * Time  
    2. Time = Distance / Speed  
    3. Speed = Distance / Time  

    Example

    # Functions for basic motion calculations  
    
    # Calculate speed  
    
    def find_speed(distance, hours):  
    
        print("Distance (km):", distance)  
    
        print("Time (hr):", hours)  
    
        speed = distance / hours  
    
        return speed  
    
    # Calculate distance  
    
    def find_distance(rate, hours):  
    
        print("Speed (km/hr):", rate)  
    
        print("Time (hr):", hours)  
    
        distance = rate * hours  
    
        return distance  
    
    # Calculate time  
    
    def find_time(distance, rate):  
    
        print("Distance (km):", distance)  
    
        print("Speed (km/hr):", rate)  
    
        time_required = distance / rate  
    
        return time_required  
    
    # Main Program  
    
    # Using absolute values to avoid negative inputs  
    
    print("Calculated Speed (km/hr):",  
    
          find_speed(abs(46.2), abs(-2.0)))  
    
    print()  
    
    print("Calculated Distance (km):",  
    
          find_distance(abs(-60.5), abs(3.0)))  
    
    print()  
    
    print("Calculated Time (hr):",  
    
          find_time(abs(50.0), abs(5.0)))

    Output:

    Distance (km): 46.2
    Time (hr): 2.0
    Calculated Speed (km/hr): 23.1
    
    Speed (km/hr): 60.5
    Time (hr): 3.0
    Calculated Distance (km): 181.5
    
    Distance (km): 50.0
    Speed (km/hr): 5.0
    Calculated Time (hr): 10.0
    

    Exception of the abs() Function

    We cannot use any other data type except numerical ones with the abs() function.

    Let’s see what happens when we use a string with the abs() function.

    Example

    abs("PythonApp")  

    Output:

    ---------------------------------------------------------------------------
    TypeError Traceback (most recent call last)
    Cell In[8], line 1
    ----> 1 abs("TpoinTech")
    
    TypeError: bad operand type for abs(): 'str'
    

    It clearly defines that the abs() function can’t be used with any other data type, as it would result in an error.

    Conclusion

    The Python abs() function is used to return the absolute value of a number. The absolute function returns a positive number if the original number is negative. The syntax is abs(number). We discussed the abs() function using integer arguments, floating-point numbers, and complex numbers. We also learnt how to do Time-Distance calculation using the Python abs() Function.