Advertisement

Type Casting in Python

Type Casting in Python


In Python, type casting is the process of converting one data type to another. This is done using either the int(), float(), or str() functions.


Type casting in python


For example:

x = int(5.6) # x will be 5 
y = float(3) # y will be 3.0 
z = str(20) # z will be '20'

You can also use these functions to convert variables from one type to another.


For example:

x = 5 y = float(x) # y will be 5.0 
z = str(x) # z will be '5'


You can also use the int() function to convert a string representation of a number to an integer, as long as the string only contains numeric characters. For example:


x = int('5') # x will be 5 
y = int('5.6') # this will cause an error because '5.6' is not a valid integer


It's important to note that you can only convert a value to a type that it is compatible with. 

For example, you can't convert the string 'hello' to an integer because it is not a numeric value.


Post a Comment

0 Comments