SECTION 1
Historical Context & Motivation
Every programming language needs a way to represent different kinds of data — numbers, text, true/false values — and at some point, your program will need to convert one kind into another. Early languages like FORTRAN and C required programmers to be very explicit about data types, and mixing them often caused silent bugs or crashes. Type conversion (also called type casting) is the process of changing a value from one data type to another. Python makes this process straightforward by giving you built-in functions like int(), float(), str(), and bool().
1957 • FORTRAN and Strict Typing
1972 • C Introduces Casting
(int) 3.14. This was powerful but error-prone.1991 • Python Is Released
2008 • Python 3 and Clean Conversions
So why does type conversion matter to you? Consider a common scenario: you use input() to ask a user for their age. Python returns that input as a string, even if the user typed a number. If you try to do math with that string, Python raises an error. Type conversion solves this problem by letting you transform "17" into the integer 17.
SECTION 2
Core Principles & Definitions
Before diving into examples, you should understand a few foundational ideas about how Python handles types and conversions. Python is a dynamically typed language, which means you don't have to declare a variable's type when you create it — Python figures it out from the value you assign. However, Python is also strongly typed, meaning it won't automatically convert between incompatible types for you. You need to explicitly tell Python when you want a conversion to happen.
Explicit Conversion
int() or str() to change a value's type. This is also called type casting.Implicit Conversion
int to a float automatically produces a float. This is called type coercion.Data Loss Is Possible
3.99 to an integer gives 3, not 4. The decimal part is simply truncated (chopped off), not rounded.Not Every Conversion Works
"hello" to an integer will cause a ValueError. The string must represent a valid number for numeric conversions to succeed.KEY TAKEAWAY
int("5") is like hiring a translator to convert the word into a number Python can do math with.SECTION 3
Visual Explanation — The Conversion Web
int, float, str, and bool — can be converted between each other. Solid arrows indicate conversions that always succeed, while dashed arrows indicate conversions that may raise errors if the value isn't compatible.As the diagram above illustrates, you can convert from any type to str without risk — every Python value has a string representation. Going from int to float is also safe (e.g., float(5) gives 5.0). However, converting a string to a number is only possible when the string looks like a valid number. The bool() function works on everything — it simply asks whether a value is "truthy" or "falsy."
SECTION 4
How Each Conversion Function Works
int() — Convert to Integer
The int() function converts a value to an integer (a whole number). When given a float, it truncates toward zero, meaning it chops off the decimal part without rounding. So int(3.9) returns 3, and int(-2.7) returns -2. When given a string, the string must contain only digits (and optionally a leading minus sign). Passing int("42") works fine, but int("42.5") raises a ValueError because the string contains a decimal point.
float() — Convert to Floating-Point
The float() function converts a value to a floating-point number (a number with a decimal). Integers convert cleanly: float(7) gives 7.0. Strings work as long as they represent a valid number: float("3.14") gives 3.14, and even float("42") gives 42.0. Note that float() is more flexible than int() when parsing strings because it accepts decimal points.
str() — Convert to String
The str() function is the most forgiving converter — every Python value can be turned into a string. Calling str(100) gives "100", str(3.14) gives "3.14", and str(True) gives "True". This is especially useful when you want to combine text with numbers using concatenation.
bool() — Convert to Boolean
The bool() function returns True or False. Python follows a simple rule: "empty" or "zero" values are falsy; everything else is truthy. So bool(0) is False, bool(0.0) is False, and bool("") (an empty string) is False. But bool(42), bool(-1), and bool("hello") all return True.
Common Gotcha
bool("False") returns True, not False! The string "False" is non-empty, so Python considers it truthy. Only an empty string "" is falsy.SECTION 5
Truthy vs. Falsy — A Detailed Breakdown
Understanding which values are truthy and which are falsy is essential for writing clean Python code, especially when using if statements. The table below shows how bool() evaluates common values across all four core types.
| Expression | Result | Why? |
|---|---|---|
bool(0) | False | Zero integer is falsy |
bool(0.0) | False | Zero float is falsy |
bool("") | False | Empty string is falsy |
bool(None) | False | None is always falsy |
bool(1) | True | Non-zero integer is truthy |
bool(-3.5) | True | Non-zero float is truthy |
bool("hi") | True | Non-empty string is truthy |
bool("0") | True | Non-empty string — even "0" — is truthy |
Truthy and falsy values in Python
SECTION 6
Worked Example — Building a Tip Calculator
Let's walk through a realistic scenario where type conversion is essential. You're building a simple tip calculator that asks the user for a meal total and a tip percentage, then displays the tip amount and final total. This example uses all four conversion functions.
Tip Calculator with Type Conversion
- 1
Step 1 — Get User Input (strings from input())
Theinput()function always returns a string, even if the user types a number. We store those strings in variables.meal_str = input("Enter meal total: ") # e.g., user types "24.50"tip_str = input("Enter tip %: ") # e.g., user types "20"meal_str ="24.50"(string), tip_str ="20"(string) - 2
Step 2 — Convert strings to numbers using float() and int()
We usefloat()for the meal total because it may have decimals, andint()for the tip percentage since it's a whole number.meal = float(meal_str) # 24.50tip_pct = int(tip_str) # 20meal =24.5(float), tip_pct =20(int) - 3
Step 3 — Calculate the tip amount
Now that we have numbers, we can do math. Notice that Python implicitly convertstip_pct(int) to a float during the division.tip_amount = meal * (tip_pct / 100) # 24.5 * 0.2 = 4.9tip_amount =4.9(float) - 4
Step 4 — Build the output string using str()
To display the result, we need to convert numbers back to strings so we can concatenate them with text.total = meal + tip_amount # 29.4print("Tip: $" + str(round(tip_amount, 2)))print("Total: $" + str(round(total, 2)))Output:Tip: $4.9andTotal: $29.4 - 5
Step 5 — Add a bool() check for empty input
We can usebool()to check if the user actually entered something before converting. An empty string is falsy, so this simple check prevents a crash.if bool(meal_str): # True if non-emptymeal = float(meal_str)else:print("No input provided!")Usingbool()provides a safety check before conversion.
SECTION 7
Strengths, Limitations & Common Errors
Each conversion function has its own strengths and pitfalls. Understanding when a conversion will succeed and when it will fail saves you from frustrating debugging sessions. The table below compares the four functions side by side.
| Function | Strengths | Limitations / Pitfalls |
|---|---|---|
int() | Works on floats, numeric strings, and booleans. Useful for getting whole numbers from user input. | Truncates decimals (doesn't round). Cannot parse strings with decimal points like "3.5". Raises ValueError on non-numeric strings. |
float() | Handles integers, numeric strings with or without decimals. More flexible than int() for string parsing. | Still fails on non-numeric strings. May introduce floating-point precision issues (e.g., 0.1 + 0.2 = 0.30000000000000004). |
str() | Never fails — every Python value has a string representation. Essential for display and concatenation. | The resulting string may not look the way you expect (e.g., str(0.1 + 0.2) shows many decimal places). Formatting functions may be better for display. |
bool() | Never fails. Great for checking if a value is 'empty' or 'zero'. Useful in conditionals. | Counterintuitive: bool("0") and bool("False") both return True because the strings are non-empty. |
Comparison of Python's four core conversion functions
KEY TAKEAWAY
bool() just checks: is there any water in the container at all?SECTION 8
Connection to Advanced Concepts
The type conversion skills you're learning now serve as the foundation for more advanced Python programming. As you progress, you'll encounter situations where conversion becomes more nuanced — dealing with collections, custom objects, and data from external sources like files or web APIs.
| What You Know Now | What's Coming Next |
|---|---|
int(), float(), str(), bool() | Conversion to/from lists, tuples, sets, and dicts using list(), tuple(), set(), dict() |
| Basic error from invalid conversion | Using try/except blocks to gracefully handle ValueError and TypeError |
str() for simple display | f-strings and .format() for precise formatting (e.g., two decimal places for money) |
| Converting user input from the console | Parsing data from JSON files, CSV files, and web APIs where all values arrive as strings |
Truthy/falsy with bool() | Defining custom __bool__() and __int__() methods in your own classes (object-oriented programming) |
How today's skills connect to future learning
As you move into data science or web development, you'll find that type conversion is a daily task. Libraries like pandas have their own type conversion methods like .astype() for converting entire columns of data at once. The core logic, however, is exactly the same as what you're learning here — transforming data from one representation into another so you can process it correctly.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
int("7.5") raises a ValueError even though int(7.5) works perfectly fine. What is the difference between passing a string versus a float to int()?Show answer
int() receives a float like 7.5, it knows the value is already a number and can truncate the decimal to produce 7. However, when it receives the string "7.5", Python's int() only knows how to parse strings that look like whole integers (digits with an optional leading minus sign). It does not automatically perform a two-step conversion. The workaround is to chain conversions: int(float("7.5")), which first converts the string to a float, then truncates to an int.Question 2: BASIC CALCULATION
x = "15"
y = int(x) + 10
z = str(y) + " points"
print(z)
What is the type and value of z?Show answer
int("15") converts the string "15" to the integer 15. Adding 10 gives y = 25 (an int). Then str(25) converts it to "25", and concatenating " points" gives z = "25 points". The variable z is a string. The program prints 25 points.Question 3: INTERMEDIATE
bool("0")
(b) bool(0)
(c) int(True) + int(False)
(d) float("inf")Show answer
True — the string "0" is non-empty, so it's truthy. This catches many beginners off guard. (b) False — the integer 0 is the only falsy integer. (c) 1 — in Python, True converts to 1 and False converts to 0, so 1 + 0 = 1. (d) inf — Python recognizes the string "inf" as a special floating-point value representing positive infinity.Question 4: APPLIED
"72.4". Write a short code snippet that: (1) converts the string to a number, (2) converts Fahrenheit to Celsius using the formula C = (F − 32) × 5 ÷ 9, (3) prints the result as a string with the format "72.4°F = 22.4°C". Use at least two different conversion functions.Show answer
temp_str = "72.4"
f = float(temp_str)
c = round((f - 32) * 5 / 9, 1)
print(temp_str + "°F = " + str(c) + "°C")
First, float() converts the string "72.4" to 72.4 so we can do arithmetic. The formula produces 22.4. Then str() converts the result back to a string for concatenation. The output is 72.4°F = 22.4°C.Question 5: CRITICAL THINKING
age = input("Enter your age: ")
if age > 16:
print("You can drive!")
When the user types 9, the program says "You can drive!" — which is clearly wrong. Explain why this happens, identify the bug, and propose a fix. Also explain what would happen in Python 3 if the user types seventeen and how you could guard against that.Show answer
input() returns a string, so age is "9" (a string), not the integer 9. Comparing a string to an integer with > in Python 3 actually raises a TypeError (in Python 2 it would do a lexicographic comparison, leading to the wrong result). The fix is to convert first: age = int(input("Enter your age: ")). If the user types "seventeen", int() will raise a ValueError. To guard against this, you could wrap the conversion in a try/except block: try: age = int(input(...)) except ValueError: print("Please enter a number."). This demonstrates why type conversion and input validation go hand in hand.SUMMARY
Summary — Type Conversion in Python
Summary
Python's four core type conversion functions — int(), float(), str(), and bool() — let you transform data between types so that operations like math, comparison, and display work correctly. Remember that int() truncates decimals rather than rounding, float() is more flexible with string parsing than int(), str() never fails, and bool() treats zero and empty values as False.
The most common real-world use case is converting user input (which always arrives as a string from input()) into the appropriate numeric type before performing calculations. Always be aware of potential errors — not every string can become a number, and converting from float to int loses the decimal portion. As you advance, you'll use these same principles to handle data from files, APIs, and databases, making type conversion one of the most fundamental and frequently used skills in Python programming.