Show Menu
Cheatography

Python Beginner to Advanced Cheat Sheet by

A detailed Python cheat sheet covering beginner to advanced topics. Python is a popular programming language that can be used on a server to create web applications and this cheat sheet will cover all essential concepts.

Basic Syntax

Comments

Single line: Use
#
symbol
Multi-­line: Use triple quotes
"­"­" or ''' 

Inline comments: Add
#
at end of line

Print Function

Basic output:
print()
function displays text
Multiple values: Separate with commas
String format­ting: Use
f-strings, format(), or %
format­ting.

Indent­ation

Critical in Python - Defines code blocks
Use 4 spaces - Standard convention
Consistent indent­ation - All lines in same block must have same indent­ation

Data Types

int
Whole numbers
float
Decimal Numbers
complex
Real + imaginary
str
Character strings
Immutable
Can't change chars
Unicode
Intern­ational support
bool
True/False Values
list
Ordered, mutable
tuple
Ordered, immutable
dict
Key-value pairs
set
Unique elements only
Data types include numeric, text, boolean, and collec­tions.

Naming Rules

Start
Letter or underscore
Characters
alphan­umeric + underscore
No reserved words
if, for, class
Convention
snake_case

Variable Declar­ation

No keyword needed
Just assign
Dynamic typing
Auto-d­ete­rmined
Case sensitive
myvar ≠ MyVar
Multiple assignment
One line

Formatting

f-strings
f"Hello {name}­"
format()
"­Hello {}".f­or­mat­(name)
% style
"­Hello %s" % name

String Methods

Case
upper(), lower(), title()
Search
find(), index(), count()
Check
starts­with(), endswith()
Modify
replace(), strip(), split()

String Operations

Concat­enation
+ operator
Repetition
* operator
Length
`en() function
Indexing
[0] zero-based
Slicing
[start­:en­d:step]

Strings (Creation Methods)

Single quotes
'Hello'
Double quotes
"­Hel­lo"
Triple quotes
Multi Line
Raw strings
r 'literal'

Condit­ionals

if
Basic condition check
elif
Additional conditions
else
Default
Operators
==, !=, <, >
Logic
and, or, not

Loops

For
Iterate sequences
While
Condit­ion­-based
range()
Number Sequence
enumer­ate()
Index + Value
zip()
Multiple sequence

Loop Control

break
Exit loop
continue
Skip iteration
else
Normal completion
pass
Empty placeh­older

Functions

Definition

• def keyword: Define function
• Parame­ters: Input values
• Return: Output value
• Docstr­ings: Docume­ntation

Arguments

• Positi­onal: Order matters
• Keyword: Use parameter names
• Default: Provide default values
• Variable: args, *kwargs

Types

• Built-in: print(), len(), type()
• User-d­efined: Custom functions
• Lambda: Anonymous functions
• Generator: Uses yield

Scope

• Local: Inside function
• Global: Outside functions
• global: Modify global vars
• nonlocal: Enclosing scope

Built-in Functions

Essential

• print(): Output to console
• input(): Get user input
• len(): Sequence length
• type(): Object type
• isinst­ance(): Check type

Conversion

• int(), float(), str()
• list(), tuple(), set()
• ord(), chr(): Char conversion

Mathem­atical

• abs(): Absolute value
• round(): Round numbers
• min(), max(): Extremes
• sum(): Sequence sum
• pow(): Power calcul­ation

Sequence

• range(): Number sequences
• enumer­ate(): Add indices
• zip(): Combine iterables
• sorted(): Sort sequence
• all(), any(): Boolean ops

File Handling

Operations

• open(): Open file for I/O
• Modes: 'r', 'w', 'a', 'x'
• Text/B­inary: 't', 'b' modes
• close(): Close file

Reading

• read(): Entire file
• readli­ne(): Single line
• readli­nes(): All lines
• Iteration: Loop through lines

Writing

write(): Write string
writel­ines(): Write list
Context manager: with statement

</d­iv>

<div style=­"­flex: 1;">

Error Handling

try
Code that may fail
except
Handle exceptions
else
No exception occured
finally
Always excute
rise
Trigger exception
Handling

Error Handling

Syntax­Error
Invalid syntax
NameError
Undefined variable
TypeError
Wrong data type
ValueError
Wrong Value
IndexError
List index error
KeyError
Dict key missing
Exception Types

Object­-Or­iented Progra­mming

Classes and Objects

• class keyword – Define class
• Object instan­tiation – Create instances
• Instance variables – Data unique to each object
• Class variables – Data shared by all instances
• self parameter – Reference to current instance

Methods

• Instance methods – Access instance data
• Class methods – Work with class data (@clas­sme­thod)
• Static methods – Indepe­ndent functions (@stat­icm­ethod)
• Special methods – init, str, repr, etc.

Inheri­tance

• Parent class – Base class being inherited
• Child class – A class that inherits
• super() function – Access parent class methods
• Method overriding – Redefine parent methods
• Multiple inheri­tance – Inherit from multiple classes

Encaps­ulation

• Private attributes – Prefix with unders­core(s)
• Property decorator – Create getter­/setter methods
• Name mangling – Double underscore prefix
• Public interface – Methods meant for external use

Polymo­rphism

• Same interface, different implem­ent­ations
• Duck typing – "If it looks like a duck..."
• Method overlo­ading – Not directly supported
• Operator overlo­ading – Define behavior for operators

Data Structures

Lists

• Ordered, mutable, duplicates OK
• Methods:
append(), insert(), remove()

• Access: indexing [0], slicing [1:3]
• Sort:
sort(), reverse()


Tuples

• Ordered, immutable, duplicates OK
• Methods:
count(), index()

• Packin­g/U­npa­cking: Multiple assignment
• Faster than lists

Dictio­naries

• Key-value pairs, mutable
• Methods:
get(), keys(), values()

• Access: dict[key] or dict.g­et(key)
• Update: update(), pop()

Sets

• Unordered, unique elements
• Methods:
add(), remove(), union()

• Operat­ions: inters­ection, difference
• Member­ship: fast in testing

Industry Applic­ations

Web Develo­pment

• Backend APIs – RESTful services, GraphQL
• Full-stack frameworks – Django, FastAPI
• Micros­ervices – Flask, FastAPI
• Content management – Django CMS, Wagtail

Data Science & Analytics

• Data analysis – Pandas, NumPy
• Machine learning – Scikit­-learn, Tensor­Flow, PyTorch
• Data visual­isation – Matplo­tlib, Seaborn, Plotly
• Big data – PySpark, Dask

Automation & Scripting

• System admini­str­ation – Automate server tasks
• Web scraping – Beauti­ful­Soup, Scrapy
• Task automation – Schedule, monitor processes
• DevOps tools – Ansible, Fabric

Scientific Computing

• Research computing - SciPy ecosystem
• Bioinf­orm­atics – BioPython
• Astronomy – AstroPy
• Physics simula­tions – NumPy, SciPy

Game Develo­pment

• Pygame – 2D game develo­pment
• Panda3D – 3D game engine
• Game scripting – Embed Python in games
• Game tools – Level editors, asset pipelines

Learning Resources

Official Docume­ntation

• python.org – Official Python docume­ntation
• PEP documents – Python Enhanc­ement Proposals
• Library reference – Standard library docume­ntation
• Language reference – Complete language specif­ication

Online Tutorials

• W3Schools
• Python.org tutorial
• Real Python
• Codecademy

Practice Platforms

• LeetCode – Coding interview prepar­ation
• HackerRank – Progra­mming challenges
• Codewars – Coding kata and challenges
• Project Euler – Mathem­atical progra­mming problems
                   
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Python Cheat Sheet
            Python 3 Cheat Sheet by Finxter

          More Cheat Sheets by musmankkh

          Git/Github Cheat Sheet