Type Casting in Python
What is Type Casting? Type casting means converting one data type to another. For example, converting a number to a string or a string to a number. Python provides built-in functions to do this.
Why Use Type Casting?
Sometimes, you need to change the type of a value to perform certain operations. For example:
- Joining text and numbers: You cannot directly combine a number with text, so you need to convert the number to a string.
- Mathematical operations: If a number is stored as a string, you must convert it to an integer or float to perform calculations.
Common Type Casting Functions
Here are the most commonly used type casting functions in Python:
int()
: Converts a value to an integer.float()
: Converts a value to a floating-point number (decimal).str()
: Converts a value to a string.
Examples of Type Casting
Let's look at some examples to understand how type casting works:
1. Converting Numbers to Strings
When you want to combine a number with text, you need to convert the number to a string first:
# Example 1: Number to String age = 25 # Convert age to a string and combine it with text message = "I am " + str(age) + " years old." print(message)
Output: I am 25 years old.
2. Converting Strings to Numbers
When you need to perform calculations with user input, you can convert a string to a number:
# Example 2: String to Integer user_input = "5" # Input is always a string # Convert the string to an integer number = int(user_input) # Perform a calculation result = number * 2 print("The result is:", result)
Output: The result is: 10
3. Converting Integers to Floats
If you want more precise calculations, you can convert integers to floating-point numbers:
# Example 3: Integer to Float number = 10 # Convert the integer to a float float_number = float(number) print("The float value is:", float_number)
Output: The float value is: 10.0
Important Note
You cannot directly add a string and an integer. It will cause an error. Example:
# This will cause an error age = 25 message = "I am " + age + " years old." print(message)
Error: TypeError: can only concatenate str (not "int") to str
To fix this, convert age
to a string using str(age)
.
Practice Example
Here’s a small program to practice type casting:
# Practice: Combine user input with type casting name = input("Enter your name: ") age = input("Enter your age: ") # Input is a string # Convert age to an integer age_next_year = int(age) + 1 # Display the message print("Hello, " + name + "! Next year, you will be " + str(age_next_year) + " years old.")
Example Output:
Enter your name: John
Enter your age: 25
Hello, John! Next year, you will be 26 years old.