Source: Python Ultimate Cheat Sheet / Python 3 Cheat Sheet / Python for Data Science Cheat Sheet
Difficulty: Beginner | Prerequisites: None. This is your starting point for Python 3.
Python 3 is a general-purpose, high-level programming language used across web development, data science, automation and scientific computing. Before you can do anything useful in Python, you need to understand how it stores and manipulates data: what types of values exist, how you name them with variables, and how you perform basic operations on them. This material is the foundation for every topic that follows in the course, from control flow to functions to object-oriented programming. If you are picking up Python for the first time, this is where to begin.
Python has a handful of core data types (integers, floats, booleans, strings) and container types (lists, tuples, dicts, sets). You store values by assigning them to variable names with =. Arithmetic, comparison and logical operators let you combine and test those values. Master these basics and every later topic clicks into place.
int (integer)
A whole number with no decimal point, positive or negative: -2, 0, 42.
In simple terms, this means any counting number (or its negative). Python integers have unlimited precision, so they never overflow.
float (floating-point number)
A number with a decimal point: 9.23, 0.0, -1.7e-6.
Think of it as any number that needs fractional precision. Floats are approximations, not exact, which matters when comparing them.
bool (boolean)
One of two constant values: True or False.
In simple terms, this is Python's way of representing yes/no or on/off logic. Under the hood, True equals 1 and False equals 0.
str (string)
An ordered, immutable sequence of characters, created with single, double or triple quotes: 'hello', "hello", '''hello'''.
Think of it as text. Once you create a string, you cannot change its characters in place; methods like replace() return a new string.
bytes
An immutable sequence of integers in the range 0 to 255, written as b'...'.
In simple terms, this is raw binary data. You encounter bytes when reading files in binary mode or working with network data.
Variable
A name bound to a value via the assignment operator =. For example, x = 5 binds the name x to the integer 5.
Think of it as a label you stick on a value so you can refer to it later.
Type conversion (casting)
Changing a value from one data type to another using built-in functions like int(), float(), str(), bool().
In simple terms, this means turning a string "15" into the integer 15 so you can do arithmetic with it.
Operator
A symbol that performs an operation on one or more values (operands). Arithmetic operators include +, -, *, /, //, %, **.
Think of it as the verb in a mathematical sentence.
Expression
A combination of values, variables and operators that Python evaluates to produce a result, e.g. (1 + 5.3) * 2 evaluates to 12.6.
Identifier
The name you give a variable, function, class or module. Must start with a letter or underscore, followed by letters, digits or underscores. Case-sensitive. Cannot be a Python keyword.
int stores whole numbers: 783, 0, -192. You can also write them in binary (0b010), octal (0o642) or hex (0xF3).
float stores decimal numbers: 9.23, 0.0, -1.7e-6. These are always approximations, so floating-point arithmetic can surprise you.
bool has exactly two values: True and False. Python treats True as 1 and False as 0 in arithmetic contexts.
str is an ordered sequence of characters. Strings are immutable. Use single quotes, double quotes, or triple quotes for multi-line strings.
bytes is an immutable sequence of byte values (0-255), written as b"...". Used for binary file I/O and network data.
Assignment binds a name to a value. Python evaluates the right-hand side first, then binds the result to the left-hand name.
x = 1.2 + 8 + sin(y) evaluates the expression, then binds the result to x.
a = b = c = 0 assigns the same value to multiple names.
y, z, r = 9.2, -7.6, 0 assigns multiple values in one line (multiple assignment).
a, b = b, a swaps two values without needing a temporary variable.
a, *b = seq unpacks a sequence: first item to a, the rest as a list to b.
Augmented assignment shortcuts: x += 3 is equivalent to x = x + 3. The same pattern works with -=, *=, /=, %=.
x = None sets a variable to Python's "undefined" or "no value" constant.
del x removes the name x from the current scope entirely.
Must start with a letter (a-z, A-Z) or underscore (_), followed by letters, digits or underscores.
Case-sensitive: BigOne and bigone are different names.
Cannot be a Python keyword (e.g. and, for, if, class).
Diacritics are allowed but best avoided for portability.
Python provides built-in functions to convert between types:
int("15") returns 15. int("3f", 16) returns 63 (hex to int). int(15.56) returns 15 (truncates, does not round).
float("-11.24e8") returns -1124000000.0.
round(15.56, 1) returns 15.6. With 0 decimals it returns an integer.
bool(x) returns False for 0, 0.0, empty containers, None, or False. Returns True for everything else.
str(x) returns a human-readable string representation of x.
chr(64) returns '@'. ord('@') returns 64. These convert between characters and their Unicode code points.
list("abc") returns ['a', 'b', 'c']. Works on any iterable.
dict([(3, "three"), (1, "one")]) returns {1: 'one', 3: 'three'}.
set(["one", "two"]) returns {'one', 'two'}.
+ addition, - subtraction, * multiplication
/ true division (always returns a float): 22 / 8 returns 2.75
// integer (floor) division: 22 // 8 returns 2
% modulus (remainder): 22 % 8 returns 6
** exponentiation: 2 ** 3 returns 8
Standard order of operations applies. Use parentheses (...) to override.
Comparisons: <, >, <=, >=, ==, !=. These return True or False.
a and b returns b if a is truthy, else returns a. Both must be true for the result to be truthy.
a or b returns a if a is truthy, else returns b. At least one must be true.
not a returns the opposite boolean value.
Important: and and or return the value of one of their operands, not necessarily True or False. This is called short-circuit evaluation. Make sure your operands are booleans if you need a boolean result.
Strings can be created with single quotes, double quotes, or triple quotes (for multi-line):
my_string = "Let's Learn Python!"
another = 'It may seem difficult first, but you can do it!'
long = '''Yes, you can even master multi-line strings'''
Concatenation joins strings with +: "I'm reading " + "a great book!" produces "I'm reading a great book!".
Replication repeats a string with *: 'Alice' * 3 produces 'AliceAliceAlice'.
You cannot concatenate a string and an integer directly. Convert the integer first: str(42).
s.upper() and s.lower() return upper- or lower-case copies.
s.strip() removes leading and trailing whitespace.
s.split() splits on whitespace, returning a list. s.split(",") splits on a specific separator.
':'.join(['a', 'b', 'c']) returns 'a:b:c'.
s.replace('old', 'new') returns a copy with substitutions.
s.count('e') counts occurrences of a substring.
s.find('sub') returns the index of the first occurrence, or -1 if not found.
s.startswith('pre') and s.endswith('suf') return booleans.
s.isalpha(), s.isdigit(), s.isalnum() test character categories.
"template {}".format(value) inserts values into placeholders:
"{:+2.3f}".format(45.72793) returns '+45.728' (sign, width, 3 decimal float).
"{1:>10s}".format(8, "toto") returns ' toto' (right-aligned, width 10).
Format spec structure: fill char, alignment (< > ^ =), sign (+ - space), min width, .precision, type (d, f, s, etc.).
from math import sin, pi, sqrt, log, ceil, floor
sin(pi/4) returns approximately 0.707
sqrt(81) returns 9.0
log(e**2) returns 2.0
ceil(12.5) returns 13 (round up)
floor(12.5) returns 12 (round down)
abs(-3.2) returns 3.2
pow(4, 3) returns 64.0
Angles are in radians, not degrees.
From | To | Function | Example |
|---|---|---|---|
str | int |
|
|
str | float |
|
|
int/float | str |
|
|
any | bool |
|
|
int | char |
|
|
char | int |
|
|
Type conversions come up constantly in real programs: user input from input() always arrives as a string, so you need int() or float() before doing any maths with it. String formatting is the backbone of generating reports, log messages and any human-readable output. Boolean logic drives every if statement and loop condition you will ever write.
Students often think int() rounds a float. It does not. int(15.99) returns 15 because it truncates (chops off the decimal), not because it rounds down. Use round() if you want rounding.
Students often think = means "equals." In Python, = is the assignment operator (it binds a name to a value). The equality test is ==.
Students often think and and or always return True or False. They do not. They return the value of one of their operands. 0 and 5 returns 0, not False.
Students often think strings can be modified in place. They cannot. Strings are immutable. Methods like .upper() or .replace() return a new string; they leave the original untouched.
⚠️ Know the difference between / (true division, returns float) and // (floor division, returns int). This is a classic exam question.
⚠️ Be able to trace a chain of assignments and swaps: a, b = b, a is a favourite for "what is the value of a after this code runs?"
⚠️ Understand what bool() considers falsy: 0, 0.0, '' (empty string), [] (empty list), None, False. Everything else is truthy.
⚠️ String immutability trips up many students in coding questions. If you assign s = "hello" and then do s.upper(), the value of s is still "hello" unless you reassign: s = s.upper().
True or False: int(7.9) returns 8. (False, it returns 7, truncation not rounding.)
Fill in the blank: The operator ** performs ______. (Exponentiation.)
True or False: "hello" + 3 will produce "hello3". (False, it raises a TypeError. You need str(3).)
Fill in the blank: bool([]) returns ______. (False, because an empty list is falsy.)
True or False: After a, b = 5, 10 followed by a, b = b, a, the value of a is 10. (True.)
Q: What is the output of print(type(15.0))?
A: . Even though the number looks whole, the .0 makes it a float.
Q: Given x = "Python", what does x[0] return?
A: 'P'. Strings are indexed from 0.
Q: What is the result of 17 // 5 and 17 % 5?
A: 3 and 2, respectively. 17 // 5 gives the integer quotient, 17 % 5 gives the remainder.
Q: Write one line of code that converts the string "42" to an integer and adds 8 to it.
A: int("42") + 8 which evaluates to 50.
Q: What happens if you run print("Score: " + 100)?
A: Python raises a TypeError. You must convert the integer to a string first: print("Score: " + str(100)).
This connects to Python Data Structures (lists, tuples, dictionaries, sets) because those container types build directly on the base types covered here. Every list item, dictionary value, or set member is one of these fundamental types.
This connects to Control Flow because if statements and while loops rely on boolean expressions, comparison operators, and the truthiness rules you have just learned.
This connects to Functions because parameters and return values are typed objects, and understanding type conversion is essential for writing functions that accept flexible input.
Python data types, int float bool str bytes, variable assignment, multiple assignment, augmented assignment, type casting, type conversion, int(), float(), str(), bool(), arithmetic operators, modulus, floor division, exponentiation, comparison operators, boolean logic, and or not, short-circuit evaluation, string concatenation, string replication, string methods, split join replace strip, string formatting, format(), identifiers, naming conventions, Python 3 basics, beginner Python