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:
- Implicit Typecasting
- Explicit Typecasting
- Formatted String Literals
- Widening
- Advantages of typecasting
- Disadvantages of typecasting
- Summary
TYPES OF TYPECASTING
Python offers two types of typecasting:
- 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)}’)
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.
- 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'>
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
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?’)
the result will be:
Hello Chidi, how is your day going?
• 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
- 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
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)'
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
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
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)
ADVANTAGES OF TYPECASTING
- Quick and convenient to make use of.
- Ensures values are properly handled.
DISADVANTAGES OF TYPECASTING
- Error-prone from unexpected typecasting results.
- When bugs or errors occur, they are subtle and might be difficult to track down
- 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)