Python Functions & Formulas
Complete Reference Guide
1. Built-In Functions
1.1 Input / Output
Function / Formula Description Example
print(value) Print value to the console print("Hello")
input(prompt) Read a string from the user name = input("Name: ")
print(end='') Print without a newline print('Hi', end='')
print(sep=',') Print items with custom separator print(1,2,3, sep=',')
1.2 Type Conversion (Typecasting)
Function / Formula Description Example
int(x) Convert x to integer int('42') → 42
float(x) Convert x to float float('3.14') → 3.14
str(x) Convert x to string str(100) → '100'
bool(x) Convert x to boolean bool(0) → False
complex(x) Convert x to complex number complex(2) → (2+0j)
list(x) Convert x to list list('abc') → ['a','b','c']
tuple(x) Convert x to tuple tuple([1,2]) → (1,2)
set(x) Convert x to set set([1,1,2]) → {1,2}
dict(x) Convert to dictionary dict(a=1) → {'a':1}
chr(n) Integer to ASCII character chr(65) → 'A'
ord(c) Character to ASCII integer ord('A') → 65
hex(n) Integer to hex string hex(255) → '0xff'
bin(n) Integer to binary string bin(10) → '0b1010'
oct(n) Integer to octal string oct(8) → '0o10'
1.3 Numeric Functions
Function / Formula Description Example
abs(x) Absolute value abs(-7) → 7
round(x, n) Round to n decimal places round(3.567, 2) → 3.57
pow(x, y) x raised to the power y pow(2, 8) → 256
max(iter) Largest item in iterable max([3,1,4]) → 4
min(iter) Smallest item in iterable min([3,1,4]) → 1
sum(iter) Sum of items in iterable sum([1,2,3]) → 6
divmod(a, b) Returns (quotient, remainder) divmod(10,3) → (3,1)
1.4 Sequence / Iterable Functions
Function / Formula Description Example
len(x) Length of sequence len('Hello') → 5
range(n) Sequence 0 to n-1 range(5) → 0,1,2,3,4
range(a,b,s) Sequence a to b-1, step s range(1,10,2) → 1,3,5,7,9
sorted(iter) Return sorted list sorted([3,1,2]) → [1,2,3]
reversed(iter) Return reversed iterator list(reversed([1,2,3]))
enumerate(iter) Index + value pairs for i,v in
enumerate(['a','b'])
zip(a, b) Combine two iterables zip([1,2],['a','b'])
map(fn, iter) Apply function to each item list(map(str,[1,2,3]))
filter(fn,iter) Filter items where fn returns True list(filter(bool,[0,1,2]))
any(iter) True if any element is True any([0,0,1]) → True
all(iter) True if all elements are True all([1,1,1]) → True
1.5 Object / Utility Functions
Function / Formula Description Example
type(x) Return type of x type(3.14) →
isinstance(x,T) Check if x is instance of T isinstance(3, int) → True
id(x) Return memory address of x id(x)
Function / Formula Description Example
dir(x) List attributes/methods of x dir(str)
help(x) Display help documentation help(print)
callable(x) Check if x is callable callable(print) → True
hasattr(o,n) Check if object has attribute hasattr(str,'upper')
getattr(o,n) Get attribute value of object getattr(str,'upper')
vars(o) Return __dict__ of object vars(obj)
open(file,mode) Open a file open('[Link]','r')
format(v,spec) Format a value format(3.14,'.1f') → '3.1'
2. String Methods
2.1 Case & Search
Function / Formula Description Example
.upper() Convert to uppercase "hello".upper() → "HELLO"
.lower() Convert to lowercase "HELLO".lower() → "hello"
.title() Title-case each word "hello world".title()
.capitalize() Capitalise first character "hello".capitalize()
.swapcase() Swap upper/lower case "Hello".swapcase() → "hELLO"
.find(sub) Index of first occurrence (-1 if not found) "hello".find("l") → 2
.index(sub) Index of first occurrence (error if not found) "hello".index("l")
.count(sub) Count occurrences of sub "hello".count("l") → 2
.startswith(s) True if string starts with s "hello".startswith("he")
.endswith(s) True if string ends with s "hello".endswith("lo")
.in operator True if sub is in string "ell" in "hello" → True
2.2 Trimming & Replacing
Function / Formula Description Example
.strip() Remove leading/trailing whitespace " hi ".strip() → "hi"
.lstrip() Remove leading whitespace " hi ".lstrip()
.rstrip() Remove trailing whitespace " hi ".rstrip()
.replace(a,b) Replace all occurrences of a with b 'cat'.replace('c','b') →
'bat'
.split(sep) Split into list by separator "a,b,c".split(",")
.join(iter) Join iterable with string ",".join(["a","b","c"])
.zfill(n) Pad with zeros on the left "7".zfill(3) → "007"
.center(n) Centre string within width n "hi".center(10)
.ljust(n) Left-justify within width n "hi".ljust(10)
.rjust(n) Right-justify within width n "hi".rjust(10)
2.3 Checking & Formatting
Function / Formula Description Example
.isdigit() True if all characters are digits "123".isdigit() → True
.isalpha() True if all characters are letters "abc".isalpha() → True
.isalnum() True if letters or digits only "abc1".isalnum() → True
.isspace() True if only whitespace " ".isspace() → True
.isupper() True if all uppercase "ABC".isupper() → True
.islower() True if all lowercase "abc".islower() → True
f-strings Embed variables directly in string f"Hello {name}!"
.format() Format string with placeholders "Hi {}".format("Bob")
len(str) Number of characters in string len("hello") → 5
[start:end:step] Slice a string "hello"[1:4] → "ell"
3. List Methods
Function / Formula Description Example
.append(x) Add x to end of list [Link](5)
.insert(i, x) Insert x at index i [Link](0, 'a')
.extend(iter) Add all items of iter to list [Link]([4,5,6])
.remove(x) Remove first occurrence of x [Link](3)
.pop(i) Remove and return item at index i [Link]() # last item
.clear() Remove all items [Link]()
.index(x) Index of first occurrence of x [Link](7)
.count(x) Count occurrences of x [Link](2)
.sort() Sort list in place [Link](reverse=True)
.reverse() Reverse list in place [Link]()
.copy() Return a shallow copy lst2 = [Link]()
sorted(lst) Return new sorted list sorted(lst)
len(lst) Number of items len(lst)
lst[i] Access element at index i lst[0] # first item
lst[a:b] Slice from a to b-1 lst[1:4]
4. Dictionary Methods
Function / Formula Description Example
.get(key, def) Return value or default [Link]("x", 0)
.keys() Return all keys [Link]()
.values() Return all values [Link]()
.items() Return key-value pairs [Link]()
.update(d2) Merge d2 into dictionary [Link]({'b':2})
.pop(key) Remove and return value for key [Link]('name')
.popitem() Remove and return last pair [Link]()
.clear() Remove all items [Link]()
.copy() Return a shallow copy d2 = [Link]()
.setdefault(k,v) Set key if not present [Link]('x',0)
key in d Check if key exists "name" in d → True
len(d) Number of key-value pairs len(d)
5. Math Module (import math)
5.1 Rounding & Powers
Function / Formula Description Example
[Link](x) Round down to nearest integer [Link](3.9) → 3
[Link](x) Round up to nearest integer [Link](3.1) → 4
[Link](x) Truncate decimal part [Link](3.9) → 3
[Link](x) Square root of x [Link](16) → 4.0
[Link](x,y) x raised to power y (float) [Link](2,10) → 1024.0
[Link](x) e raised to the power x [Link](1) → 2.718...
[Link](x) Natural logarithm of x [Link](math.e) → 1.0
[Link](x,b) Logarithm of x to base b [Link](100,10) → 2.0
math.log2(x) Base-2 logarithm math.log2(8) → 3.0
math.log10(x) Base-10 logarithm math.log10(1000) → 3.0
[Link](x) Absolute value as float [Link](-3) → 3.0
[Link](n) Factorial of n [Link](5) → 120
[Link](a,b) Greatest common divisor [Link](12,8) → 4
5.2 Trigonometry & Constants
Function / Formula Description Example
[Link] Value of pi (3.14159...) [Link] → 3.14159...
math.e Euler's number (2.71828...) math.e → 2.71828...
[Link] Positive infinity [Link]
[Link](x) Sine of x (radians) [Link]([Link]/2) → 1.0
[Link](x) Cosine of x (radians) [Link](0) → 1.0
[Link](x) Tangent of x (radians) [Link]([Link]/4) → 1.0
[Link](x) Convert radians to degrees [Link]([Link]) →
180.0
[Link](x) Convert degrees to radians [Link](180) → 3.14...
[Link](a,b) Hypotenuse of right triangle [Link](3,4) → 5.0
6. Random Module (import random)
Function / Formula Description Example
[Link]() Float between 0.0 and 1.0 [Link]() → 0.573...
[Link](a,b) Integer between a and b inclusive [Link](1,6) → 4
[Link](a,b) Float between a and b [Link](1.0,5.0)
[Link](seq) Random item from sequence [Link](['a','b','c'])
[Link](seq,k=n) n random items with replacement [Link](lst, k=3)
[Link](seq,k) k unique random items [Link](lst, 3)
[Link](lst) Shuffle list in place [Link](my_list)
[Link](n) Set seed for reproducibility [Link](42)
[Link](a,b,s) Random int in range(a,b,s) [Link](0,10,2)
7. Operators & Expressions
7.1 Arithmetic Operators
Function / Formula Description Example
x + y Addition 5 + 3 → 8
x - y Subtraction 5 - 3 → 2
x * y Multiplication 5 * 3 → 15
x / y Division (float result) 7 / 2 → 3.5
x // y Floor division (int result) 7 // 2 → 3
x % y Modulus (remainder) 7 % 2 → 1
x ** y Exponentiation 2 ** 8 → 256
7.2 Comparison Operators
Function / Formula Description Example
x == y Equal to 5 == 5 → True
x != y Not equal to 5 != 3 → True
x > y Greater than 5 > 3 → True
x < y Less than 3 < 5 → True
x >= y Greater than or equal 5 >= 5 → True
x <= y Less than or equal 3 <= 5 → True
7.3 Logical & Assignment Operators
Function / Formula Description Example
and True if both are True x > 0 and x < 10
or True if at least one is True x < 0 or x > 100
not Invert boolean value not True → False
x += n Add and assign x += 5 (same as x = x+5)
x -= n Subtract and assign x -= 3
x *= n Multiply and assign x *= 2
x /= n Divide and assign x /= 4
Function / Formula Description Example
x //= n Floor divide and assign x //= 2
x %= n Modulus and assign x %= 3
x **= n Exponent and assign x **= 2
8. File Handling
Function / Formula Description Example
open(f,'r') Open file for reading f = open('[Link]','r')
open(f,'w') Open file for writing (overwrites) f = open('[Link]','w')
open(f,'a') Open file for appending f = open('[Link]','a')
open(f,'x') Create new file (error if exists) f = open('[Link]','x')
.read() Read entire file as string content = [Link]()
.readline() Read one line line = [Link]()
.readlines() Read all lines into list lines = [Link]()
.write(str) Write string to file [Link]("Hello")
.writelines(lst) Write list of strings to file [Link](lines)
.close() Close the file [Link]()
with open(f) as f Auto-close after block with open("[Link]") as f:
.seek(n) Move to byte position n [Link](0) # start
.tell() Return current byte position pos = [Link]()
9. Exception Handling
Function / Formula Description Example
try / except Catch and handle exceptions try: x=int('a') except
ValueError:
except Exception as e Catch any exception with detail except Exception as e:
print(e)
else Run if no exception occurred try:... except:... else:...
finally Always runs, exception or not finally: [Link]()
raise Exception(msg) Manually raise an exception raise ValueError("Bad
input")
ValueError Wrong value type provided int('abc')
TypeError Wrong data type used 1 + 'a'
IndexError List index out of range lst[99]
KeyError Dict key not found d['missing']
ZeroDivisionError Division by zero 5 / 0
FileNotFoundError File does not exist open("[Link]")
NameError Variable not defined print(undefined_var)
10. Defining Functions
Function / Formula Description Example
def fn(params): Define a function def greet(name):
return value Return a value from function return [Link]()
def fn(x=default): Parameter with default value def add(x, y=0):
def fn(*args): Accept any number of positional args def total(*nums):
def fn(**kwargs): Accept keyword arguments as dict def show(**info):
lambda x: expr Anonymous one-line function sq = lambda x: x**2
fn.__doc__ Access docstring of function def fn(): """doc"""
global var Use global variable inside fn global counter
nonlocal var Use enclosing scope variable nonlocal total
return a, b Return multiple values as tuple return x, y
isinstance(x,type) Type check inside function isinstance(x, int)
11. Quick Reference Cheat Sheet
Category Most Used Functions
Output print()
Input input()
Type Conversion int() float() str() bool() list() tuple() set()
Numeric abs() round() pow() max() min() sum() divmod()
String Methods .upper() .lower() .strip() .split() .replace() .find() .format()
List Methods .append() .pop() .sort() .reverse() .extend() .insert()
Dict Methods .get() .keys() .values() .items() .update() .pop()
Math Module [Link]() [Link]() [Link]() [Link] [Link]()
Random Module [Link]() [Link]() [Link]() [Link]()
Sequence len() range() sorted() reversed() enumerate() zip()
File Handling open() .read() .write() .close() with open() as f:
Exceptions try / except / else / finally raise
Operators + - * / // % ** == != > < and or not
Python Functions & Formulas Reference Guide | Covers Python 3.x | Generated for educational use