Complete reference covering syntax, data structures, control flow, functions, OOP, file I/O, exceptions, decorators, generators, lambdas, regex, datetime, and common libraries (NumPy, Pandas). Ideal for beginners and pros. Quick lookup with table of contents.
- Basic Syntax & Operators
- Data Types & Structures
- Control Flow
- Functions
- Modules & Packages
- File Handling
- Error & Exception Handling
- Object-Oriented Programming (OOP)
- List Comprehensions & Generators
- Lambda & Functional Tools
- Decorators
- Working with Dates & Times
- Regular Expressions
- Common Built-in Functions
- Useful Libraries (Quick Start)
# Single-line comment""" Multi-line comment """# Printing outputprint("Hello", "World", sep="-", end="!\n") # Hello-World!# Taking inputname=input("Enter name: ") # always returns stringage=int(input("Enter age: ")) # type conversion# Variables (dynamic typing, snake_case convention)x=10# intpi=3.14# floatis_valid=True# bool (True/False)message="Hi"# str# Type checkingtype(x) # <class 'int'>isinstance(x, int) # True# Arithmetic: + - * / % // **5/2# 2.5 (float division)5//2# 2 (integer division)5**2# 25 (exponent)# Comparison: == != < > <= >=# Logical: and, or, not# Assignment: = += -= *= /= //= %= **=s="python"s[0] # 'p' (indexing)s[-1] # 'n's[1:4] # 'yth' (slicing start:stop:step)s[::-1] # 'nohtyp' (reverse)# Methodss.upper() # 'PYTHON's.lower() s.capitalize()
s.title()
s.strip() # remove whitespaces.replace("py", "PY")
s.split(",") # list from string",".join(["a","b"]) # 'a,b'f"Value = {x}"# f-string formatting"Value = {}".format(x)lst= [1, 2, 3]
lst.append(4) # [1,2,3,4]lst.extend([5,6]) # [1,2,3,4,5,6]lst.insert(0, 0) # [0,1,2,3,...]lst.pop() # removes last, returns itlst.pop(2) # remove index 2lst.remove(3) # remove first 3lst.index(2) # first index of 2lst.sort() # in-place sortsorted(lst) # returns new sorted listlst.reverse()
len(lst)
dellst[2] # delete by indext= (1, 2, 3)
t=1, 2, 3# packinga, b, c=t# unpackingt.count(2) # 1t.index(2) # 1d= {"a": 1, "b": 2}
d["c"] =3d.get("x", 0) # 0 if missing, avoids KeyErrord.keys()
d.values()
d.items() # view of (key,value) pairsfork, vind.items():
print(k, v)
d.pop("a") # remove key 'a'deld["b"]Dict comprehension:
{x: x**2forxinrange(5)}s= {1, 2, 3}
s.add(4)
s.remove(2)
s.union({3,4}) # | operators.intersection({2,3}) # & operators.difference({3}) # - operatorifcondition:
passelifother_condition:
passelse:
pass# Ternary operatorresult="Even"ifx%2==0else"Odd"# While loopwhilecount<5:
print(count)
count+=1else: # runs if no break occurredprint("Loop finished normally")
# For loop over iterableforiinrange(5): # 0,1,2,3,4foriinrange(2, 10, 2): # 2,4,6,8foridx, valinenumerate(lst):
forkey, valindict.items():
foriteminreversed(lst):
# Loop controlbreak# exit loopcontinue# skip to next iterationpass# placeholder, does nothingdeffunction_name(param1, param2="default"):
"""Docstring: explains function."""result=param1+param2returnresult# Callfunction_name(5, 6)
# Variable number of argumentsdeffunc(*args): # tuple of positional argsdeffunc(**kwargs): # dict of keyword args# Exampledefsum_all(*nums):
returnsum(nums)
sum_all(1,2,3,4) # 10defprint_info(**data):
fork,vindata.items():
print(f"{k}: {v}")
print_info(name="Alice", age=30)
# Mixed order: standard, *args, **kwargsdefexample(a, b, *args, option=True, **kwargs):
pass# Type hints (Python 3.5+)defadd(x: int, y: int) ->int:
returnx+y# Import a moduleimportmathmath.sqrt(25)
# Specific importfrommathimportsqrt, pisqrt(25)
# Aliasimportnumpyasnp# Import everything (not recommended)fromosimport*# Your own module: save as mymodule.pyimportmymodule# Package: directory with __init__.pyfrommypackageimportmymodule# Useful built-in modules: os, sys, datetime, json, re, random, math, collections, itertools, functools# Read filewithopen("file.txt", "r") asf:
content=f.read() # entire fileline=f.readline() # one linelines=f.readlines() # list of lines# Write/overwritewithopen("file.txt", "w") asf:
f.write("Hello\n")
f.writelines(["line1\n", "line2\n"])
# Appendwithopen("file.txt", "a") asf:
f.write("append this")
# Modes: r (read), w (write, truncates), a (append), x (exclusive create), b (binary), t (text, default)# Combine: "rb", "wb", "r+", etc.# JSON handlingimportjsondata= {"name": "Alice", "age": 30}
withopen("data.json", "w") asf:
json.dump(data, f)
withopen("data.json", "r") asf:
loaded=json.load(f)# Basic try/excepttry:
risky_code()
exceptValueErrorase:
print(f"Value error: {e}")
except (TypeError, ZeroDivisionError):
print("Math error")
exceptExceptionase: # catches any exceptionprint(f"Unexpected: {e}")
else:
print("No error occurred")
finally:
print("Always runs (closing resources, etc.)")
# Raising exceptionsifx<0:
raiseValueError("x cannot be negative")
# Custom exceptionclassMyError(Exception):
passraiseMyError("Something went wrong")classDog:
# Class attributespecies="Canis familiaris"# Constructordef__init__(self, name, age):
self.name=name# instance attributeself.age=age# Instance methoddefbark(self):
returnf"{self.name} says woof!"# String representationdef__str__(self):
returnf"{self.name}, {self.age} years old"def__repr__(self):
returnf"Dog('{self.name}', {self.age})"# InheritanceclassBeagle(Dog):
def__init__(self, name, age, color):
super().__init__(name, age) # call parent constructorself.color=color# Override methoddefbark(self):
return"Arooooo!"# Usagemy_dog=Dog("Rex", 5)
print(my_dog.bark())
print(my_dog) # uses __str__# Property decorator (getter/setter)classPerson:
def__init__(self, first):
self._first=first@propertydeffirst(self):
returnself._first.capitalize()
@first.setterdeffirst(self, value):
self._first=value.strip()# List comprehensionsquares= [x**2forxinrange(10)] # [0,1,4,...,81]evens= [xforxinrange(20) ifx%2==0] # with conditionmatrix= [[jforjinrange(5)] foriinrange(3)] # nested# Set comprehensionunique_lens= {len(word) forwordin ["hi", "hello"]}
# Dict comprehensionsquares_dict= {x: x**2forxinrange(5)}
# Generator expression (memory efficient, parentheses)gen= (x**2forxinrange(1000000))
next(gen) # get next valueforvalingen: ...
# Generator function (yield)deffibonacci(limit):
a, b=0, 1whilea<limit:
yieldaa, b=b, a+bfornuminfibonacci(100):
print(num)# Lambda: anonymous functionsquare=lambdax: x**2# equivalent to def square(x): return x**2# Used with map, filter, sortedlist(map(lambdax: x*2, [1,2,3])) # [2,4,6]list(filter(lambdax: x>2, [1,2,3,4])) # [3,4]sorted([(1,2), (3,1)], key=lambdat: t[1]) # sort by second element# functools.reducefromfunctoolsimportreducereduce(lambdaa,b: a*b, [1,2,3,4]) # 24 (1*2*3*4)# Partial applicationfromfunctoolsimportpartialmultiply=lambdax, y: x*ydouble=partial(multiply, 2) # fixes first argument to 2double(5) # 10# Function decorator (modify/ enhance function)deftimer(func):
importtimedefwrapper(*args, **kwargs):
start=time.time()
result=func(*args, **kwargs)
print(f"Time: {time.time()-start:.4f}s")
returnresultreturnwrapper@timerdefslow_function():
time.sleep(1)
return"Done"# Decorator with argumentsdefrepeat(times):
defdecorator(func):
defwrapper(*args, **kwargs):
for_inrange(times):
result=func(*args, **kwargs)
returnresultreturnwrapperreturndecorator@repeat(3)defgreet(name):
print(f"Hi {name}")fromdatetimeimportdatetime, date, time, timedelta# Currentnow=datetime.now()
today=date.today()
# Createdt=datetime(2024, 3, 15, 14, 30)
# Formatdt.strftime("%Y-%m-%d %H:%M:%S") # '2024-03-15 14:30:00'dt.strftime("%A") # 'Friday'# Parse stringparsed=datetime.strptime("2024-03-15", "%Y-%m-%d")
# Arithmetictomorrow=today+timedelta(days=1)
diff=dt2-dt1# timedelta objectdiff.daysdiff.total_seconds()importrepattern=r"\d+"# raw string for backslashes# Searchmatch=re.search(r"\d+", "Order 42")
ifmatch:
print(match.group()) # '42'# Find allre.findall(r"\d+", "12 apples, 34 oranges") # ['12','34']# Splitre.split(r"\s+", "a b c") # ['a','b','c']# Replacere.sub(r"\d+", "NUM", "Item 42") # 'Item NUM'# Compile for reusephone=re.compile(r"\d{3}-\d{3}-\d{4}")
phone.findall("Call 123-456-7890")
# Common patterns
. # any character (except newline)
\d# digit
\w# word char [a-zA-Z0-9_]
\s# whitespace^# start of string
$ # end of string*+ ? # 0+, 1+, 0 or 1
{3,5} # 3 to 5 repetitions
(a|b) # either a or blen([1,2,3]) # 3type(42) # <class 'int'>int("10") # 10str(10) # "10"list((1,2)) # [1,2]tuple([1,2]) # (1,2)dict([("a",1)]) # {'a':1}set([1,1,2]) # {1,2}sum([1,2,3]) # 6max([1,5,3]) # 5min([1,5,3]) # 1abs(-5) # 5round(3.14159, 2) # 3.14pow(2,3) # 8sorted([3,1,2]) # [1,2,3]reversed([1,2,3]) # iterator [3,2,1]enumerate(["a","b"]) # (0,'a'), (1,'b')zip([1,2], ["a","b"]) # (1,'a'), (2,'b')any([True, False]) # Trueall([True, True]) # Truerange(5) # 0..4map(func, iterable)
filter(func, iterable)
help(print) # documentationdir(list) # attributes/methods# NumPy (arrays, math)importnumpyasnparr=np.array([1,2,3])
arr.mean(), arr.std()
np.linspace(0, 1, 5) # 0, 0.25, 0.5, 0.75, 1# Pandas (data analysis)importpandasaspddf=pd.DataFrame({"col1": [1,2], "col2": [3,4]})
df.head(), df.describe()
df[df.col1>1]
# Matplotlib (plotting)importmatplotlib.pyplotaspltplt.plot([1,2,3], [4,5,6])
plt.show()
# Randomimportrandomrandom.randint(1,10) # integer between 1 and 10random.random() # float 0..1random.choice([1,2,3])
random.sample(range(100), 5) # 5 unique samplesrandom.shuffle(lst)
# OS moduleimportosos.getcwd() # current diros.listdir(".")
os.path.join("folder", "file.txt")
os.path.exists("file.txt")
# Sysimportsyssys.argv# command-line argumentssys.exit(1) # exit with error codePro Tips:
- Use
python -m pdb script.pyfor debugging - Virtual environment:
python -m venv venv - Linting:
pylint, Formatting:black - Speed up loops with local variable caching:
for i in range(n):→ assignrange_local = rangeoutside loop - Use
__slots__in classes to save memory for many instances