🐍 Python for Everyone

← Back to all chapters

Chapter 2 of 27 Beginner 16 min read

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.

Say you're building the signup form for PixelHub — a username field, an age field, an account balance. Every one of those values has to live somewhere in memory with a specific type and a specific address. Most of the time Python hides this from you. But the moment something goes wrong (a crash, a weird bug, an interview question you can't answer), it's because one of these hidden details mattered. This chapter makes them visible, using that one signup form as the thread running through every example.
Sub-topic 1 of 4

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.

naming.py
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
What is... case-sensitivity? Python treats uppercase and lowercase letters as completely different characters in a name. 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.

Quick recap
  • 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.
Sub-topic 2 of 4

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.

auto_types.py
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)
Output
asha_codes 24 149.5 True (3+4j)
try_it.py
Click "Run Code" to see the output here — runs a real Python interpreter right in this page.

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.

What is... a boolean? A boolean is a data type with exactly two possible values: 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.
What is... dynamic typing? Dynamic typing means a variable's type is determined automatically from the value assigned to it, and can even change later in the same program: 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.

Quick recap
  • Python is dynamically typed — no need to declare a type.
  • Core types: str, int, float, bool, complex.
  • True and False are booleans, not strings — no quotes.
Sub-topic 3 of 4

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.

type_and_id.py
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!
What is... identity? An object's identity is its unique location in memory, returned by 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.

Quick recap
  • 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.
Sub-topic 4 of 4

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.

conversion.py
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
try_conversion.py
Click "Run Code" to see the output here.
What is... type conversion? Type conversion (also called "casting") is turning a value of one type into another — 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.

Quick recap
  • 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.
In the Real World

Points to Remember

← Chapter 1 Take the Quiz →