Converting Between Types (int, float, str, bool)

๐Ÿท๏ธ Python Basics: Syntax, Variables, and Types / Type Checking and Type Conversion

When working with data in Python, you'll often need to change a value from one type to another. This is called type conversion or type casting. For example, you might receive a number as text from a configuration file but need to perform math operations on it, or you might need to turn a calculated number into a string for display purposes.

Python makes this straightforward with built-in functions. Let's explore how to convert between the four most common types: int, float, str, and bool.


โš™๏ธ Why Type Conversion Matters

  • Data from external sources (files, APIs, user input) often arrives as strings, even if it looks like a number.
  • Mathematical operations require numeric types (int or float), not strings.
  • Displaying or logging values often requires converting numbers to strings.
  • Boolean values can represent the truthiness of other types, which is useful for condition checks.

๐Ÿ› ๏ธ The Four Conversion Functions

Python provides four key functions for type conversion. Each function takes a value and attempts to return it as the target type.

Conversion Function Target Type Example Input Example Output
int() Integer "42" or 3.14 42 or 3
float() Float "3.14" or 5 3.14 or 5.0
str() String 42 or True "42" or "True"
bool() Boolean 1 or "" True or False

๐Ÿ”„ Converting to Integer (int())

The int() function converts a value to an integer. It works with floats (truncating the decimal part) and strings that represent whole numbers.

  • Converting a float to int removes the decimal portion: int(3.99) gives 3, not 4.
  • Converting a string to int requires the string to contain a valid integer: int("42") works, but int("3.14") will raise an error.
  • You can also convert a boolean: int(True) gives 1, and int(False) gives 0.

๐Ÿ”„ Converting to Float (float())

The float() function converts a value to a floating-point number. It handles integers, strings containing decimal numbers, and booleans.

  • Converting an integer to float adds a decimal point: float(5) gives 5.0.
  • Converting a string to float works with decimal strings: float("3.14") gives 3.14.
  • Converting a boolean: float(True) gives 1.0, and float(False) gives 0.0.

๐Ÿ”„ Converting to String (str())

The str() function converts any value to its string representation. This is the safest conversion because almost everything can be turned into a string.

  • Converting numbers: str(42) gives "42", and str(3.14) gives "3.14".
  • Converting booleans: str(True) gives "True", and str(False) gives "False".
  • This is especially useful when combining values in print statements or log messages.

๐Ÿ”„ Converting to Boolean (bool())

The bool() function converts a value to True or False based on its "truthiness." This is a core concept in Python.

  • Values that convert to False: 0, 0.0, "" (empty string), None, empty collections like [] or {}.
  • Almost everything else converts to True: any non-zero number, any non-empty string, any populated collection.
  • Examples: bool(1) gives True, bool("hello") gives True, bool(0) gives False, bool("") gives False.

๐Ÿ•ต๏ธ Common Pitfalls and Gotchas

  • String to integer conversion fails if the string contains non-numeric characters. For example, int("42abc") raises a ValueError.
  • Float to integer truncates, it does not round. Use the round() function if you need rounding before conversion.
  • Boolean conversion of strings is not based on the word "true" or "false". The string "False" is non-empty, so bool("False") actually gives True.
  • Loss of precision occurs when converting between float and int. The decimal part is discarded, not rounded.

๐Ÿงช Practical Examples in Context

  • Reading a port number from a config file: The value comes as "8080" (string), so you convert it with int("8080") to use it in socket binding.
  • Calculating a percentage: You have 3 successes out of 10 attempts. To get a decimal result, convert one to float: float(3) / 10 gives 0.3.
  • Logging a result: After a calculation, you combine the result with text: "The answer is " + str(answer).
  • Checking if a value exists: Use bool(user_input) to see if a user provided any input at all.

๐Ÿ“Š Quick Reference Table

Starting Type To Int To Float To String To Bool
int (e.g., 42) โ€” float(42) โ†’ 42.0 str(42) โ†’ "42" bool(42) โ†’ True
float (e.g., 3.14) int(3.14) โ†’ 3 โ€” str(3.14) โ†’ "3.14" bool(3.14) โ†’ True
str (e.g., "42") int("42") โ†’ 42 float("42") โ†’ 42.0 โ€” bool("42") โ†’ True
str (e.g., "") โŒ Error โŒ Error โ€” bool("") โ†’ False
bool (e.g., True) int(True) โ†’ 1 float(True) โ†’ 1.0 str(True) โ†’ "True" โ€”

โœ… Key Takeaways

  • Use int(), float(), str(), and bool() to convert between types explicitly.
  • Always validate or handle errors when converting strings to numbers, especially from external sources.
  • Remember that bool() follows truthiness rules, not literal string matching.
  • Type conversion is a fundamental skill for handling data from different sources and preparing it for operations or output.

Type conversion lets you change a value from one data type to another, such as turning a string of digits into a number for calculations.

๐Ÿ”ง Example 1: Converting an integer to a float

This shows how to turn a whole number into a decimal number.

score = 42
score_float = float(score)
print(score_float)

๐Ÿ“ค Output: 42.0


๐Ÿ”ง Example 2: Converting a float to an integer

This shows how to truncate a decimal number to a whole number, removing the decimal part.

temperature = 98.7
temp_int = int(temperature)
print(temp_int)

๐Ÿ“ค Output: 98


๐Ÿ”ง Example 3: Converting a number to a string

This shows how to turn a numeric value into text so it can be combined with other text.

count = 5
count_str = str(count)
print("The count is " + count_str)

๐Ÿ“ค Output: The count is 5


๐Ÿ”ง Example 4: Converting a string to an integer

This shows how to take a string that contains digits and turn it into a number for math operations.

user_input = "100"
user_number = int(user_input)
result = user_number + 50
print(result)

๐Ÿ“ค Output: 150


๐Ÿ”ง Example 5: Converting values to boolean

This shows how Python evaluates different values as True or False when converted to boolean.

print(bool(1))
print(bool(0))
print(bool("hello"))
print(bool(""))
print(bool(3.14))

๐Ÿ“ค Output: True
๐Ÿ“ค Output: False
๐Ÿ“ค Output: True
๐Ÿ“ค Output: False
๐Ÿ“ค Output: True


๐Ÿ”ง Example 6: Converting a boolean to an integer

This shows how True becomes 1 and False becomes 0 when converted to an integer.

flag_true = True
flag_false = False
print(int(flag_true))
print(int(flag_false))

๐Ÿ“ค Output: 1
๐Ÿ“ค Output: 0


๐Ÿ”ง Example 7: Converting between types in a practical calculation

This shows a real-world scenario where user input (a string) must be converted to a number for a calculation.

price_str = "19.99"
quantity_str = "3"
price = float(price_str)
quantity = int(quantity_str)
total = price * quantity
print(total)

๐Ÿ“ค Output: 59.97


Comparison Table: Common Type Conversions

Source Type Target Type Function Example Result
int float float() float(7) 7.0
float int int() int(7.9) 7
int str str() str(42) "42"
float str str() str(3.14) "3.14"
str (digits) int int() int("100") 100
str (decimal) float float() float("2.5") 2.5
any type bool bool() bool(0) False
bool int int() int(True) 1

When working with data in Python, you'll often need to change a value from one type to another. This is called type conversion or type casting. For example, you might receive a number as text from a configuration file but need to perform math operations on it, or you might need to turn a calculated number into a string for display purposes.

Python makes this straightforward with built-in functions. Let's explore how to convert between the four most common types: int, float, str, and bool.


โš™๏ธ Why Type Conversion Matters

  • Data from external sources (files, APIs, user input) often arrives as strings, even if it looks like a number.
  • Mathematical operations require numeric types (int or float), not strings.
  • Displaying or logging values often requires converting numbers to strings.
  • Boolean values can represent the truthiness of other types, which is useful for condition checks.

๐Ÿ› ๏ธ The Four Conversion Functions

Python provides four key functions for type conversion. Each function takes a value and attempts to return it as the target type.

Conversion Function Target Type Example Input Example Output
int() Integer "42" or 3.14 42 or 3
float() Float "3.14" or 5 3.14 or 5.0
str() String 42 or True "42" or "True"
bool() Boolean 1 or "" True or False

๐Ÿ”„ Converting to Integer (int())

The int() function converts a value to an integer. It works with floats (truncating the decimal part) and strings that represent whole numbers.

  • Converting a float to int removes the decimal portion: int(3.99) gives 3, not 4.
  • Converting a string to int requires the string to contain a valid integer: int("42") works, but int("3.14") will raise an error.
  • You can also convert a boolean: int(True) gives 1, and int(False) gives 0.

๐Ÿ”„ Converting to Float (float())

The float() function converts a value to a floating-point number. It handles integers, strings containing decimal numbers, and booleans.

  • Converting an integer to float adds a decimal point: float(5) gives 5.0.
  • Converting a string to float works with decimal strings: float("3.14") gives 3.14.
  • Converting a boolean: float(True) gives 1.0, and float(False) gives 0.0.

๐Ÿ”„ Converting to String (str())

The str() function converts any value to its string representation. This is the safest conversion because almost everything can be turned into a string.

  • Converting numbers: str(42) gives "42", and str(3.14) gives "3.14".
  • Converting booleans: str(True) gives "True", and str(False) gives "False".
  • This is especially useful when combining values in print statements or log messages.

๐Ÿ”„ Converting to Boolean (bool())

The bool() function converts a value to True or False based on its "truthiness." This is a core concept in Python.

  • Values that convert to False: 0, 0.0, "" (empty string), None, empty collections like [] or {}.
  • Almost everything else converts to True: any non-zero number, any non-empty string, any populated collection.
  • Examples: bool(1) gives True, bool("hello") gives True, bool(0) gives False, bool("") gives False.

๐Ÿ•ต๏ธ Common Pitfalls and Gotchas

  • String to integer conversion fails if the string contains non-numeric characters. For example, int("42abc") raises a ValueError.
  • Float to integer truncates, it does not round. Use the round() function if you need rounding before conversion.
  • Boolean conversion of strings is not based on the word "true" or "false". The string "False" is non-empty, so bool("False") actually gives True.
  • Loss of precision occurs when converting between float and int. The decimal part is discarded, not rounded.

๐Ÿงช Practical Examples in Context

  • Reading a port number from a config file: The value comes as "8080" (string), so you convert it with int("8080") to use it in socket binding.
  • Calculating a percentage: You have 3 successes out of 10 attempts. To get a decimal result, convert one to float: float(3) / 10 gives 0.3.
  • Logging a result: After a calculation, you combine the result with text: "The answer is " + str(answer).
  • Checking if a value exists: Use bool(user_input) to see if a user provided any input at all.

๐Ÿ“Š Quick Reference Table

Starting Type To Int To Float To String To Bool
int (e.g., 42) โ€” float(42) โ†’ 42.0 str(42) โ†’ "42" bool(42) โ†’ True
float (e.g., 3.14) int(3.14) โ†’ 3 โ€” str(3.14) โ†’ "3.14" bool(3.14) โ†’ True
str (e.g., "42") int("42") โ†’ 42 float("42") โ†’ 42.0 โ€” bool("42") โ†’ True
str (e.g., "") โŒ Error โŒ Error โ€” bool("") โ†’ False
bool (e.g., True) int(True) โ†’ 1 float(True) โ†’ 1.0 str(True) โ†’ "True" โ€”

โœ… Key Takeaways

  • Use int(), float(), str(), and bool() to convert between types explicitly.
  • Always validate or handle errors when converting strings to numbers, especially from external sources.
  • Remember that bool() follows truthiness rules, not literal string matching.
  • Type conversion is a fundamental skill for handling data from different sources and preparing it for operations or output.

Interactive Views

You are currently in ๐Ÿ“š All-in-One mode. Use the tabs at the top to switch to ๐Ÿ“– Theory Only or ๐Ÿ’ป Code Only views.

Type conversion lets you change a value from one data type to another, such as turning a string of digits into a number for calculations.

๐Ÿ”ง Example 1: Converting an integer to a float

This shows how to turn a whole number into a decimal number.

score = 42
score_float = float(score)
print(score_float)

๐Ÿ“ค Output: 42.0


๐Ÿ”ง Example 2: Converting a float to an integer

This shows how to truncate a decimal number to a whole number, removing the decimal part.

temperature = 98.7
temp_int = int(temperature)
print(temp_int)

๐Ÿ“ค Output: 98


๐Ÿ”ง Example 3: Converting a number to a string

This shows how to turn a numeric value into text so it can be combined with other text.

count = 5
count_str = str(count)
print("The count is " + count_str)

๐Ÿ“ค Output: The count is 5


๐Ÿ”ง Example 4: Converting a string to an integer

This shows how to take a string that contains digits and turn it into a number for math operations.

user_input = "100"
user_number = int(user_input)
result = user_number + 50
print(result)

๐Ÿ“ค Output: 150


๐Ÿ”ง Example 5: Converting values to boolean

This shows how Python evaluates different values as True or False when converted to boolean.

print(bool(1))
print(bool(0))
print(bool("hello"))
print(bool(""))
print(bool(3.14))

๐Ÿ“ค Output: True
๐Ÿ“ค Output: False
๐Ÿ“ค Output: True
๐Ÿ“ค Output: False
๐Ÿ“ค Output: True


๐Ÿ”ง Example 6: Converting a boolean to an integer

This shows how True becomes 1 and False becomes 0 when converted to an integer.

flag_true = True
flag_false = False
print(int(flag_true))
print(int(flag_false))

๐Ÿ“ค Output: 1
๐Ÿ“ค Output: 0


๐Ÿ”ง Example 7: Converting between types in a practical calculation

This shows a real-world scenario where user input (a string) must be converted to a number for a calculation.

price_str = "19.99"
quantity_str = "3"
price = float(price_str)
quantity = int(quantity_str)
total = price * quantity
print(total)

๐Ÿ“ค Output: 59.97


Comparison Table: Common Type Conversions

Source Type Target Type Function Example Result
int float float() float(7) 7.0
float int int() int(7.9) 7
int str str() str(42) "42"
float str str() str(3.14) "3.14"
str (digits) int int() int("100") 100
str (decimal) float float() float("2.5") 2.5
any type bool bool() bool(0) False
bool int int() int(True) 1