Skip to content
  • Variables, Types & Operators · Python

Variables, Types & Operators

LearnViaNotes @learnvianotes· 2 min read

A variable is a name bound to an object. Every object has an identity, a type and a value.

Built-in types

TypeExampleMutable?
int42, -7, 10**100 (unlimited size)No
float3.14, 1e-9 (64-bit IEEE 754)No
complex2 + 3jNo
boolTrue, False (a subclass of int)No
str'hi', "hi", '''multi'''No
NoneTypeNone — the single “no value” objectNo
list / dict / set[1, 2], {'a': 1}, {1, 2}Yes
tuple / frozenset(1, 2), frozenset({1})No
Python
x = 10
print(type(x))                    # <class 'int'>
x = "now a string"                # same name, different object and type
print(isinstance(x, str))         # True
print(True + True)                # 2

Operators at a glance

Arithmetic + - * / // % **, comparison == != < <= > >= (chainable), logical and or not, identity is, membership in, bitwise & | ^ ~ << >> and the walrus :=. The next topic, Operators & Precedence, covers each one in depth.

Python
print(7 / 2, 7 // 2, 7 % 2, -7 // 2)   # 3.5 3 1 -4
print(2 ** 10, divmod(17, 5))          # 1024 (3, 2)
print(0 < 5 < 10)                      # True
print("" or "default", 0 and 99)       # default 0
if (n := len("hello")) > 3:
    print(n)                           # 5

== vs is

Python
a = [1, 2, 3]
b = [1, 2, 3]
c = a
print(a == b, a is b, a is c)   # True False True

Truthiness

In a condition, every object is truthy except these falsy values:

False · None · 0, 0.0, 0j · '' · [] · () · {} · set() · range(0)

Python
items = []
if not items:              # idiomatic emptiness check
    print("empty")         # empty
print(bool("0"), bool(0))  # True False

Type conversion

Python
print(int("42") + 1, float("2.5"), str(99) + "!")   # 43 2.5 99!
print(int(3.99), round(2.5), round(3.5))            # 3 2 4
print(int("ff", 16), bin(10), hex(255))             # 255 0b1010 0xff

Free for students and teachers

Write notes like this one

Cards for every idea, quizzes and flashcards, read aloud — on the web and your phone.

Something wrong with this note? Open it to report