Blog

  • Python eval() Function

    In Python, the eval() function is an underlying Python function that evaluates a string as a Python expression. It takes a single parameter, which is a string that addresses a Python expression. The eval() function then evaluates this expression and returns the outcome. The python eval() function parses the expression passed to it and runs python expression(code) within the program.

    The eval() function is in many cases used in Python to execute dynamically produced code. For instance, on the off chance that you have a string that contains a numerical expression, you can use the eval() function to evaluate that expression and return the outcome.

    Python eval() Function Syntax

    It has the following syntax:

    eval(expression, globals, locals)  

    Parameters

    • expression: The string is parsed and evaluated as a Python expression.
    • globals (optional): A dictionary that specifies the available global methods and variables.
    • locals (optional): It is an another dictionary which is commonly used for mapping type in Python.

    Return

    It returns the result evaluated from the expression.

    Different Examples for Python eval() Function

    Here, we are going to discuss several examples of Python eval() Function.

    Python eval() Function Example 1

    The below example shows the working of the eval() function in Python.

    # Python program for eval() function  
    
    # Declaring variables  
    
    x = 15  
    
    y = 25  
    
    result = eval('x + y')  
    
    # print result  
    
    print(result)

    Output:

    40
    

    Explanation:

    In this example, we have defined two variables x and y and introduced them with the values 15 and 25, separately. We then, at that point, call the eval() function with the string ‘x + y’ as the expression. The eval() function evaluates this expression as the sum of the values of x and y, which is 40. At last, we print the outcome using the print() function.

    Python eval() Function Example 2

    As well as accepting a single parameter that addresses a Python expression as a string, the eval() function likewise permits us to determine the context where the expression ought to be evaluated. You can use the locals and globals contentions to pass in dictionaries references that address the local and global namespaces, separately.

    Here is an example that shows the way that you can use locals and globals with the eval() function:

    # Python program for eval() function  
    
    x = 5  
    
    y = 15  
    
    expr = 'x + y'  
    
    result = eval(expr, globals(), locals())  
    
    print(result)

    Output:

    20
    

    Explanation:

    In this example, we have defined two variables x and y, and a string expr that contains a Python expression. We then call the eval() function with the globals() and locals() functions as contentions, which address the global and local namespaces, separately. The eval() function evaluates the expression ‘x + y’ utilizing the globals() and locals() namespaces and returns the outcome, which is 20.

    Python eval() Function Example 3

    We can likewise use the locals() and globals() dictionaries to assign values to variables in the expression that you are evaluating. Here is an example:

    # Python program for eval() function  
    
    x = 20  
    
    y = 30  
    
    expr = 'x + y + z'  
    
    result = eval(expr, globals(), {'z': 50})  
    
    print(result)

    Output:

    100
    

    Explanation:

    In this example, we have defined two variables x and y, a string expr that contains a Python expression, and a dictionary reference that contains the worth of the variable z. We then, at that point, call the eval() function with the globals() and locals() functions as contentions. The eval() function evaluates the expression ‘x + y + z’ utilizing the globals() and locals() namespaces and returns the outcome, which is 100.

    Utilizing locals() and globals() with the eval() function can be useful when you want to evaluate an expression in a particular context, like a function or class. Be that as it may, it means quite a bit to use these contentions with caution, as they can permit us to change variables unexpectedly.

    Conclusion

    The eval() function is an amazing asset in Python that permits us to execute dynamically produced code and perform complex numerical computations. In many cases, it is best to use the eval() function with caution and know about its possible security, execution, and maintenance issues.

  • Python bytearray() Function

    The python bytearray() function returns a bytearray object and can convert objects into bytearray objects, or create an empty bytearray object of the specified size.

    Python bytearray() Function Syntax

    It has the following syntax:

    bytearray(x, encoding, error)  

    Parameters

    • x (optional): It is the source that initializes the array of bytes.
    • encoding (optional): It is an encoding of the string.
    • error (optional): It takes action when the encoding fails.

    Return

    It returns an array of bytes.

    Different Examples for Python bytearray() Function

    Here, we are going to discuss several examples for Python bytearray() Function.

    Python bytearray() Function Example 1

    The below example shows an array of bytes from a string:

    string = "Python is programming language."  
    
      
    
    # string with encoding 'utf-8'  
    
    arr = bytearray(string, 'utf-8')  
    
    print(arr)

    Output:

    bytearray(b'Python is programming language.')
    

    Explanation: In the above example, we take a variable that contains a string value and convert it into a bytearray object.

    Python bytearray() Function Example 2

    The below example shows an array of bytes of given integer size:

    size = 5  
    
      
    
    arr = bytearray(size)  
    
    print(arr)

    Output:

    bytearray(b'\x00\x00\x00\x00\x00')
    

    Python bytearray() Function Example 3

    The below example shows an array of bytes from an iterable list:

    rList = [2, 3, 4, 5, 6]  
    
      
    
    arr = bytearray(rList)  
    
    print(arr)

    Output:

    bytearray(b'\x02\x03\x04\x05\x06')
  • Python ascii() Function

    The python ascii() function returns a string containing a printable representation of an object and escapes the non-ASCII characters in the string using \x, \u or \U escapes.

    Python ascii() Function Syntax

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

    ascii(object)  

    Parameters

    object: It takes an object like strings, list etc.

    Return

    It returns a readable version of an object and replaces none-ascii characters with the escape character.

    Python ascii() Function Example

    Here, we are going to discuss different examples for Python ascii() Function works in Python.

    normalText = 'Python is interesting'  
    
    print(ascii(normalText))  
    
      
    
    otherText = 'Pyth�n is interesting'  
    
    print(ascii(otherText))  
    
      
    
    print('Pyth\xf6n is interesting')

    Output:

    'Python is interesting'
    'Pyth\xf6n is interesting'
    Pyth�n is interesting
    

    Explanation: In the above example, variables such as normalText, and otherText contain the string values, and returns ascii value of a particular variable.

  • 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.