Skip to content
beginner

Type Conversion in Python: Casting Between Data Types

Every value in Python carries a type, and Python is strict about it. A string "30" and an integer 30 look alike on screen, but they behave completely…

Published 2026-06-08Updated 2026-09-128 min read
Charming young girl in a teal dress cuddling a toy, enjoying nature outdoors.
Charming young girl in a teal dress cuddling a toy, enjoying nature outdoors. Photo by Sandeep Singh on Pexels.

Every value in Python carries a type, and Python is strict about it. A string "30" and an integer 30 look alike on screen, but they behave completely differently in code. Type conversion (also called casting) is how you move a value from one type to another so your program can do what you actually meant.

The rule that organizes everything here is simple: convert at the boundary where data enters an operation, then inspect the result. Most of the time that boundary is user input, which arrives as text through input(). Get that one habit right, and the rest of casting becomes a small set of tools you reach for on purpose.

What Is Python Type Conversion?

Type conversion means changing a value from one data type to another. In Python, you do this with built-in functions like int(), float(), and str().

There are two kinds, and you only need to remember them once:

  • Implicit conversion happens automatically. When you add an integer and a float, Python promotes the integer to a float so no data is lost.
  • Explicit conversion (casting) is when you call a function yourself to force a value into a specific type.

The practical rule for choosing: data that arrives as text—from input(), a file, or an API—usually needs explicit conversion before you can do numeric work. Python may promote compatible numeric operands on its own, but when the result type matters, check it with type() instead of assuming.

If these types are still unfamiliar, review the basic variable and data-type rules first.

When Do You Need to Convert Types?

You will hit type conversion constantly in real programs. The most common trigger is user input.

When you call input(), Python always returns a string—even if the user types a number. That means you cannot do math on it until you convert it. This is the single most common reason beginners reach for casting.

You will also convert types when you want to:

  • Combine text and numbers in a message, which requires turning the number into a string.
  • Control the result of a calculation, like forcing a decimal result or dropping a decimal.
  • Read data from a file or an API, where values often arrive as strings even when they represent numbers.

A classic beginner failure is adding a string and a number:

age = input("How old are you? ")  # User types: 30
print(age + 1)

This raises a TypeError, because age is a string and Python won't add a string and an integer. The fix is to convert at the boundary—right where the input enters the arithmetic:

age = input("How old are you? ")  # User types: 30
age_number = int(age)             # Now age_number is the integer 30
print("Next year, you'll be", age_number + 1)
Next year, you'll be 31

Knowledge check

Check your understanding

Answer this question before you continue.

A user types 30 in response to input(). What is the type of the value returned by input(), before any conversion?
Misconception Check

Focus: Identify why numeric user input must be explicitly converted before arithmetic.

How to Convert Types in Python

Flowchart showing text input such as 30 entering int(), becoming the integer 30, then flowing to a numeric operation and type check; invalid text branches to a ValueError handling step.
Convert incoming text before the operation, then inspect the result; invalid text should follow an error-handling path.

Python gives you three built-in functions you will use almost every day:

  • int(): Converts a value to an integer
  • float(): Converts a value to a float
  • str(): Converts a value to a string

The syntax is simple: put the value you want to convert inside the parentheses.

int("123")    # Converts the string "123" to the integer 123
float(5)      # Converts the integer 5 to the float 5.0
str(42)       # Converts the integer 42 to the string "42"
123
5.0
42

One detail worth knowing: int() and float() don't change the original value. They create a new value of the target type. So int("123") returns a new integer 123; the string "123" still exists untouched.

Knowledge check

Check your understanding

Answer this question before you continue.

Which expression converts the string value "3.5" to a float?
Single Choice

Focus: Choose the built-in conversion function that matches a desired target type.

Practical Examples of Type Conversion

Let's see casting in action with the conversions you will use most. Each example follows the same move: text enters, an operation needs a number, and you verify the type after converting.

Convert String to Integer

Here is a different boundary than the age example—a numeric text field from a form or a file. Watch how type() makes the change visible:

quantity = "12"          # Arrives as text, maybe from a form or file
print(type(quantity))    # <class 'str'>

quantity_number = int(quantity)
print(quantity_number)   # 12
print(type(quantity_number))  # <class 'int'>
<class 'str'>
12
<class 'int'>

The value still looks like 12 on screen, but type() proves it is now an integer you can add, multiply, or compare.

Convert Integer to String

To build a message that mixes text and a number, use str():

score = 99
message = "Your score is " + str(score)
print(message)
Your score is 99

This turns the integer 99 into the string "99" so it can join the rest of the text.

Convert Float to Integer

Using int() on a float removes the decimal part—it does not round:

price = 19.99
whole_price = int(price)   # whole_price is 19
print(whole_price)
19

int(19.99) gives 19, not 20. If you need rounding, use round() instead.

One boundary worth knowing: int() truncates toward zero, not just "down." That matters when you process signed values like balances or measurements:

print(int(3.8))    # 3
print(int(-3.8))   # -3, not -4
3
-3

int(-3.8) gives -3 because it drops the decimal part, moving toward zero. If you want true rounding, round() is the separate tool for that.

Knowledge check

Check your understanding

Answer this question before you continue.

What does this code print?
Output Prediction

Focus: Predict the result of converting a positive floating-point value to an integer.

price = 19.99
print(int(price))

Convert String to Float

When a user might type a decimal, use float():

height = input("Enter your height in meters: ")  # User types: 1.75
height_number = float(height)
print("Your height is", height_number)
Your height is 1.75

This lets you accept both whole numbers and decimals from the same input.

What Happens If Conversion Fails?

Casting only works when the value can actually become the target type. If you try to convert something that doesn't make sense, Python raises a ValueError:

value = "hello"
number = int(value)   # ValueError: invalid literal for int()

Only strings that look like numbers can be converted to numbers. int("hello") will always fail.

To keep your program from crashing, wrap the conversion in a try/except block:

user_input = input("Enter a number: ")
try:
    number = int(user_input)
    print("You entered:", number)
except ValueError:
    print("That wasn't a valid number.")

Now the program responds gracefully instead of stopping with an error.

Knowledge check

Check your understanding

Answer this question before you continue.

A program must handle a user entering nonnumeric text without crashing. Which replacement correctly handles an invalid int() conversion?
Debugging

Focus: Select an error-handling pattern that prevents an invalid integer conversion from stopping the program.

user_input = input("Enter a number: ")
# conversion code goes here

Common Mistakes and When to Avoid Casting

Here are the pitfalls I see beginners hit most:

  • Forgetting that input() returns a string. You cannot do math on it until you convert it.
  • Assuming int() rounds. It truncates toward zero. int(7.8) is 7, not 8.
  • Converting text that isn't a number. int("hello") raises a ValueError. Check your data first, or handle the error.
  • Casting when you don't need to. If you're only printing a value, print() already converts it to a string for you. You don't need str() there.
  • Skipping the inspection step. After you convert, confirm the result with type() before you trust it in the next operation.

A quick comparison of the two conversion types:

ConversionWho does itWhen it happensBeginner mistake
ImplicitPython, automaticallyMixing types in an expression, like int + floatAssuming the result type instead of checking with type()
ExplicitYou, with int(), float(), str()When you need a specific type, like converting user inputForgetting that invalid strings raise ValueError

Practice: Try It Yourself

Here's a small task to lock this in. The conversion boundary is marked for you—your job is to complete the two missing lines.

  1. Ask the user to enter a number.
  2. Convert the input to an integer.
  3. Add 10 to the number.
  4. Print the result.

A starting point:

user_input = input("Enter a number: ")
## TODO: convert user_input to an integer and store it in number
## TODO: add 10 to number and store the result
print("Your number plus 10 is:", result)

Once it runs, test the article's decision rules. What happens if you enter something that isn't a number? What changes if you use float() instead of int()? What happens if you try to convert a float string like "3.5" with int()? Each answer should remind you why you convert at the boundary and inspect the result.

Next Steps

Type conversion is a small skill that unlocks a lot of real code. Keep the decision rule in your pocket: identify the current type, choose the target type based on the operation you need, convert once at the boundary, and handle invalid input. That checklist carries you past user input into files, APIs, and any place where text arrives pretending to be a number.

From here, practice combining numbers and strings while keeping your code readable with clear naming and comments.

Knowledge check

Final check

Finish the article by checking the ideas you just learned.

Which sequence best follows the article's main rule when a program receives a number through input()?
Question 1 of 2Single Choice

Focus: Apply the article's rule of converting input at the boundary before performing numeric work.

Which statement correctly describes int(-3.8) according to the article?
Question 2 of 2Misconception Check

Focus: Distinguish truncation toward zero from rounding when converting a float to an integer.

References

  1. Built-in Types — Python 3.14.7 documentationdocs.python.org
8sources checked
8source domains
5searches run

Research updated Sep 5, 2026

Practical resource

Want a more structured Python path?

Use the Python Starter Pack to turn scattered tutorials into a focused practice path.

View the bundle
Coming soon

Python Starter Pack

A compact LearnPyFast PDF pack covering what Python is, installation, your first program, running Python code, and Python versions.

$9
PDF BundleTopic PackPythonBeginner
  • 5 curated chapters
  • Enhanced PDF edition with bundle-only learning guidance
  • Offline-friendly format for focused review
  • Source article links for future online updates

Coming soon

Free Python bundle

Get the LearnPyFast Python Starter Bundle

A focused collection of beginner-friendly Python resources to help you move from setup to building practical projects.

You’ll receive the bundle by email. You can unsubscribe anytime.

No spam. You can unsubscribe anytime. See our Privacy policy.

Related sites

Continue beyond Python

Explore related Worldmonger sites when you want to move from Python basics into JavaScript or LLM application building.

JavaScript tutorialstutorial

LearnJSFast

Beginner-friendly JavaScript tutorials for practical web development and self-taught developers.

JavaScriptFrontendWeb development
Visit LearnJSFast
LLM tutorialstutorial

LearnLLMFast

Practical LLM tutorials for builders who want to understand prompting, workflows, agents, and AI applications.

LLMAIBuilders
Visit LearnLLMFast

Keep learning

Related tutorials

Continue with nearby Python topics and beginner-friendly explanations.

Close-up view of HTML and CSS code displayed on a computer screen, ideal for programming and technology themes.
beginner
11 min read

Basic Math in Python

Python does not make you memorize a calculator manual. It hands you a small set of operators and lets you run the calculation and read the answer…

Read tutorial
Close-up of a large pot filled with black dye used in traditional incense stick production indoors.
beginner
9 min read

Python Comments and Code Style

Comments are not for Python. They are for the next human who reads your code—and that human is often you, six weeks later. The interpreter skips every line…

Read tutorial