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.

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 itThe browser boxes can't pause for typing, so here the "typed" text is written straight into a variable. Casting clean text is easy:
Real fields are not clean. People type the rupee sign and the comma they see on their banking app:
ValueErrorRun 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:
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:
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():
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:
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:
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:
Here is where people get caught. A dropdown sends its choice as text:
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):
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.
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:
Quick practice
print(int(float("7.9")))print(str(5) * 3, 5 * 3)This prints "4" over and over instead of the total fare. Make it print 480.
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.0parse_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.
Practice — level up
0/5 solvedSolve each in its own editor — Run to try, Check to grade. Stuck? Reveal a Hint, or the full Solution + walkthrough.
Write safe_int(text) returning int(text), or 0 if it isn't a valid whole number.
Write money(amount) returning a string like "$1,234.50" — a leading $, thousands separators, exactly 2 decimals.
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.
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.
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>}.