Casting is the process of converting a variable from one data type to another. In Python, you can cast between different data types using built-in functions. This is particularly useful when you need to perform operations that require a specific data type.
Casting Functions
Python provides several built-in functions for casting between data types:
- int() – Converts a value to an integer.
- float() – Converts a value to a floating-point number.
- str() – Converts a value to a string.
Converting to Integer
Use the int()
function to convert a value to an integer. This function can handle strings representing whole numbers, floating-point numbers (by truncating the decimal part), and boolean values.
Explanation of Code:
In the example below, the int()
function is used to convert a string "10"
to an integer 10
, a float 3.14
to an integer 3
, and a boolean True
to an integer 1
.
# Convert string to integer
x = int("10")
print(x) # Output: 10
# Convert float to integer
y = int(3.14)
print(y) # Output: 3
# Convert boolean to integer
z = int(True)
print(z) # Output: 1
Converting to Float
Use the float()
function to convert a value to a floating-point number. This function can handle strings representing numbers and integer values.
Explanation of Code:
In the example above, the float()
function is used to convert a string "3.14"
to a float 3.14
and an integer 10
to a float 10.0
.
# Convert string to float
a = float("3.14")
print(a) # Output: 3.14
# Convert integer to float
b = float(10)
print(b) # Output: 10.0
Converting to String
Use the str()
function to convert a value to a string. This function can handle numbers, booleans, and other data types.
Explanation of Code:
In the example above, the str()
function is used to convert an integer 10
to a string "10"
, a float 3.14
to a string "3.14"
, and a boolean False
to a string "False"
.
# Convert integer to string
c = str(10)
print(c) # Output: "10"
# Convert float to string
d = str(3.14)
print(d) # Output: "3.14"
# Convert boolean to string
e = str(False)
print(e) # Output: "False"
Python Casting Example Code
Explanation of Code:
This program uses a predefined input value instead of prompting the user. The input, which is a string, is converted to a float using the float()
function. The program performs addition and multiplication operations and prints the results. Finally, the results are converted to strings and printed again.
# Predefined input for testing
input_str = "5" # Replace this with any number you want to test
# Convert the input string to a float
number = float(input_str)
# Perform calculations
result_add = number + 10
result_multiply = number * 2
# Print the results
print("Addition result:", result_add)
print("Multiplication result:", result_multiply)
# Convert the results to strings and print
print("Addition result as string:", str(result_add))
print("Multiplication result as string:", str(result_multiply))
