Skip to the workspace
Pebellslearn by building
Fundamentals  ›  Lesson

Type Casting & Input

Type Casting 20 minType conversion creates a value of one type from a compatible value of another type. Input from a text field starts as text.

Type conversion creates a value of one type from a compatible value of another type. Input from a text field starts as text.

Convert external values, handle conversion failures and validate business rules separately from successful parsing.

A text field containing “250” is still text. Before calculating with it, you must choose a numeric representation and decide which input spellings you accept. We will separate cleaning, conversion, domain checks and display, because each can fail or discard information for a different reason.

A typed amount "  ₹1,234.50 " is cleaned in three steps, strip, remove the rupee sign, remove the comma, until float() turns "1234.50" into the number 1234.5; a dashed red arrow shows calling float() on the raw text straight away ends in ValueError

Read a UPI amount

A payment form asks "How much?". In a terminal script you'd read it with input(), and input() always returns a string:

amount = input("Amount: ")     # the user types 250
print(amount + 50)             # TypeError: can only concatenate str to str
amount = float(input("Amount: "))   # cast the moment you read it

The browser boxes can't pause for typing, so here the "typed" text is written straight into a variable. Casting clean text is easy:

python

Real fields are not clean. People type the rupee sign and the comma they see on their banking app:

broken — fix itValueError

Run it and read the error. Clean the text before float() so it prints 1334.5.

int() is stricter still. It reads only whole-number text:

What happens when you run this?
print(int("3.5"))

Preparing this topic’s interactive investigation…

Split a cab fare

Three friends share a ₹487 cab ride. Dividing gives a float, and now you must decide what "each" means. int() is tempting, but it does not round:

What does this print?
fare = 487
each = int(fare / 3)
print(each, each * 3)

int() truncates: it drops everything after the dot, towards zero. To get the nearest whole number use round(), and to make sure the driver is never short, round up with math.ceil():

python

Two rounding surprises, both real: halves round to the even neighbour (called banker's rounding, it avoids a bias towards rounding up), and some decimals are stored a hair below what you typed:

python

These exercises specify round(x, 2). A real billing system must choose a rounding policy. Decimal("2.675") represents that decimal exactly; Decimal(2.675) starts with the float approximation instead. Decimal arithmetic still has a precision context, so division can require rounding.

Python also performs some conversions implicitly: int + float gives a float, and True counts as 1 in a sum. Implicit does not mean lossless: float(2**53 + 1) cannot retain that exact integer on usual binary64 floats. Text is never parsed automatically for arithmetic:

python

Check a form field

A sign-up form must reject blank fields. bool() says whether a value counts as true. The falsy values are few: 0, 0.0, "", None, and empty collections like [] and {}. Everything else is truthy:

python

Here is where people get caught. A dropdown sends its choice as text:

What does this print?
newsletter = "False"
print(bool(newsletter))

The same goes for "0": the text is non-empty, so it is truthy, even though the number 0 is falsy. if field: asks "did they type anything?", not "is the amount zero?". To reject a zero amount, convert first, then compare.

In a real form you cannot let one bad keystroke crash the page. Wrap the cast in try / except ValueError and hand back a safe value instead (the exceptions lesson covers this fully):

python

Catch ValueError by name. A bare except: would also hide your own typos.

Conversion answers only one question

float(text) asks whether text uses a supported numeric spelling. It accepts more than digits and a dot: signs, exponents such as "1e3", and special values such as "nan" and "inf". Successful conversion does not establish “a usable positive payment.” That is a second, application-specific check.

python

This function assumes its input is a string. Passing an unrelated object can raise a different error; the contract should state what inputs it accepts. None distinguishes rejection from a legitimate numeric value. Returning 0 for every parse failure, as the warm-up asks, deliberately loses that information and should be limited to contexts where that fallback is intended.

Likewise, removing all commas is valid only under this exercise's assumed thousands-separator convention. "1,2" becomes 12, although another locale might mean 1.2. A parser needs an agreed format, not just more replacements. For independent practice, accept only the flags yes and no, ignoring outer spaces and case. Reject maybe, 0 and empty text explicitly; using bool(text) cannot implement that language.

Formatting numbers back into text

The last step is the reverse cast: a number becomes text for the screen. An f-string with a format spec after the colon does it in one go:

python

Quick practice

What does this print?
print(int(float("7.9")))
What does this print?
print(str(5) * 3, 5 * 3)
broken — fix it

This prints "4" over and over instead of the total fare. Make it print 480.

What does this print?
print(bool("0"), bool(0))

🎯 Your turn

Write parse_amount(text). It cleans a price string and returns it as a float:

  • parse_amount("$84.00") → 84.0
  • parse_amount("$1,234.50") → 1234.5

Hint: the same chain as the rupee example, with $ in place of ₹: text.strip().replace("$", "").replace(",", ""), then wrap it in float(...).

Press ▶ Run, try the Live App chips, then ✓ Check. After that, the practice set below goes from a safe int to cleaning a whole list of messy amounts.

Your task
Build parse_amount(text). It cleans a price string and returns it as a float. Example: parse_amount("$84.00") → 84.0.

Practice — level up

0/5 solved

Solve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.

Warm-upSafe int

Write safe_int(text) returning int(text), or 0 if it isn't a valid whole number.

casttry/except
DrillMoney format

Write money(amount) returning a string like "$1,234.50" — a leading $, thousands separators, exactly 2 decimals.

f-strings
BuildParse a CSV row

Write parse_row(row) for a "name,price,qty" string, returning a list [name, price(float), qty(int)], or None if it doesn't have 3 parts or the numbers are invalid.

splitcasttry/except
BossAligned receipt

Write format_receipt(items) where items is [(name, price), ...]. Return a multi-line string: each line name left-aligned in 12 cols then $price right-aligned in 7 cols (2 decimals), and a final TOTAL line the same way. Join with \n.

comprehensionf-string-alignsum
CapstoneClean messy amounts

Write clean_amounts(raw) for a list of messy price strings (may contain $, ,, spaces, or junk). Return {"total": <sum of valid, 2dp>, "valid": <count>, "skipped": <count of unparseable>}.

casttry/exceptloopdictround
Project context and further resources
You're building a piece ofBill Splitter & Tip Calculator
This piece — parse_amount(): Turns messy text guests type ($1,234.50) into real numbers.
Scenario A guest types "$1,234.50" into the bill field. The app gets text and must convert it to a number to do the math.
parse_amount.py
Call the function you wrote — just like your app's frontend would. Edit the inputs and hit Call.
parse_amount(text) → floatClean a price string and return it as a float.
try:
returned
Press Run to execute your code.
Press Check to run the tests for this lesson.
Hover to wake the cannons. Drag to move, or use arrow keys when focused. Press Enter to fire a shot.