Conversion or Casting
What Is Type Conversion or Casting?
- Type conversion is the process of converting a value from one datatype to another. This is useful in many scenarios, such as when reading user input, which is often in string format, and converting it to an integer or a floating-point number to perform calculations.
Why Use Type Conversion?
- Type conversion allows you to manipulate and use data in different formats effectively, enabling you to perform various operations that might not be possible with the original datatype.
How to Cast in Python:
- Casting is done using constructor functions:
int() - Converts a value to an integer:
pythonx = int(1) # x will be 1 y = int(2.88) # y will be 2 z = int("3") # z will be 3 print(x) print(y) print(z)- Output:
1 - Output:
2 - Output:
3
- Output:
float() - Converts a value to a float:
pythonx = float(1) # x will be 1.0 y = float(2.8) # y will be 2.8 z = float("3") # z will be 3.0 w = float("4.2") # w will be 4.2 print(x) print(y) print(z) print(w)- Output:
1.0 - Output:
2.8 - Output:
3.0 - Output:
4.2
- Output:
str() - Converts a value to a string:
pythonx = str("s1") # x will be 's1' y = str(2) # y will be '2' z = str(3.0) # z will be '3.0' print(x) print(y) print(z)- Output:
s1 - Output:
2 - Output:
3.0
- Output:
Summary:
- Casting allows you to convert variables from one type to another, ensuring you can work with the data in the format you need. Practice using
int(),float(), andstr()to become proficient in casting! - Type conversion is a crucial skill in Python programming, enabling you to work with data in various formats. Practice converting between different types to understand how to manipulate and use data effectively!