A topic in the Open Knowledge Graph — a free, open map of 15,290 topics and the order to learn them in.

Type Conversion and Casting

College Depth 71 in the knowledge graph I know this Set as goal
594topics build on this
320prerequisites beneath it
See this on the map →
Integer and Floating-Point Number TypesOperators and Expressions+3 moreBasic Input and OutputError Handling and Exceptions+1 more
casting type conversion int float str coercion

Core Idea

Type conversion (casting) transforms a value from one data type to another. Explicit conversion uses functions like int(), float(), and str() to request a specific type. Implicit conversion (coercion) happens automatically when a language combines compatible types (e.g., adding an int to a float). Not all conversions are valid — converting 'hello' to int raises an error. Understanding when and how to convert types is essential for processing user input and mixing numeric types correctly.

How It's Best Learned

Write a calculator that reads string input, converts to numbers, computes, and formats the result as a string. Deliberately trigger conversion errors and read the error messages carefully.

Common Misconceptions

Explainer

You already know that values in a program have types — integers, floats, strings, booleans — and that operators behave differently depending on those types. But what happens when you need to combine values of different types, or when data arrives in one type and you need it in another? This is where type conversion (also called casting) comes in: explicitly transforming a value from one type to another using built-in functions like `int()`, `float()`, and `str()`.

The most common scenario is processing user input. When a program reads from the keyboard, the result is always a string — even if the user typed `42`. To do arithmetic with that input, you must convert it: `age = int(input("Enter your age: "))`. Without the `int()` call, `age` would hold the string `"42"`, and adding 1 to it would either concatenate the string or raise an error, depending on the language. Going the other direction, `str(42)` turns the integer into the string `"42"`, which you can then concatenate into a message like `"You are " + str(42) + " years old"`.

Not every conversion makes sense, and the language will tell you so with an error. `int("hello")` fails because there is no meaningful integer for arbitrary text. Even `int("3.14")` fails in most languages — you cannot jump directly from a decimal-containing string to an integer. The correct path is `int(float("3.14"))`, converting to float first, then truncating to int. Notice the word truncating: `int(3.9)` produces `3`, not `4`. It chops off the decimal portion rather than rounding. This surprises many beginners who expect mathematical rounding behavior.

Some languages also perform implicit conversion (or coercion), automatically converting types when it seems safe. In Python, `3 + 2.5` silently promotes the integer `3` to `3.0` before adding, yielding `5.5`. This is convenient, but implicit conversion can also hide bugs — JavaScript's `"5" + 3` produces the string `"53"` instead of the number `8`, because it coerces the number to a string for concatenation. Understanding when your language converts implicitly versus when you must convert explicitly is essential for writing code that behaves as you intend.

Practice Questions 5 questions

Prerequisite Chain

Understanding ZeroThe Number ZeroCounting to FiveCounting to 10Counting to 20Counting a Set of Objects Up to 20Cardinality: The Last Number CountedMatching Numerals to QuantitiesSubitizing Small QuantitiesAddition Within 10Number Bonds to 10Addition Within 20Doubles and Near DoublesDoubles Facts Within 10Near Doubles Facts Within 20Mental Math Strategies for AdditionMental Math: Adding and Subtracting TensAddition Within 100Repeated Addition as MultiplicationMultiplication as Equal GroupsMultiplication: ArraysBasic Multiplication Facts (0s, 1s, 2s, 5s, 10s)Multiplication Facts Within 100Division as Equal SharingDivision as Grouping (Measurement Division)Division: Grouping (Repeated Subtraction) ModelDivision: Fair Sharing ModelDivision as Equal SharingDivision as GroupingBasic Division FactsDivision Facts Within 100Multiplication and Division Fact FamiliesRelationship Between Multiplication and DivisionDivision Facts as Inverse of MultiplicationRemainders and Quotients in DivisionDivision Word ProblemsMulti-Step Word ProblemsSolving Multi-Step Word ProblemsMultiplication Word ProblemsDivision Word ProblemsIntroduction to Long DivisionFactors and MultiplesPrime and Composite NumbersEquivalent FractionsRelating Fractions and DecimalsDecimal Place ValueIntegers and the Number LineComparing and Ordering IntegersAbsolute ValueAdding IntegersSubtracting IntegersMultiplying IntegersIntroduction to ExponentsOrder of OperationsInteger Order of OperationsVariable ExpressionsThe Distributive PropertyVariables and Expressions ReviewIntroduction to PolynomialsAdding and Subtracting PolynomialsMultiplying PolynomialsFactorialPermutationsCombinationsCounting Principles: Addition and Multiplication RulesIntroduction to Graph TheoryPropositional Logic FoundationsLogical EquivalencesBoolean AlgebraBoolean Type and Truth ValuesType Systems and Type SafetyType Conversion and Casting

Longest path: 72 steps · 320 total prerequisite topics

Prerequisites (5)

Leads To (3)