HomeCourseModule 03 › None, type conversions, and reading the type

None, type conversions, and reading the type

Module 03 · Variables and Data Types7 min readBeginner

What you'll learn

  • Use None as an 'unknown' placeholder
  • Convert between strings, ints, and floats
  • Inspect the type of any value

None — Python's "nothing"

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.

Type conversions

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:

FunctionWhat it doesExample
int(x)Try to turn into a whole numberint("42") → 42
float(x)Try to turn into a decimalfloat("3.14") → 3.14
str(x)Turn into textstr(42) → "42"
bool(x)Turn into True/Falsebool("hi") → True

The "everything is a string when it comes from outside" rule

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

Checking the type at runtime

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.

Walkthrough: a "safe" number parse

The problem

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.

The fix using try/except

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."

Key takeaways

  • None = "no value yet." Check with x is None.
  • Convert with int(), float(), str(), bool().
  • Data coming from outside is almost always a string. Convert before you compute.
  • Use type() or isinstance() to inspect a value at runtime.

Spot the bug

response = input("How old are you? ")
if response > 18:
    print("Adult")

What's broken? Fix it.

Answer

input() always returns a string. Comparing a string to an int crashes. Fix: if int(response) > 18:

📹 Video walkthrough
A video walkthrough of this lesson will be embedded here. Until then, the written walkthrough above mirrors what the video will cover step-for-step.