Types and conversions
Worked examples
Read the claim, then run it and check the machine agrees. One at a time — nothing here is taken on trust.
# type(x).__name__ gives the short name of a value's type
print(type(42).__name__) # int
print(type(3.14).__name__) # float
print(type("hi").__name__) # str
print(type(True).__name__) # bool
# the three conversions you'll use daily
print(int("42")) # 42
print(float("3.14")) # 3.14
print(repr(str(42))) # '42' (repr shows the quotes: it's text)
type(x).__name__ reports the kind of a value — 'int', 'float',
'str', 'bool'. The conversion functions are named after the type you
want: int("42") builds the number 42, float("3.14") builds 3.14,
and str(42) builds the text '42' (we wrapped it in repr so you can
see the quotes that prove it is a str).
print(int(3.9)) # 3 — chopped toward zero, NOT rounded to 4 print(int(3.1)) # 3 — same result: truncation print(int(-3.9)) # -3 — toward zero again (up from -3.9) print(isinstance(True, int)) # True — bool is a kind of int print(int(True)) # 1 print(int(False)) # 0
int() on a float truncates: 3.9 and 3.1 both become 3, and
-3.9 becomes -3 — always toward zero, never rounding. And because
bool is built on int, isinstance(True, int) is True while
int(True) is 1 and int(False) is 0.
# We CATCH each error so the program finishes and prints what happened.
try:
int("3.5")
except Exception as e:
print(type(e).__name__, "->", e)
try:
"3" + 4
except Exception as e:
print(type(e).__name__, "->", e)
Wrapping a risky line in try/except lets us see the error instead of
crashing. The first prints ValueError -> invalid literal for int() with
base 10: '3.5' — the type (str) was fine, the value was not. The second
prints TypeError -> can only concatenate str (not "int") to str — the
types themselves do not fit the +. Read the error name first: it tells
you whether to fix the value or fix the type.
# input() ALWAYS returns a str. We simulate the user typing 5:
answer = "5"
try:
print(answer + 4) # str + int — this cannot work
except Exception as e:
print(type(e).__name__, "->", e)
# the fix: convert before you compute
print(int(answer) + 4) # 9
answer holds the text "5", exactly as input() would hand it to
you — so answer + 4 raises TypeError: can only concatenate str (not
"int") to str. Convert first with int(answer) and int(answer) + 4 is
9. This one habit — int(...) whatever a user typed before doing math —
prevents the most common beginner bug there is.
Check the concept
One question at a time. Unsure? Revisit the lecture, then answer.
The challenge
Pass the quiz to unlock the challenge — your code will still be waiting here.