Variables and Constants

How variables are defined and reused, and how literals are expressed.

Python Language


Defining a Variable

How to define a variable of a specific datatype.

Error Loading

Missing

Variables

x = 100

Defining a Constant

How to define an immutable variable.

Missing

Constants

Python does not have true constants, but conventionally, uppercase names indicate constants.

PI: float = 3.1415 # Convention for constants (not enforced) count: int = 10 # Mutable variable count += 1 # Allowed
  • Variables are dynamically typed unless explicitly hinted.

Complex Literals

Native support for literal complex datatypes (non-primitive types).

Missing

Literals

Python has a few native literals.

my_int = 10 my_binary = 0b1010 my_octal = 0o12 my_hex = 0xA my_float = 10.5 my_sci_not = 2.0e3 my_complex = 3 + 4j my_bool = True my_None = None

For strings, multi-line and raw strings are supported:

my_str = 'hello' my_str_double = "hello" my_multi_line = """hello there""" my_raw = r"New\nLine" -- ignores escape sequences my_formatted = f"Hello {name}"

The complex type literals are as follows:

my_list = [1, 2, 3] my_tuple = (1,2,3) -- note that Tuple types are separate to arrays in python my_single_tuple = (42,) -- special syntax single-element tuple my_dict = {"key": "value", "age": 30} my_set = {1, 2, 3} my_empty_set = set() -- avoid confusion with empty dict my_bytes = b"hello"` my_byte_array = bytearray(b"hello")