Learn what type casting in Python is, why it's used, and how to convert between data types like int, float, str, and bool with examples. Master explicit & implicit type conversion.
Type casting (also called type conversion) is the process of converting a value from one data type to another in Python. Python is dynamically typed, but sometimes you need to explicitly convert between types to perform certain operations or meet function requirements.
# Integer conversion
x = int(3.7) # 3 (float to int)
y = int("42") # 42 (string to int)
# Float conversion
a = float(5) # 5.0 (int to float)
b = float("3.14") # 3.14 (string to float)
# String conversion
s = str(100) # "100" (int to string)
t = str(7.5) # "7.5" (float to string)
# Boolean conversion
bool(0) # False (int to bool)
bool(1) # True
bool("") # False (empty string to bool)
bool("hello") # True (non-empty string to bool)
3 + 4.5
becomes 3.0 + 4.5
)int()
, float()
, str()
# User input (always comes as string)
age = input("Enter your age: ") # "25" (string)
age_num = int(age) # 25 (integer)
# Mathematical operations
result = float(5) / 2 # 2.5 instead of 2
# String formatting
price = 19.99
print("The price is $" + str(price))
# Data validation
user_input = "123"
if user_input.isdigit():
value = int(user_input)
else:
print("Invalid number")
Type casting is essential when you need to ensure your data is in the correct format for operations, storage, or display purposes.
Write a Python program that:
str()
function.Example Input:
Enter a number: 100
Expected Output:
Your number is: 100
Write a Python program that:
"123"
).int()
function.Example Input:
Enter a number as a string: 50
Expected Output:
Double the number: 100
Write a Python program that:
oct()
and hexadecimal using hex()
.Example Input:
Enter a number: 255
Expected Output:
Octal: 0o377
Hexadecimal: 0xff
Write a Python program that:
int(value, base)
.Example Input:
Enter an octal number: 0o377
Enter a hexadecimal number: 0xff
Expected Output:
Octal to Integer: 255
Hexadecimal to Integer: 255