Latticework

Command Palette

Search for a command to run...

Python

Variables & Types

12 min

Explanation

Python variables don't need a declared type — you just assign a value, and Python figures out the type from the value itself. This is called dynamic typing.

x = 5        # x is an int
x = "hello"  # now x is a str — same variable, different type

There's no int x = 5; like in Java or C++. The name x is just a label pointing at whatever object you last assigned to it.

Try it

Run this to see how the same variable name can point at different types over its lifetime.

Loading editor…
Explanation

Python's built-in scalar types you'll use constantly:

  • int — whole numbers: 5, -12, 1_000_000
  • float — decimals: 3.14, -0.5
  • str — text: "hello", 'also fine'
  • boolTrue / False
  • None — Python's "nothing here" value (like null)

Mixing int and float in an expression (e.g. 5 / 2) automatically produces a float. Integer division uses // instead.

Exercise

Write a function `fahrenheit_to_celsius(f)` that converts a Fahrenheit temperature to Celsius using the formula (f - 32) * 5 / 9, and returns the result.

Exercise

Write a function `swap(a, b)` that returns a tuple `(b, a)` — swap the two values using tuple unpacking, without a temporary variable.

Quiz

What does `type(5.0)` return in Python?

Checkpoint

You can now create variables and reason about Python's dynamic typing.