Welcome to a friendly exploration of variables and expressions in Python, complete with a dash of duck-typing and a scoop of None. Think of variables as labeled boxes in your memory warehouse, waiting to store anything you wish. Expressions let you take those boxes and do something with them—like adding up numbers or appending strings.
When you finish this article, you should be able to:
None in PythonPython embraces a concept called duck-typing. Picture a carnival game: if something waddles like a duck and quacks like a duck, we call it a duck—no need to ask for its ID. In code, that means we don’t check an object’s type to decide what we can do with it; instead, we just use the methods or attributes we need.
For instance, if we want to iterate over an object, we assume it’s iterable. If it isn’t, Python will throw an error, and we handle it. This style is referred to as EAFP (Easier to Ask for Forgiveness than Permission), rather than checking in advance with type() or isinstance().
The advantage of duck-typing is flexibility. Your code can handle objects that act like lists, even if they aren’t strictly lists. It’s like being open-minded: “Hey, if it can dance like a list, we’ll treat it like one!”
In Python, we don’t use let, var, or const to declare variables like in JavaScript. Instead, we simply assign a value to a name, and Python knows we’ve created a variable.
a = 7
b = "Marbles"
print(a) # => 7
print(b) # => Marbles
You can also chain assignments to give multiple variables the same value:
count = max = min = 0
print(count) # => 0
print(max) # => 0
print(min) # => 0
Remember, while chaining can be concise, it can also reduce clarity. Use it sparingly.
Python places no strict restrictions on reassigning variables, including changing their type. A variable could store an integer one moment and a string the next. It’s as if you relabeled a box from “Books” to “Shoes,” and that’s perfectly normal in Python.
a = 17
print(a) # => 17
a = "seventeen"
print(a) # => seventeen
This highlights why clear naming matters. If you name a variable total_count and later assign it a string, future-you may be scratching your head about what’s going on.
You can also use shorthand assignment operators in Python, just like JavaScript:
a = 10
a += 5 # a = a + 5
a -= 2 # a = a - 2
a *= 3 # a = a * 3
a /= 4 # a = a / 4
a **= 2 # a = a ** 2
a //= 3 # a = a // 3
a %= 7 # a = a % 7
In JavaScript, odd arithmetic often leads to NaN (“Not a Number”). Python, on the other hand, prefers to throw errors instead of returning NaN when operations don’t make sense. It’s like a strict instructor: “That’s invalid math! I won’t even try to give you a number.”
a = "7"
a /= 2
This triggers a TypeError because you can’t divide a string by an integer. If you really need a NaN-like behavior, you can force it by calling:
print(float("nan"))
In Python, None stands in for “no value” or “nothing.” Whereas JavaScript has both null and undefined, Python just has None. Think of it like an empty box that doesn’t even contain air—just void.
It’s useful when you want to distinguish between “no result” and 0 or an empty string. Many programmers use None as a sentinel value to indicate a special condition, like “Data not loaded yet” or “No valid response.”
my_var = None
print(my_var is None) # => True
If a Python function has no return statement, it automatically returns None. Or you can explicitly write return without a value and that also yields None.
Consider you’re building a basic user registration flow. You want to store optional input, handle a missing input with None, and also demonstrate how duck-typing can simplify your code.
Let’s do it one piece at a time:
First, ask the user for an optional phone number. If they leave it blank, store None:
phone_number = input("Enter phone number (or press ENTER to skip): ")
if phone_number == "":
phone_number = None
Next, demonstrate duck-typing by not worrying whether phone_number is a string or None before printing. If we need to do something specifically string-like, we could check with if phone_number is not None, or just handle an error if it arises.
if phone_number is None:
print("No phone number provided.")
else:
print("Phone number is:", phone_number.upper())
Notice how we never explicitly asked, “Is phone_number of type str?” We let the code attempt upper(), and it works if phone_number is indeed a string. If it isn’t, we’d get an error and handle it (that’s EAFP in practice).
Understanding how Python deals with variables, expressions, and “nothingness” is key for building robust applications:
None for those missing values keeps your data consistent.
None signals “this setting is off or unspecified.”
NULL often maps to Python None, so queries that don’t find records might populate variables with None.
var or letNaN for impossible math operationsNone works as a “no value” placeholder, analogous to JavaScript’s null or undefinedNone and how to detect it with is None
With these skills, you can elegantly handle all sorts of scenarios—whether checking for missing data, chaining multiple variables, or duck-typing your way into a more flexible, Pythonic style. Embrace the freedom of variables and None, and enjoy the power of Python’s dynamic nature in your code!