Variables & Types
12 min
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.
Run this to see how the same variable name can point at different types over its lifetime.
Python's built-in scalar types you'll use constantly:
int— whole numbers:5,-12,1_000_000float— decimals:3.14,-0.5str— text:"hello",'also fine'bool—True/FalseNone— Python's "nothing here" value (likenull)
Mixing int and float in an expression (e.g. 5 / 2) automatically
produces a float. Integer division uses // instead.
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.
Write a function `swap(a, b)` that returns a tuple `(b, a)` — swap the two values using tuple unpacking, without a temporary variable.
What does `type(5.0)` return in Python?
You can now create variables and reason about Python's dynamic typing.