Chapter 3 of 24 · Python for Beginners — Complete Free Tutorial

Variables and Data Types

With a working interpreter, the Python for Beginners series can start writing real code. A variable in Python is a name glued to a value — no declaration keyword, no type annotation, no ceremony. This chapter covers how names are created, how they must be spelled, the handful of built-in types you will use daily, and how to check at any moment what a value actually is.

Variables without declarations

Assignment is the declaration. There is no let, no const, no int before the name: writing name = value creates the variable if it does not exist and repoints it if it does.

course = "Python for Beginners"
lessons = 24
price = 0.0
is_free = True

lessons = lessons + 1
print(course, lessons, price, is_free)

Expected output:

Python for Beginners 25 0.0 True

Under the hood the name holds a reference to a value object, and lessons = lessons + 1 builds a new integer and points the name at it. A name must be assigned before it is read — otherwise you get NameError: name 'course_name' is not defined, Python’s version of JavaScript’s ReferenceError.

Naming rules and snake_case

The grammar is simple; the conventions are what make code readable. Rules enforced by the interpreter:

  • Names may contain letters, digits and underscores — week_3, total_refunds, _internal.
  • They may not start with a digit — 3rd_place is a syntax error.
  • They are case sensitive — Total and total are two different variables.
  • They may not be keywords — if, class, import, None and friends are reserved (import keyword; keyword.kwlist lists them all).

PEP 8, the community style guide, then asks for a shape per kind of name. Python accepts TotalPrice for a variable, but readers will assume it is a class — matching the convention costs nothing and saves a mental translation on every line:

Kind of nameStyleExample
Variables and functionssnake_casetotal_price, get_full_name()
ClassesPascalCaseShoppingCart
Modules and packageslowercaseimport json
ConstantsUPPER_SNAKE_CASEMAX_RETRIES = 3
Private-ish internalsleading underscore_cache

The four built-in types you need first

You will meet classes and tuples in later chapters; day-to-day Python leans on four value types, plus one special value.

TypeExampleWhat to know now
int42, -7, 10_000Whole numbers of unlimited size — 2 ** 1000 is exact, where JavaScript rounds
float3.14, -0.5, 1e6Binary floating point: precise, not exact (0.1 + 0.2 is not 0.3)
str"Ada", 'Ada'Text of any length, Unicode by default, immutable
boolTrue, FalseCapital letters; they behave as 1 and 0 in arithmetic
NoneNoneThe single “no value here” object; its type is NoneType
print(type(42), type(3.14), type("Ada"), type(True), type(None))

Expected output:

<class 'int'> <class 'float'> <class 'str'> <class 'bool'> <class 'NoneType'>

None is the closest Python gets to JavaScript’s null, but unlike undefined there is only one — a name that was never assigned raises NameError rather than quietly returning a hole in your data.

Dynamic typing: type() and isinstance()

Because the value carries the type, you can always ask what it is. type() returns the exact class; isinstance() answers yes or no and understands inheritance (chapter 16), so it is usually the better test in real code:

value = 10
print(type(value), isinstance(value, int))

value = "ten"
print(type(value), isinstance(value, int))

Expected output:

<class 'int'> True
<class 'str'> False

Mutable vs immutable (a preview). Every value in Python is either immutable — the object never changes, so a new name or a new object is created instead — or mutable, where the object can be edited in place. Numbers and strings are immutable:

score = 10
copy = score
score = 11
print(score, copy)

words = ["a", "b"]
words.append("c")
print(words)

Expected output:

11 10
['a', 'b', 'c']

The integer 10 was never modified — score was repointed at a new 11, so copy still holds the old value. The list, by contrast, was edited in place and every name pointing at it sees the change. Lists and dictionaries get chapters 8 and 9; keep the distinction visible from now on.

Multiple assignment and tuple unpacking

One statement can fill several names. Chained assignment gives every name the same value; assignment from a sequence spreads the values out — and because the right side is evaluated before anything is bound, swapping two names needs no temporary variable:

a = b = c = 0
print(a, b, c)

x, y = 1, 2
x, y = y, x
print(x, y)

first, last = "Ada", "Lovelace"
print(first, last)

Expected output:

0 0 0
2 1
Ada Lovelace

This pattern — called tuple unpacking — is everywhere in idiomatic Python: function returns, loop counters and column headers all lean on it. The number of names on the left must match the number of values on the right, or Python raises ValueError: not enough values to unpack.

A worked example

Everything in this chapter, in one short program. Read it, predict the output, then run it:

name = "Ada"
age = 36
height = 1.67
is_active = True

print(name, "is", age, "years old")
print("Type of height:", type(height))
print("Active account:", is_active)
print(name, age, height, is_active)
print("Next year:", age + 1)

Expected output:

Ada is 36 years old
Type of height: <class 'float'>
Active account: True
Ada 36 1.67 True
Next year: 37

Four names, four types, one print() per idea. Note that type() reports the class itself and that 1.67 printed as 1.67 rather than 1.6700000000000001 — Python trims the binary noise when the shortest round-trip form is the true one.

Common mistakes

  • Writing a declaration keyword — let total = 0 or int total = 0 is a SyntaxError; assignment alone is enough.
  • camelCase out of habit — it runs, but it reads as foreign Python; use snake_case for variables and functions.
  • Reading a name before assigning it — NameError: name 'x' is not defined usually means a typo, not a missing import.
  • Comparing floats for exact equality — 0.1 + 0.2 == 0.3 is False; chapter 5 covers the tolerance pattern.
  • Assuming None means false — it does in a condition, but as a value None is its own type; distinguishing “missing” from 0 or "" is a feature, not an annoyance.

Practice checklist

  1. Create five variables for a book (title, pages, price, in print, rating) with the correct types, and print them in one line and in five.
  2. Predict then verify type() for -3, 7.0, "", True and None.
  3. Swap two names without a temporary variable, then unpack three values into three names in a single statement.
  4. Run the mutable and immutable example, then prove the integer was untouched by printing copy after the reassignment.
  5. Rename every camelCase variable you have written so far to snake_case and rerun the programs to confirm nothing broke.

What's next?

Values are stored, named and typed; the next chapter takes the text type apart — indexing, slicing, methods and the f-string you will use in nearly every program: Strings and f-Strings.

Quiz: Variables and Data Types

5 questions · 70% to pass

Frequently Asked Questions

Python is a general-purpose language first released in 1991, designed around one idea: code is read far more often than it is written. English keywords and indentation instead of braces make it readable, the standard library covers files, JSON, dates and testing, and pip adds thousands more packages. The same language handles scripts, web APIs, data work and machine learning.

None at all. Python is widely considered the friendliest first language: no declaration keywords, no braces, no build step, and error messages that name the problem. This series begins at your first print() call. If you already read JavaScript or TypeScript you will adjust quickly, but no previous language is assumed anywhere in these 24 chapters.

Python 3 only, any release from 3.12 onwards. Python 2 reached end of life in 2021 and its print "hi" statements and xrange() no longer run. One historical quirk remains: installers ship the interpreter as python3 on macOS and Linux, while Windows usually offers python or the py launcher, and every command in this series works with that one-word swap.

More than you might expect. Everyday automation such as renaming files, cleaning spreadsheets or scraping pages; web backends with Django, Flask or FastAPI; data analysis and machine learning with pandas, NumPy and PyTorch; DevOps tooling, desktop apps and games. Python is also the classic glue language, calling C, Rust or Fortran libraries from short readable scripts.

Pure Python can run 10 to 100 times slower than C, yet that rarely blocks you: heavy numeric work lives in C extensions such as NumPy, which Python coordinates. Dynamic typing does push errors to runtime, surfacing as a TypeError on the line that finally uses the bad value. Type hints checked by mypy move those mistakes back into your editor.

Only the interpreter. Install CPython from python.org, version 3.12 or newer, confirm it with python3 --version, and open a plain text editor; VS Code with the Python extension is the recommendation here. The early chapters use no third-party packages, so there is nothing else to set up until virtual environments and pip arrive.

A dict is a real runtime mapping: keys may be any hashable value rather than only strings, insertion order has been guaranteed since Python 3.7, and a missing key raises KeyError unless you ask with get(). JavaScript objects coerce every key to a string and carry a prototype chain. A TypeScript interface is erased at compile time and describes shape only; TypedDict is Python's checked equivalent.

Reach for a list when items will be added, removed or reordered: it is ordered, mutable and rich with methods. Pick a tuple for fixed records and function returns, because it is immutable and hashable, so it can be a dictionary key. Choose a set for unique values and fast membership checks; it has no order and de-duplicates on creation.

Yes, gradually. Annotate public function signatures first; the interpreter ignores hints at runtime, so a checker such as mypy is what gives them teeth. Add tests the same way: pytest collects any test_*.py file and plain assert statements, and a suite that finishes in a tenth of a second is one you will run after every change. Both habits cost little now and much more later.

JavaScript and TypeScript keep the browser, so anything rendered to the user stays theirs. Python takes the server: Django for full-featured applications, Flask for small ones, FastAPI for typed async APIs where your annotations become automatic documentation. Your TypeScript habits transfer directly, and asyncio mirrors the event loop you already know, just with different keywords.