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:
These two methods include typecasting based on automatic and manual conversions of data into types.
Implicit typecasting is an automatic process where one data type is converted to another using a function.
num_int = 123num_flo = 1.23num_new = num_int + num_floprint("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 is a manual data conversion process, so the
type castings are carried out by 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 = 123num_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_strprint("Sum of num_int and num_str:",num_sum)print("Data type of the sum:",type(num_sum))