Variables & Data Types
You already used variables in Chapter 1. This chapter follows one running example — the signup form for a small app called PixelHub — to show exactly what's happening under the hood every time you create one.
1. Naming variables properly
In Chapter 1 you wrote name = "Asha" without worrying too
much about what names are allowed. Python actually has firm rules
about it — break them, and your program won't even run. Here's
the PixelHub signup form your teammate wrote last week — and why
three of these five lines crashed it before it even started.
username123 = "valid" # starts with a letter — OK
_username = "valid" # starts with underscore — OK
123username = "invalid" # cannot start with a digit
user name = "invalid" # no spaces allowed
user$name = "invalid" # no special symbols allowed
username, Username,
and USERNAME are three separate variables. This trips up
beginners constantly — if your code says a variable is
"undefined" but you swear you created it, check the capitalization
first.
Go Deeper: why these rules exist
Python's parser needs to instantly tell a variable name apart from a
number or an operator while reading your code left to right. Letting
names start with a digit would make 123abc ambiguous
— is that the number 123 followed by something called
abc, or one name? Banning that ambiguity up front keeps
the language simple to parse and impossible to misread.
- A variable name must start with a letter or underscore (
_). - After that, digits are allowed.
- No spaces, no special symbols (
$,%, etc.). - Names are case-sensitive:
age≠Age.
2. Python decides the type for you
In languages like Java or C, you must announce a variable's type before using it. Python doesn't ask you to — it looks at the value you assign and figures the type out automatically. This is called dynamic typing, and it's one of the biggest reasons Python feels so much lighter to write.
Back to the PixelHub signup form: once the name mistakes are fixed, here's what a working profile card actually stores — five fields, five different types, and Python worked out every one of them without being told.
username = "asha_codes" # str — text
user_age = 24 # int — whole number
account_balance = 149.5 # float — decimal number
is_verified = True # bool — True or False
signal = 3 + 4j # complex — rarely needed, but built in
print(username, user_age, account_balance, is_verified, signal)
asha_codes 24 149.5 True (3+4j)
First click loads a real Python engine in your browser (a few seconds) — after that, running is instant. This sandbox can't use input(), so try editing the values above instead.
True or False (capitalized, no quotes —
those are keywords, not strings). is_verified above is a
boolean. Booleans are what every comparison like 5 > 3
produces, and they're the foundation of every decision your programs
will make starting in Chapter 4.
user_age = 24 then later
user_age = "twenty-four" is completely legal —
user_age just points to a different type of value now.
Go Deeper: complex numbers
A complex number has a real and an imaginary part, written as
a+bj in Python (using j instead of math's
usual i, a convention borrowed from electrical
engineering). A signup form will basically never need one —
signal above only exists to prove the type is real
— but it's a first-class built-in type, useful to know if you
ever move into scientific computing.
- Python is dynamically typed — no need to declare a type.
- Core types:
str,int,float,bool,complex. TrueandFalseare booleans, not strings — no quotes.
3. Peeking under the hood: type() and id()
Since Python decides types automatically, you sometimes need to ask
it what it decided. Two built-in functions answer that: one tells
you a value's type, the other tells you exactly where in memory it
lives. Let's point them at the user_age field from the
PixelHub signup form.
user_age = 24
print(type(user_age)) # <class 'int'>
print(id(user_age)) # some memory address, e.g. 140713...
second_age = 24
print(id(second_age)) # often the SAME address as user_age!
id(). Two variables can hold "the same value" while
being different questions from "are they the exact same object in
memory" — that second question is what id() and the
is keyword answer.
Go Deeper: why do user_age and second_age share an address?
For small, unchanging values like the integer 24,
Python reuses one object in memory instead of creating a new one
every time. When you write user_age = 24 and
second_age = 24, both variables just point at that
one shared object — that's why
id(user_age) == id(second_age). This works because
numbers, strings, and booleans in Python are
immutable: once created, an object's value can
never change in place. If a birthday later bumps
user_age = 25, Python doesn't modify the original
object — it creates a brand new one and points
user_age at that instead, leaving
second_age untouched at 24.
type(value)tells you the data type.id(value)tells you the memory address.- Numbers, strings, and booleans are immutable — they can't be changed in place.
4. Converting between types
Remember from Chapter 1: input() always returns a
string, even if the person types a number. On the PixelHub signup
form, that's exactly what happens the moment a real person fills it
out — the age box hands back "24", not
24. Sooner or later you need to explicitly convert a
value from one type to another, and Python gives you one function
per type to do it.
age_text = "24" # what input() hands back
user_age = int(age_text) # str -> int
print(user_age + 1) # 25 — next birthday
balance_text = "149.50"
account_balance = float(balance_text) # str -> float
user_id_text = str(1042) # int -> str
is_active = bool(1) # -> True
int("24") turns the string
"24" into the number 24. It only works if
the value actually makes sense in the new type: int("hello")
raises an error, because "hello" isn't a number in any language.
Go Deeper: the bool() trap that catches everyone once
bool("False") returns True. Read that
again — it's not a typo. bool() doesn't look at
what the text says, it only checks whether the string is
empty or not. Any non-empty string, including the
literal text "False", converts to True.
Only bool("") (an empty string) gives False.
This exact mistake shows up in real bugs when a signup form's
email_verified setting comes back from a database
export as the text "false", and a developer forgets
this rule — every account reads as verified.
int(),float(),str(),bool(),complex()convert between types.- Conversion fails with an error if the value doesn't make sense in the target type.
bool()on a string only checks if it's empty — not what the text says.
- Every "500 Internal Server Error" you've ever seen on a website is often, under the hood, a
TypeErrorfrom mixing types the way this chapter warned about — unhandled by that site's code. - Config files (
.env, JSON settings) load everything as strings or loosely-typed values first — real production code constantly does exactly theint()/float()conversions you just practiced before trusting that data. id()and immutability aren't academic trivia — they're the exact reasoning behind why Python's small-integer caching exists, and why comparing objects withisvs==causes real, hard-to-find bugs in production systems.
Points to Remember
- Variable names: start with a letter or underscore, then letters/digits only, no spaces or symbols, case-sensitive.
- Python is dynamically typed — it infers
str,int,float,bool, orcomplexfrom the value you assign. type(x)shows the data type;id(x)shows the memory address.- Small immutable values (like small ints) may share the same memory address until reassigned.
- Convert between types explicitly with
int(),float(),str(),bool(),complex()— watch out for thebool()-on-strings trap.