Sometimes you need a variable to mean "I don't have a value yet" or "this is blank." Python uses None for that.
last_login = None
if last_login is None:
print("New user")
Compare with is, not ==, when checking for None.
You'll constantly get data as the wrong type — a number that came in as text, a date that came in as a number. Convert with these:
| Function | What it does | Example |
|---|---|---|
int(x) | Try to turn into a whole number | int("42") → 42 |
float(x) | Try to turn into a decimal | float("3.14") → 3.14 |
str(x) | Turn into text | str(42) → "42" |
bool(x) | Turn into True/False | bool("hi") → True |
Any value that arrives from a CSV, a web form, the command line, or a user input box arrives as a string. If you want to do math with it, convert first.
# Pretend "12" came from a CSV cell
quantity = "12"
price = 5
# This is a bug — it repeats "12" five times
print(quantity * price) # "1212121212"
# Convert first
print(int(quantity) * price) # 60
type(42) # int
type("hi") # str
type([1,2,3]) # list
isinstance(42, int) # True
isinstance() is the cleaner version. Use it in real code.
A user might type "42", or "forty-two", or accidentally hit space. We want a function that returns the number, or None if it can't.
def safe_int(text):
try:
return int(text.strip())
except (ValueError, AttributeError):
return None
safe_int("42") # 42
safe_int("forty-two") # None
safe_int(" 100 ") # 100
Don't worry about try/except in detail — we cover it in Module 4. The point: real-world data is messy, and Python gives you tools to handle "what if it's broken."
None = "no value yet." Check with x is None.int(), float(), str(), bool().type() or isinstance() to inspect a value at runtime.response = input("How old are you? ")
if response > 18:
print("Adult")
What's broken? Fix it.
input() always returns a string. Comparing a string to an int crashes. Fix: if int(response) > 18: