Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags


How to do typecasting in Python


Python is an object-oriented coding language used to code, and runs any application. The Python language has many types and is divided into many sub-topics. One of the most widely-used topics in Python language is typecasting.


Typecasting is a process in which data is converted from one to another. Typecasting is divided into two different types. They are:

  • Implicit typecasting
  • Explicit typecasting

These two methods include typecasting based on automatic and manual conversions of data into types.

Implicit typecasting

Implicit typecasting is an automatic process where one data type is converted to another using a function.

num_int = 123
num_flo = 1.23

num_new = num_int + num_flo

print("datatype of num_int:",type(num_int))
print("datatype of num_flo:",type(num_flo))

print("Value of num_new:",num_new)
print("datatype of num_new:",type(num_new))

Explicit typecasting

Explicit typecasting is a manual data conversion process, so the type castings are carried out by Python literalssuch as int(), float(), and str().

  • int() constructs an integer number from an integer literal, a float literal, by rounding down to the previous whole number, or a string literal provides the string that represents a whole number.
  • float() constructs a float number from an integer literal, a float literal, or a string literal (providing that the the string represents a float or an integer).
  • str() constructs a string from a wide variety of data types including strings, integer literals, and float literals.
#Programme for explicit function.
num_int = 123
num_str = "456"

print("Data type of num_int:",type(num_int))
print("Data type of num_str before Type Casting:",type(num_str))

num_str = int(num_str)
print("Data type of num_str after Type Casting:",type(num_str))

num_sum = num_int + num_str

print("Sum of num_int and num_str:",num_sum)
print("Data type of the sum:",type(num_sum))



View all Courses

Keep Exploring