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.
Assignment uses a single equals sign. The name goes on the left, and the value on the right:
1name = "echo"
2port = 1337There is no declaration step and no type to write. The first assignment creates the name, and later assignments point it somewhere else:
1port = 1337
2port = 31337 # port now refers to a different intPython can assign several names at once. The values on the right are matched up with the names on the left, in order:
host, port = "localhost", 1337 # host = "localhost", port = 1337Because the whole right side is evaluated before any name changes, this also swaps two variables without a temporary:
1a, b = 1, 2
2a, b = b, a # a = 2, b = 1Assigning the same value to several names uses chained assignment:
x = y = 0 # x = 0, y = 0Python 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 --.
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:
1max_retries = 5
2BUFFER_SIZE = 4096list, 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.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.
1value = 42
2value = "forty-two" # allowed: the name now refers to a strThe built-in type() function reports an object's type, and isinstance() checks it:
1type(42) # Return: <class 'int'>
2type("42") # Return: <class 'str'>
3isinstance(42, intDynamic 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:
1>>> "Port: " + 1337
2Traceback (most recent call last):
3 File "<stdin>", line 1, in <You convert explicitly instead, by calling the type you want:
1"Port: " + str(1337) # Return: 'Port: 1337'
2int("1337") + 1 # Return: 1338
3Converting 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.
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.
Python's most common built-in types are:
int, float, complexboolstrbytes, bytearraylist, tuple, rangeset, frozensetdictNone, the only value of NoneTypeThe rest of this section gives a quick tour; most of these types get a lesson of their own.
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:
12 ** 64 # Return: 18446744073709551616
22 ** 64 + 1 # Return: 18446744073709551617Integer literals can be written in other bases with a prefix, and hex(), bin() and oct() go the other way:
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 ==:
10.1 + 0.2 # Return: 0.30000000000000004
20.1 + 0.2 == 0.3 # Return: FalsePython 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:
17 / 2 # Return: 3.5
26 / 2 # Return: 3.0
37 // 2 # Return: 3% 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.
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:
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.
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:
1ports = [22, 80, 443] # list
2point = (3, 4) # tuple
These are covered in detail, along with sets, in Lists, Tuples & Sets.
A dict maps keys to values, much like a hash table:
1user = {"name": "echo", "uid": 1000}
2user["uid"] # Return: 1000Dictionaries get their own lesson in Dictionaries.
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 ==:
1result = None
2if result is None:
3 print("nothing yet")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.
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:
1s = "hack"
2before = id(s)
3s += "er"
4s # Return: 'hacker'
5Trying to change part of an immutable object in place is an error:
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.
list, dict, set and bytearray are mutable. Their methods change the object itself, and every name that refers to it sees the change:
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:
1a = [1, 2, 3]
2b = a.copy() # or list(a), or a[:]
3b.appendA 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:
1import copy
2
3grid = [[0, 0], [0, 0]]
4*[[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:1bad = [[0] * 3] * 3
2The same rule explains how functions behave with their arguments, which is covered in Pass by Reference vs. Pass by Value.