Command Palette

Search for a command to run...

Hectal
Back to the lesson: Topic 1.6 — Checking and Converting Types
Python · Example 1 of 2

type, isinstance and the conversion functions

Look at int("1_000"): underscores are allowed in text given to int().

Every value has a type. type() and isinstance() tell you which, and int(), float(), str() and bool() convert between types when the conversion makes sense. Python never converts text and numbers silently, so "5" + 5 is an error.

Change the code and press Run (Ctrl+Enter). Predict what will happen first, then break it on purpose and read what changes. Your edits are saved and match the lesson page.

Ready for more? This phase has 6 hands-on exercises with automatic checks.

Practice questions

Write the code in the editor, run it, then open the model answer to compare.

01

Convert the text "250" to a number, add 50, and print the total.

02

Turn the number 7 into text and use it to print Lucky number: 7 by joining strings with +.

03

Turn the text "9.99" into a whole number by cutting off the decimals, and print it.

Explain it without notes

01

What is the difference between type(x) and isinstance(x, int)?

02

Why does Python refuse "5" + 5, and what are the two ways to resolve it?

03

What does int(-3.9) give, and what does that tell you about int() on floats?

04

What is the difference between a ValueError and a TypeError in conversions?

type, isinstance and the conversion functions
Sign in to run this example in your browser.

Expected output

<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'>
True False True
True
43 7.0 99 balloons
3 -3 7.0 False True
12 1000 255 5
3.0 <class 'float'> 2.5