Explicit Conversion
int("42") # 42
float("3.14") # 3.14
str(100) # "100"
bool(0) # False
bool("") # False
bool("abc") # True
Implicit Conversion
Python auto-promotes int → float in mixed arithmetic:
3 + 0.5 # 3.5 (float)
Common Errors
int("3.14") # ValueError — use float first
int("abc") # ValueError
int(" 42 ") # 42 (whitespace OK)
float("inf") # infinity
float("nan") # not-a-number
Safe Pattern
def to_int(s, default=0):
try:
return int(s)
except ValueError:
return default
Truthy and Falsy
Empty collections, 0, 0.0, "", and None are all falsy. Everything else is truthy.
Practise this on PyForm — free
PyForm runs Python in your browser with an AI tutor trained for HKDSE. No install, no credit card.
Open PyForm →