Converting in Both Directions

The full round trip you will use constantly:

text to number, do the arithmetic, number back to text for display.

Number to text

PYTHON

total = 51
message = "Total: " + str(total)
nice = f"Total: {total}"

JAVASCRIPT

const total = 51;
const message = "Total: " + String(total);
const nice = `Total: ${total}`;
Compare → Python needs str() to join a number onto a string with +. JavaScript converts automatically, which is convenient and occasionally surprising. Template strings avoid the whole question in both languages.
EXAMPLE
loading editor…
YOUR TURN
Your turn → This is the real shape of processing a form submission. Change the quantity and rerun.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

✦ When conversion fails

int("hello") raises a ValueError in Python and stops the program. Number("hello") in JavaScript quietly returns NaN, which stands for Not a Number, and then silently poisons every calculation it touches. Python shouts, JavaScript whispers. Both need checking.

EXAMPLE
loading editor…
YOUR TURN
Your turn → Change "hello" to a real number written as text, like "7", so every line runs in both languages.
loading editor…

Syntax has to be exact. Every quote, bracket and parenthesis needs its partner, and in Python the spaces at the start of a line count. One slip and the program won't run; the message will say where.

Mark this lesson complete

Signed in, your progress follows you to every device.

Next: Parsing Safely →
← Back