DEV Community

Chidi E. Egwu
Chidi E. Egwu

Posted on • Updated on

Understanding Typecasting Using Python

Python is a dynamic programming language, which means it performs type checking at runtime, which opens the door to more errors at runtime and a higher likelihood of shipping code with errors. While typecasting is an essential part of any dynamic programming language, type conversion is often used with little recognition or understanding of its operations.
Typecasting can be defined as the conversation or reassignment of datatypes, and it is known by various names depending on the author's preference or the programming language in use.
Typecasting can also be referred to as type coercion, type conversion, and type juggling.

The topics to be covered by this article includes:

  1. Implicit Typecasting
  2. Explicit Typecasting
  3. Formatted String Literals
  4. Widening
  5. Advantages of typecasting
  6. Disadvantages of typecasting
  7. Summary

TYPES OF TYPECASTING
Python offers two types of typecasting:

  1. Implicit Typecasting: This is an automatic type conversation; conversion without the need for direct user interaction; the conversion decision is handled by the Python interpreter.

Example:

number = 22
float_number = 22.8
new_number = number + float_number
print(f‘number datatype {type(number)}’)
print(f‘number datatype {type(float_number)}’)
print(f‘number datatype {type(new_number)}’)
Enter fullscreen mode Exit fullscreen mode

We have three variables declared, number houses an integer, float_number houses a float or decimal point integer, and new_number is used to store the sum of float_number and number. When the type method is called against all variables they return their variable type, but you will notice that the new_number variable returns a floating-point value, this is because the interpreter carries out implicit typecasting and
converts the number variable value to float before carrying out the summation. This is a result of python converting smaller datatype to large datatype to prevent data loss.

  1. Explicit Typecasting: This refers to the direct conversion (casting) of object values through the use of predefined methods such as:
  • int()
  • float()
  • str()
  • complex()
  • bool()

INTEGER METHOD: The Int() method returns an integer from numbers and strings with base -10 values. In addition, complex values cannot be converted to integers.

Example 1:

variable_1 = 22.2
variable_2 = int(variable_1)
print(f’data type for variable_1 before casting: {type(variable_1}’)
print(f’data type for variable_2 after casting {type(int(variable_2)}’)
data type for variable_1 before casting <class float>
data type for variable_2 after casting: <class 'int'>
Enter fullscreen mode Exit fullscreen mode

If we print variable_2, we will notice that the float has been converted (cast) to an integer.

Example 2:

>> print(int(20.22) 
20
Enter fullscreen mode Exit fullscreen mode

NOTE:
It is worth explaining the following points:

f(f-strings) – In Python 3.6, the "formatted string literal" was introduced as a new way to format strings by replacing variables or values within the curly bracket, as shown above, and below.
Example:

name = “Chidi”
print(f’Hello {name}, how is your day going?’)
Enter fullscreen mode Exit fullscreen mode

the result will be:

Hello Chidi, how is your day going?
Enter fullscreen mode Exit fullscreen mode

Widening – Python will automatically convert a smaller datatype to a datatype that can accommodate more values of the previous or original datatype during this process. For example, you can convert an int to a float or a char to a string.

FLOAT METHOD: This method converts values to floating decimal points; values passed as strings must be in base -10.

>>> print(float(20)) 
20.0
Enter fullscreen mode Exit fullscreen mode
  • Python also supports Narrowing (not automatically), which is the conversion of larger datatypes to smaller datatypes. Typically, this results in data loss. Example
>>> print(int(20.22) 
20
>>> float(1) 
1.0
Enter fullscreen mode Exit fullscreen mode

STRING METHOD: this converts any data type into a string.

>>> str(1)
'1'
>>> str(a)
'1'
>>> str(True)
'True'
>>> str(False)
'False'
>>> str(50+112j)
'(50+112j)'
Enter fullscreen mode Exit fullscreen mode

BOOLEAN METHOD: It converts any data type to a Boolean data type and returns True for all values except those listed below, which return False.

>>> bool(False)
False
>>> bool(None)
False
>>> bool(0)
False
>>> bool("")
False
>>> bool(())
False
>>> bool([])
False
>>> bool({})
False
Enter fullscreen mode Exit fullscreen mode

COMPLEX METHOD: The complex method returns a complex number when given a number. The complex method can take two numbers, a real number first an imaginary number second, then returns a complex number. Its applications include physics and
mathematical calculations, to name a few.
Syntax: complex([real[, imag]])
If the real or imag is omitted the default value of 0 is used.

>>> complex(2)
(2+0j)
>>> complex()
0j
Enter fullscreen mode Exit fullscreen mode

When a string is passed to a complex method, the imaginary values do not need to be passed, but the values should be in the form 'real+imag'. The default imaginary values are used if a string value is passed, as shown below.

>>> complex('1')
(1+0j)
Enter fullscreen mode Exit fullscreen mode

ADVANTAGES OF TYPECASTING

  1. Quick and convenient to make use of.
  2. Ensures values are properly handled.

DISADVANTAGES OF TYPECASTING

  1. Error-prone from unexpected typecasting results.
  2. When bugs or errors occur, they are subtle and might be difficult to track down
  3. Option of complex types

SUMMARY
I believe I have successfully guided you through everything you need to know to understand or begin using typecasting in Python. While this knowledge can be applied to other programming languages, reading should be accompanied by practice; experiment with codes and purposefully start using typecasting in your code.

Top comments (0)