Welcome!
Join our coding community
Ā© 2024 Ace Coding Academy
Code Examples
Example 1
int(). Converting to Integers.
# Float to Integer
price = 19.99
price_int = int(price) # 19
# String to Integer
age_str = "25"
age = int(age_str) # 25
# Will raise ValueError if the string contains non-numeric characters: int("25a") would fail.
# Boolean to Integer
value = True
value_int = int(value) # 1 (True converts to 1)
another_value = False
another_int = int(another_value) # 0 (False converts to 0)
Example 2
float(). Converting to Floats
# Integer to Float
count = 42
count_float = float(count) # 42.0
# String to Float
temperature = "98.6"
temp_float = float(temperature) # 98.6
# Boolean to Float
is_active = True
active_float = float(is_active) # 1.0
# Similar to integer conversion, True becomes 1.0 and False becomes 0.0
Example 3
str(). Converting to Strings.
# Integer to String
year = 2023
year_str = str(year) # "2023"
# Float to String
pi = 3.14159
pi_str = str(pi) # "3.14159"
# Boolean to String
is_registered = True
status = str(is_registered) # "True"
Example 4
bool(). Converting to Booleans.
# Integer to Boolean
zero = 0
result1 = bool(zero) # False (0 is False)
non_zero = 42
result2 = bool(non_zero) # True (any non-zero number is True)
# String to Boolean
empty = ""
result1 = bool(empty) # False (empty string is False)
non_empty = "Hello"
result2 = bool(non_empty) # True (non-empty string is True)
# Float to Boolean
zero_float = 0.0
result1 = bool(zero_float) # False
small_float = 0.00001
result2 = bool(small_float) # True (any non-zero float is True)