thecodezone.
The Code Zone
Short steps, at your pace · Free lessons and practice · Member video walkthroughs
Save your next small win.

Checking your account…

03.15 · Python basics / Watch · 17 min

Turn numeric text into a number

The digits look familiar, but their type changes what an operation does. Decide whether you want to join text or add numbers.

Activity 15 of 19 in Python basics

All courses

Python Basics / 03.15

Understand type conversion

Not started

Convert numeric text before calculating, and distinguish int, float, str and bool conversions.

More options

Your lesson progress

Walkthrough: not startedPractice: not started

Empty: not started. Yellow: in progress. Green: complete. Marking the whole activity complete does not replace your test results. These circles save in this browser for this pilot.

Rob joins the text values 7 and 2 to get 72, converts both with int, and then adds them to get 9.
Rob’s comic strip · Python basics

ORIGINAL WALKTHROUGH · 10:09

Watch with Rob.

Pause whenever you want to try a change. You can return to the lesson at any time.

LEARN WITH THE CODE ZONE

Unlock this video walkthrough

Written lessons and coding practice are free. Video walkthroughs are included with a paid Code Zone membership or an active free trial.

Have a Code Zone website account? Use your learning account’s email to get a six-digit sign-in code, or use your existing website password.

Need a website account? Paid Skool members and active trial members can use the email from their membership questions to request a sign-in code. No invite link or Skool password needed.

Close this window to keep practicing. After signing in, you’ll return to this lesson.

Video walkthroughs are included with an active Code Zone membership. The written lesson and practice are free.

Open video & code editor (opens in a new tab)

Starter source code for VS Code

Copy the source below or download the file to follow along in VS Code.

The download includes a lesson link in each file and a README so you can find your way back.

main.py
main.pypython · example
# Code along with Rob: type conversion
# Compare joining numeric strings with adding integers.
# Try int, float and str on suitable values.
# Keep the original text and save a converted value separately.
# Predict bool on an empty and a non-empty string.

The same digits can be text or a number

The value "7" is a string because it is inside quotes. The value 7 is an integer. With two strings, + joins their characters: "7" + "2" gives "72". With two integers, + adds: 7 + 2 gives 9.

Use int to convert suitable integer text before doing arithmetic. The conversion returns a new value; it does not change the original string. Keep the original when it is useful to compare what you received with what you calculated.

Convert before adding numeric text
type_conversion.pypython · example
first_text = "7"
second_text = "2"

print(first_text + second_text)  # 72
print(int(first_text) + int(second_text))  # 9
Open workspace to paste this example (opens in a new tab)

Use int for integer text, float for decimal text

int("42") produces the integer 42. float("2.5") produces the float 2.5. Choose a conversion that matches the text you have and the calculation you want.

int can also convert a float by truncating toward zero: int(2.9) is 2, and int(-2.9) is -2. This differs from floor division, which rounds downward. Converting can discard information; it does not automatically make a calculation more precise.

Parsing text and truncating a float are different cases
type_conversion.pypython · example
print(int("42"))  # 42
print(float("2.5"))  # 2.5
print(int(2.9))  # 2
print(int(-2.9))  # -2
Open workspace to paste this example (opens in a new tab)

Conversions have valid and invalid inputs

int("2.5") raises ValueError because decimal-point text is not an integer spelling for this call. float("2.5") can read it. int("hello") also raises ValueError: Python cannot invent a number from those letters.

The video discusses input, whose result is text. This practice uses predefined strings so you can focus on conversion without an input dialog. Later lessons will handle invalid input and exceptions. Avoid treating isdigit as a universal number validator: signs and decimal points are not digits, and not every digit-like Unicode character is accepted by int.

Choose a conversion that can read the text
type_conversion.pypython · example
decimal_text = "2.5"
amount = float(decimal_text)
print(amount + 1)  # 3.5

# int("2.5") would raise ValueError.
# int("hello") would raise ValueError.
Open workspace to paste this example (opens in a new tab)

Use str when you need text for a message

str turns a value into its text representation. In the example, count is the integer 7 and str(count) is the string "7", allowing it to join the other text.

print displays a string’s contents without its surrounding delimiter quotes. The output is Count: 7, with no extra quotation marks. You can also use an f-string, as in the earlier formatting lesson, to put a numeric value inside a message.

A text representation is useful when building a message
type_conversion.pypython · example
count = 7
print("Count: " + str(count))  # Count: 7
print(f"Count: {count}")  # Count: 7
Open workspace to paste this example (opens in a new tab)

Python mixes some numeric types, but does not guess at numeric text

Adding an integer and a float produces a float for these ordinary values: 7 + 2.5 gives 9.5. That numeric cooperation does not mean Python automatically converts strings for arithmetic.

The expression "7" + 2 raises TypeError. Decide what you intend: int("7") + 2 gives numeric 9, while "7" + str(2) gives text "72". Explicit conversion makes your choice clear.

Choose addition or joining; do not rely on guessing
type_conversion.pypython · example
print(7 + 2.5)  # 9.5
print(int("7") + 2)  # 9
print("7" + str(2))  # 72
Open workspace to paste this example (opens in a new tab)

bool checks truthiness, not whether text spells False

bool returns a Boolean value, True or False. Zero and an empty string are falsey; a non-empty string is truthy. So bool("False") is True because that string is not empty. It is not a parser for yes/no words.

The next section explores Boolean values in more detail. For this practice, preserve the two starting strings and convert their numeric contents before adding.

A non-empty string can contain any word
type_conversion.pypython · example
print(bool(0))  # False
print(bool(""))  # False
print(bool("False"))  # True
Open workspace to paste this example (opens in a new tab)

Build it one step at a time

Prefer learning by typing? Work through short instructions, run the Python code and check each change before continuing. Your guided project saves separately from the challenge below.

The mini-lesson opens in a new tab. Your own code carries forward; each step has a focused check and an optional hint.

Start mini-lesson(opens in a new tab)

4 steps · Saved work · Instant feedback

YOUR TURN

Convert the inputs before calculating the sum

Keep first_text assigned to the string "7" and second_text assigned to the string "2". Change total so it adds the integer values of both strings using int. Keep print(total). To pass: both original variables must still hold their starting strings, total must hold the number 9, and the program must print 9 exactly once. Do not replace the inputs with numeric literals. After passing, try different integer strings and predict the sum before running again.

Expected output
9

Keep the starting inputs. Print these lines in this order, without extra output.

  • first_text still holds the string 7
  • second_text still holds the string 2
  • total holds the number 9

Edit Python, then run it. Check challenge checks your output and the listed Python requirements. Your code saves on this browser after a short pause. Sign in and choose Save account draft to keep it across devices. Word wrap is enabled.

Ready to checkRun the checks to see your results here.

Need a nudge?

Look at the operand types

Both starting values are strings. With two strings, + joins text rather than adding numeric values.

Convert each value before the plus

int returns the integer represented by suitable numeric text. Apply it to each input where you calculate total, keeping the original assignments intact.

Replace your editor code?

Your current work will be replaced. Choose Cancel to keep it.

Ready to try it?

Practice in your browser and see your results.

Progress details

Have a question?

Ask the Code Zone community.

Ask a question in The Code Zone (opens in a new tab)

Continue learning

ONE STEP FORWARD

Explain whether the operands are text or numbers, then fix a sum that is joining digits.