Page 100 - Information_Practice_Fliipbook_Class11
P. 100

Note that sum is a float value, even though num is of type int.

        4.7.2 Explicit Type Conversion

        Explicit conversion, also called typecasting, takes place when the programmer gives such instruction. The syntax for
        explicit conversion is:
        <transform_type> (<expression>)
        It would convert the expression to transform_type. For example,
         >>> percentile = 99.99
         >>> int(percentile)
              99
        Consider program 4.1 given below.

         Program 4.1

        # Objective: To accept a number and display its square.
        num = input("Enter a number : ")
        square  = num * num
        print("The square of the entered number is ", square)
        Output:
        Enter a number : 5
        Traceback (most recent call last):
          File "C:\Users\ORANGE\7_1_square.py", line 2, in <module>
            square  = num * num
        TypeError: can't multiply sequence by non-int of type 'str'
        The execution of program 4.1 generates an error because input() returns a string value, and the binary operation
        multiplication cannot be performed on strings. So, execution of the statement, square = num * num, results in
        error. Of course, if the data type of the value being returned by input() is converted to an integer prior to assigning
        it to num using int(), then an arithmetic operation can be performed on num. The revised version of program 4.1 is
        given below. It correctly displays the square of the number 5 as output.
        Program 4.1_revised

        # Objective: To accept a number and display its square.
        num = int(input("Enter a number: "))  # explicit type conversion
        square = num * num
        print("The square of the entered number is ", square)

        Output:
        Enter a number : 5
        The square of the entered number is 25
        Table 4.8 lists some of the functions that can be used for explicit type conversion in Python. In this table, the name
        num denotes a numeric object.

                                     Table 4.8: Functions for explicit type conversion in Python
                 Function            Description

                 int(num)            Converts num to an integer
                 float(num)          Converts num to a floating-point number
                 str(num)            Converts num to a string on which no arithmetic calculations can be done

                 chr(num)            Converts num to str, if in suitable range
                 ord()               Transforms an ASCII character to its ASCII code and a Unicode character to
                                     its Unicode.

          86   Touchpad Informatics Practices-XI
   95   96   97   98   99   100   101   102   103   104   105