Typecasting
Introduction
- Typecasting: The process of converting a value of one data type to another.
- Common conversions:
- Integers to floats
- Floats to integers
- Strings to booleans
- Booleans to strings
- Floats to strings
- Strings to integers
- Integers to booleans
Importance of Typecasting
- User inputs are always strings:
- Convert to integer/float for mathematical operations.
- Truncate decimal portions by casting floats to integers.
Types of Typecasting
- Explicit Typecasting: Manual conversion using specific functions.
- Implicit Typecasting: Automatic conversion during operations.
Explicit Typecasting
- Variables:
- String:
name
- Integer:
age
- Float:
GPA
- Boolean:
student
- Using
type function:
type(variable_name) to determine the data type.
- Example:
print(type(name)) # Output: <class 'str'>
print(type(age)) # Output: <class 'int'>
print(type(GPA)) # Output: <class 'float'>
print(type(student)) # Output: <class 'bool'>
- Converting to Float:
- Example:
age = float(age)
print(age) # Output: 21.0
print(type(age)) # Output: <class 'float'>
- Converting to Integer:
- Example:
GPA = int(GPA)
print(GPA) # Output: 1
- Converting to String:
- Example:
student = str(student)
print(student) # Output: 'True'
print(type(student)) # Output: <class 'str'>
- Converting to Boolean:
- Converting numbers: Any non-zero number is
True, zero is False.
- Example:
age = bool(age)
# Any non-zero number or non-empty string
print(age) # Output: True (if age != 0)
- Checking user input:
- Non-empty string is
True.
- Empty string is
False.
Implicit Typecasting
- Automatic conversion during operations.
- Example:
x = 2
y = 2.0
x = x / y # x is implicitly converted to a float
print(x) # Output: 1.0
print(type(x)) # Output: <class 'float'>
Summary
- Typecasting: Process of converting one data type to another.
- Two types: Explicit (manual) and Implicit (automatic).
- Examples:
- Converting between strings, integers, floats, and booleans.
Reminder
- Explicit Conversion Functions:
int(), float(), str(), bool()
- Implicit conversion occurs during operations such as arithmetic.
If you found this helpful, please like, comment, and subscribe!