Table of Contents
IronForgeCyber
Courses
Resources
Blog
Log In


IronForgeCyber

AboutPrivacyTerms

© 2026 IronForgeCyber. All rights reserved.

  1. courses
  2. python
  3. variables
11 min read

Variables & Types

A variable is a name that refers to a value, so the rest of the program can use that value without repeating it. In C, a variable is a box of a fixed size and type: int x reserves four bytes that can only ever hold an integer. Python works differently. Values are objects that live on their own, and a variable is just a label attached to one. That one difference explains most of what follows: why a variable can hold an int and then a str, why changing a list through one name changes it through another, and why some types can be changed in place while others cannot.

Variable Assignment

Assignment uses a single equals sign. The name goes on the left, and the value on the right:

python
1name = "echo"
2port = 1337

There is no declaration step and no type to write. The first assignment creates the name, and later assignments point it somewhere else:

python
1port = 1337
2port = 31337    # port now refers to a different int

Python can assign several names at once. The values on the right are matched up with the names on the left, in order:

python
host, port = "localhost", 1337    # host = "localhost", port = 1337

Because the whole right side is evaluated before any name changes, this also swaps two variables without a temporary:

python
1a, b = 1, 2
2a, b = b, a    # a = 2, b = 1

Assigning the same value to several names uses chained assignment:

python
x = y = 0    # x = 0, y = 0

Python also has augmented assignment operators that combine an operation with assignment. x += 1 is shorthand for x = x + 1, and the same works for -=, *=, /=, //=, %=, **= and the bitwise operators. There is no ++ or --.

Naming Variables

Names can contain letters, digits and underscores, but cannot start with a digit. They are case-sensitive, so count and Count are two different variables. A handful of keywords such as if, for, class and None are reserved and cannot be used as names.

By convention (PEP 8), variables and functions use snake_case, constants use UPPER_CASE, and classes use CapWords:

python
1max_retries = 5
2BUFFER_SIZE = 4096
Don't shadow built-ins
Python will happily let you name a variable list, str, input, max or id. Doing so hides the built-in function of the same name for the rest of that scope, and the next call to list(...) fails with a confusing TypeError: 'list' object is not callable.

Dynamic Typing

Python is dynamically typed: names have no type, but objects do. A name can refer to an int on one line and a str on the next, and Python only checks whether an operation makes sense when that operation runs.

python
1value = 42
2value = "forty-two"    # allowed: the name now refers to a str

The built-in type() function reports an object's type, and isinstance() checks it:

python
1type(42)                  # Return: <class 'int'>
2type("42")                # Return: <class 'str'>
3isinstance(42, int

Dynamic does not mean loose. Python is also strongly typed: it will not silently convert between unrelated types the way JavaScript or C sometimes do. Adding a string to a number is an error, not a guess:

python
1>>> "Port: " + 1337
2Traceback (most recent call last):
3  File "<stdin>", line 1, in <

You convert explicitly instead, by calling the type you want:

python
1"Port: " + str(1337)    # Return: 'Port: 1337'
2int("1337") + 1         # Return: 1338
3

Converting text to numbers this way is the first step of almost every challenge: input arrives as strings, and int() turns each piece into something you can do math with. int() raises a ValueError if the string is not a valid number.

Type hints
You will see annotations like port: int = 1337 in modern code. These are type hints: documentation that tools like editors and type checkers read. Python itself ignores them when the program runs, so they never stop you from assigning a different type.

Where a name can be used, its scope, depends on where it was assigned. That is covered with functions, in Variable Scope.

Data Types

Python's most common built-in types are:

  • Numeric types: int, float, complex
  • Boolean type: bool
  • Text type: str
  • Binary types: bytes, bytearray
  • Sequence types: list, tuple, range
  • Set types: set, frozenset
  • Mapping type: dict
  • The null type: None, the only value of NoneType

The rest of this section gives a quick tour; most of these types get a lesson of their own.

Numbers

An int is a whole number, and it has no maximum size. Where C's int overflows past about two billion, Python just keeps going, which matters a lot in cryptography challenges full of enormous numbers:

python
12 ** 64          # Return: 18446744073709551616
22 ** 64 + 1      # Return: 18446744073709551617

Integer literals can be written in other bases with a prefix, and hex(), bin() and oct() go the other way:

python
10x539            # Return: 1337
20b101            # Return: 5
30o17             # Return: 15
4hex(1337)        # Return: '0x539'

Underscores can be used to group digits in long literals: 1_000_000 is the same as 1000000.

A float is a number with a decimal point, stored as a 64-bit IEEE 754 double. Floats are approximate, so avoid comparing them with ==:

python
10.1 + 0.2              # Return: 0.30000000000000004
20.1 + 0.2 == 0.3       # Return: False

Python has two division operators. / always produces a float, even when the division is exact. // is floor division: it rounds down to the nearest whole number. % gives the remainder, and ** raises to a power:

python
17 / 2       # Return: 3.5
26 / 2       # Return: 3.0
37 // 2      # Return: 3
Warning
Floor division and % round toward negative infinity, unlike C, which rounds toward zero. -7 // 2 is -4 in Python but -3 in C, and -7 % 2 is 1 in Python but -1 in C. Keep this in mind when porting C code.

A bool is either True or False. Booleans are a kind of int, with True == 1 and False == 0, which is why sum() over a list of booleans counts the True values.

complex numbers such as 3 + 4j exist too, but you will rarely need them.

Strings

A str is a sequence of Unicode characters, written in single, double or triple quotes as covered in Basic Syntax. Strings support indexing and len(), and + and * join and repeat them:

python
1flag = "flag{example}"
2flag[0]         # Return: 'f'
3len(flag)       # Return: 13
4"ab"

That last line is a staple of exploit scripts, where you need a run of padding bytes. Strings get their own lesson in Strings, and their raw-byte counterpart, bytes, in Bytes & Encoding.

Sequences

A sequence holds items in order, accessed by an index starting at 0. A list can grow, shrink and change. A tuple is fixed once created. A range represents a run of integers without storing them all:

python
1ports = [22, 80, 443]          # list
2point = (3, 4)                 # tuple

These are covered in detail, along with sets, in Lists, Tuples & Sets.

Mappings

A dict maps keys to values, much like a hash table:

python
1user = {"name": "echo", "uid": 1000}
2user["uid"]     # Return: 1000

Dictionaries get their own lesson in Dictionaries.

None

None represents the absence of a value, like NULL in C. A function that doesn't return anything returns None, and it is a common placeholder before a variable has a real value. There is only one None object, so check for it with is, not ==:

python
1result = None
2if result is None:
3    print("nothing yet")

Mutable vs Immutable

Every type is either mutable, meaning an object of that type can be changed after it is created, or immutable, meaning it cannot. This matters because several names can refer to the same object.

The built-in id() function returns a number that identifies an object for as long as it exists, which makes it easy to see when two names refer to the same object and when an operation created a new one. The is operator compares identity directly: a is b is True when a and b are the same object.

Immutable Types

int, float, bool, str, tuple, bytes and frozenset are immutable. Operations that look like they change one actually build a new object and point the name at it:

python
1s = "hack"
2before = id(s)
3s += "er"
4s                    # Return: 'hacker'
5

Trying to change part of an immutable object in place is an error:

python
1>>> s = "hack"
2>>> s[0] = "j"
3Traceback (most recent call last):

Since an immutable object can never change, it is safe to share it between any number of names. Immutability is also what makes these types usable as dictionary keys.

Mutable Types

list, dict, set and bytearray are mutable. Their methods change the object itself, and every name that refers to it sees the change:

python
1a = [1, 2, 3]
2b = a            # b refers to the same list, not a copy
3b.append(4)

This is called aliasing, and it is the source of a classic bug: you pass a list to a function or store it in two places, change it in one, and are surprised when the other changes too. When you need an independent copy, ask for one:

python
1a = [1, 2, 3]
2b = a.copy()     # or list(a), or a[:]
3b.append

A copy() is shallow: it copies the outer container, but the items inside are still shared. For a list of lists, use copy.deepcopy() to copy every level:

python
1import copy
2
3grid = [[0, 0], [0, 0]]
4
Building a grid with *
[[0] * 3] * 3 looks like a 3×3 grid, but the outer * repeats a reference to the same inner list three times, so setting one cell changes a whole column. Build grids with a comprehension instead, which creates a new inner list for each row:
python
1bad = [[0] * 3] * 3
2

The same rule explains how functions behave with their arguments, which is covered in Pass by Reference vs. Pass by Value.

)
# Return: True
4isinstance(True, int) # Return: True, since bool is a subclass of int
module
>
4TypeError: can only concatenate str (not "int") to str
float
(
"2.5"
)
# Return: 2.5
4int("0x539", 16) # Return: 1337
5bin(5) # Return: '0b101'
4-7 // 2 # Return: -4, rounded down, not toward zero
57 % 2 # Return: 1
62 ** 10 # Return: 1024
+
"cd"
# Return: 'abcd'
5"A" * 8 # Return: 'AAAAAAAA'
3
list
(
range
(
5
)
)
# Return: [0, 1, 2, 3, 4]
id
(
s
)
==
before
# Return: False, s now refers to a new string
4 File "<stdin>", line 1, in <module>
5TypeError: 'str' object does not support item assignment
4a # Return: [1, 2, 3, 4]
5a is b # Return: True
(
4
)
4a # Return: [1, 2, 3]
shallow
=
grid
.
copy
(
)
5deep = copy.deepcopy(grid)
6
7grid[0][0] = 1
8shallow[0][0] # Return: 1, the inner lists are shared
9deep[0][0] # Return: 0
bad
[
0
]
[
0
]
=
1
# bad = [[1, 0, 0], [1, 0, 0], [1, 0, 0]]
3
4good = [[0] * 3 for _ in range(3)]
5good[0][0] = 1 # good = [[1, 0, 0], [0, 0, 0], [0, 0, 0]]