what are python Python Casting briefly describe and give examples
what are
python Python Casting
Python casting is the process of converting one data type to
another data type. For example, you can convert an integer to a floating point
number, or a string to an integer.
In Python, you can use the following casting functions:
- int():
converts a number or a string to an integer.
- float():
converts a number or a string to a floating point number.
- str():
converts a number or a list to a string.
- bool():
converts a value to a Boolean (True or False).
Examples:
x = int(5.5) # x will be 5
y = float(10) # y will be 10.0
z = str(True) # z will be
"True"
a = bool(0) # a will be False
It's also possible to do casting by just assigning the value
of one type to a variable of another type, this is called Implicit casting
a = 5.5
b = int(a) # b will be 5
c = "5"
d = int(c) # d will be 5
It's important to note that some casting may lead to loss of
data, for example casting a float to int will truncate the decimal part,
casting a long string to int will only take the first number it finds, casting
a complex number to float will only take the real part.
It's also important to note that casting a non-numeric
string to an int or float will raise an exception.
Comments
Post a Comment