PYTHON • SYNTAX AND CORE TYPES

Type Conversion — Convert between types using int(), float(), str(), bool()

Learn how to seamlessly transform data between Python's core types to keep your programs flexible and error-free.

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
FORTRAN required programmers to declare variable types in advance. Mixing integers and floating-point numbers could produce unexpected results if conversions were not handled carefully.
1972
C Introduces Casting
The C programming language introduced explicit casting syntax, allowing programmers to convert between types using notation like (int) 3.14. This was powerful but error-prone.
1991
Python Is Released
Guido van Rossum released Python with a philosophy of readability. Python is dynamically typed, meaning variables don't need type declarations, and built-in conversion functions make casting intuitive.
2008
Python 3 and Clean Conversions
Python 3 unified and cleaned up type conversion behavior. For example, division now always returns a float, making the need for explicit conversion clearer and more predictable.

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.

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.

1

Explicit Conversion

You deliberately call a conversion function like int() or str() to change a value's type. This is also called type casting.
2

Implicit Conversion

Python sometimes converts types automatically behind the scenes. For example, adding an int to a float automatically produces a float. This is called type coercion.
3

Data Loss Is Possible

Converting 3.99 to an integer gives 3, not 4. The decimal part is simply truncated (chopped off), not rounded.
4

Not Every Conversion Works

Trying to convert "hello" to an integer will cause a ValueError. The string must represent a valid number for numeric conversions to succeed.
✦ KEY TAKEAWAY
Think of type conversion like translating between languages. The word "five" (a string) and the number 5 (an integer) represent the same idea, but Python treats them differently. Using int("5") is like hiring a translator to convert the word into a number Python can do math with.

Visual Explanation — The Conversion Web

This diagram shows how Python's four core types — 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."

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
Be careful: bool("False") returns True, not False! The string "False" is non-empty, so Python considers it truthy. Only an empty string "" is falsy.

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.

Truthy and falsy values in Python
ExpressionResultWhy?
bool(0)FalseZero integer is falsy
bool(0.0)FalseZero float is falsy
bool("")FalseEmpty string is falsy
bool(None)FalseNone is always falsy
bool(1)TrueNon-zero integer is truthy
bool(-3.5)TrueNon-zero float is truthy
bool("hi")TrueNon-empty string is truthy
bool("0")TrueNon-empty string — even "0" — is truthy
A reference chart showing input → output for each of the four conversion functions. Green results indicate truthy/successful conversions, and red indicates falsy results.

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())The input() 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 use float() for the meal total because it may have decimals, and int() for the tip percentage since it's a whole number. meal = float(meal_str) # 24.50 tip_pct = int(tip_str) # 20
meal = 24.5 (float), tip_pct = 20 (int)
3
Step 3 — Calculate the tip amountNow that we have numbers, we can do math. Notice that Python implicitly converts tip_pct (int) to a float during the division. tip_amount = meal * (tip_pct / 100) # 24.5 * 0.2 = 4.9
tip_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.4 print("Tip: $" + str(round(tip_amount, 2))) print("Total: $" + str(round(total, 2)))
Output: Tip: $4.9 and Total: $29.4
5
Step 5 — Add a bool() check for empty inputWe can use bool() 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-empty meal = float(meal_str) else: print("No input provided!")
Using bool() provides a safety check before conversion.

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.

Comparison of Python's four core conversion functions
FunctionStrengthsLimitations / 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.
✦ KEY TAKEAWAY
Think of type conversion like pouring water between different-shaped containers. Pouring from a tall glass (float) into a short cup (int) means some water (the decimal part) spills and is lost. Pouring into a bigger bowl (str) always works — there's room for everything. And bool() just checks: is there any water in the container at all?

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.

How today's skills connect to future learning
What You Know NowWhat's Coming Next
int(), float(), str(), bool()Conversion to/from lists, tuples, sets, and dicts using list(), tuple(), set(), dict()
Basic error from invalid conversionUsing try/except blocks to gracefully handle ValueError and TypeError
str() for simple displayf-strings and .format() for precise formatting (e.g., two decimal places for money)
Converting user input from the consoleParsing 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)

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.

Practice Problems

PROBLEM 1 — CONCEPTUAL
Explain why 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()?
PROBLEM 2 — BASIC CALCULATION
Predict the output of the following code: x = "15" y = int(x) + 10 z = str(y) + " points" print(z) What is the type and value of z?
PROBLEM 3 — INTERMEDIATE
What does each of the following expressions evaluate to? Explain any surprising results. (a) bool("0") (b) bool(0) (c) int(True) + int(False) (d) float("inf")
PROBLEM 4 — APPLIED
You're writing a program that reads temperatures from a text file. Each line contains a temperature as a string like "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.
PROBLEM 5 — CRITICAL THINKING
A classmate writes this code and is confused by the behavior: 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.

Summary — Type Conversion in Python

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.

Varsity Tutors • Python • Type Conversion — Convert between types using int(), float(), str(), bool()