Type Conversion in Python
In previous lessons, we learned how Python stores different types of data. Today, we will learn about Type Conversion, which allows us to convert data from one type to another.
Type Conversion is commonly used when working with user input, calculations, and data processing.
What is Type Conversion?
Type Conversion is the process of changing one data type into another.
For example:
- String → Integer
- Integer → Float
- Float → String
Why Type Conversion is Important
Type Conversion helps programmers:
- Process user input
- Perform calculations
- Format output
- Handle different data types
- Prevent errors
Converting String to Integer
The "int()" function converts a value to an integer.
Example
age = "21"
age = int(age)
print(age)
Output
21
Converting Integer to Float
The "float()" function converts a value to a floating-point number.
Example
number = 10
result = float(number)
print(result)
Output
10.0
Converting Number to String
The "str()" function converts a value to a string.
Example
age = 21
text = str(age)
print(text)
Output
21
Converting Float to Integer
Example
number = 12.9
print(int(number))
Output
12
The decimal part is removed.
Checking Data Types
The "type()" function shows the type of a variable.
Example
age = 21
print(type(age))
Output
User Input and Type Conversion
Example
age = int(input("Enter your age: "))
print(age + 5)
Without conversion, Python treats input as text.
Implicit Type Conversion
Python sometimes converts data automatically.
Example
x = 10
y = 2.5
result = x + y
print(result)
Output
12.5
Python automatically converts the integer to a float.
Real-World Applications
Type Conversion is used in:
- Form validation
- Data analysis
- Financial calculations
- Databases
- APIs
Conclusion
Type Conversion is a fundamental Python skill that allows programs to handle different types of data efficiently.
Understanding how and when to convert data types helps developers write more reliable and flexible applications.
Practice converting between strings, integers, floats, and other data types to strengthen your Python programming skills.
Top comments (0)