Ravindra BagaleCourses & study guides मराठी Track your progress

Python Variables and Data Types Explained for Beginners (int, float, str, bool)

P2.3 How to Convert Data Types in Python (Type Casting)

Why. Data from files and forms often arrives as text. Before you can add or average it, you must convert it to a number.

What. Use the type name as a function to convert.

  • int("42") → 42
  • float("19.99") → 19.99
  • str(42) → "42"
  • bool(0) → False, bool(5) → True

How.

Convert safely

  1. Look at the value and its type.
  2. Pick the target type.
  3. Wrap the value: float(value).
  4. Check the new type with type().

Worked example A — Text to number.

Step 1 — What we do. An online form in Dublin sends the amount "120.50" as text. We convert it before adding a €5 fee.

Step 2 — Type and run this code.

amount_text = "120.50"
amount = float(amount_text)
print(amount + 5)

Step 3 — Output you should see.

125.5

Step 4 — What it means. After float(), maths works. Without it, "120.50" + 5 gives an error.

Worked example B — Number to text for a message.

Step 1 — What we do. We build a message for a patient in Nairobi. Text and numbers cannot be joined with + directly.

Step 2 — Type and run this code.

visits = 3
message = "Total visits: " + str(visits)
print(message)

Step 3 — Output you should see.

Total visits: 3

Step 4 — What it means. str() turns 3 into "3" so it can join with other text. Later you will learn f-strings, which are easier.

Worked example C — An intended error: text that is not a number.

Step 1 — What we do. We try to convert text with a comma.

Step 2 — Type and run this code.

print(int("1,200"))

Step 3 — Output you should see.

ValueError: invalid literal for int() with base 10: '1,200'

Step 4 — What it means. Python cannot read the comma. Remove it first: int("1,200".replace(",", "")) gives 1200. You will see this often with Indian formats like "1,25,000".

Ravindra Bagale's Tip

When numbers come with ₹, $ or commas, clean the text first, then convert. Remove symbols with .replace(), then use float().