Show Menu
Cheatography

Introduction to Python Cheat Sheet (DRAFT) by

Cheat sheet about the basics of python programming

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Looping Statements

For Loop
for item in iterable:
# Code block to be executed for each item
Example
for i in range(5):
print(i)
Output
0
1
2
3
4
While Loop
while condition:
# Code block to be executed as long as condition is True
Example
count = 0
while count < 5:
print(count)
count += 1
Output
0
1
2
3
4
break
Terminates the loop immedi­ately
continue
Skips the rest of the code inside the loop for the current iteration and proceeds to the next iteration
pass
Acts as a placeh­older, does nothing
Nested Loops
for i in range(3):
for j in range(2):
print(i, j)
List Compre­hension
[expre­ssion for item in iterable]
Dictionary Compre­hension
{key_e­xpr­ession: value_­exp­ression for item in iterable}
Generator Expression
(expre­ssion for item in iterable)

Evolution of Python

Birth of Python (1989-­1991)
Created by Guido van Rossum, Python emerged in the late 1980s as a successor to the ABC language. Its name was inspired by Monty Python's Flying Circus, a British sketch comedy series.
Python 1.0 (1994)
Python 1.0 was released with features like lambda, map, filter, and reduce. Its simplicity and readab­ility gained attention in the progra­mming community.
Python 2.x Series (2000-­2008)
Python 2 introduced signif­icant improv­ements and became widely adopted. However, this series faced challenges with compat­ibility issues when Python 3 was released.
Python 3.x Series (2008-­pre­sent)
Python 3 marked a major overhaul of the language, aiming to fix incons­ist­encies and introduce new features while mainta­ining backward compat­ibi­lity. Despite initial resist­ance, it eventually gained widespread accept­ance.
Python Enhanc­ement Proposals (PEPs)
PEPs serve as the formal mechanisms for proposing major changes to Python. They facilitate community discussion and decisi­on-­making processes, ensuring Python's evolution reflects the needs of its users.
Community and Ecosystem Growth
Python's open-s­ource nature has fostered a vibrant community, contri­buting to a vast ecosystem of libraries, framew­orks, and tools. This growth has propelled Python to become one of the most popular and versatile progra­mming languages worldwide.
Recent Develo­pments
Continual updates and enhanc­ements keep Python relevant and compet­itive in the ever-c­hanging landscape of progra­mming languages. Recent develo­pments include optimi­zations for perfor­mance, improv­ements in concur­rency, and enhanc­ements in data science and machine learning capabi­lities.
Future Directions
Python continues to evolve, with ongoing efforts to enhance perfor­mance, mainta­ina­bility, and ease of use. The commun­ity­-driven develo­pment model ensures that Python remains adaptable to emerging techno­logies and evolving progra­mming paradigms.

Rules for Identi­fiers

Must start with a letter (a-z, A-Z) or underscore (_).
Can be followed by letters, digits (0-9), or unders­cores.
Python identi­fiers are case-s­ens­itive.
Cannot be a reserved word or keyword.

Identity Operators

Is: is
Is not: is not

Membership Operators

In: in
Not in: not in

Data Types

Integer (int)
Represents whole numbers.
Float (float)
Represents floati­ng-­point numbers (decimal numbers).
String (str)
Represents sequences of characters enclosed in quotes (' or ").
Boolean (bool)
Represents truth values True or False.
List
Ordered collection of items, mutable.
Tuple
Ordered collection of items, immutable.
Dictionary (dict)
Collection of key-value pairs, unordered.
Set
Collection of unique items, unordered.

Data Types

Integer (int)
Represents whole numbers.
Float (float)
Represents floati­ng-­point numbers (decimal numbers).
String (str)
Represents sequences of characters enclosed in quotes (' or ").
Boolean (bool)
Represents truth values True or False.
List
Ordered collection of items, mutable.
Tuple
Ordered collection of items, immutable.
Dictionary (dict)
Collection of key-value pairs, unordered.
Set
Collection of unique items, unordered.

Features of Python

Simple and Readable Syntax
Python's syntax is designed to be simple and readable, making it easy for beginners to learn and unders­tand. Its clean and concise syntax reduces the cost of program mainte­nance.
Interp­reted Language
Python is an interp­reted language, meaning that it does not need to be compiled before execution. This allows for rapid develo­pment and testing of code.
High-Level Language
Python abstracts low-level details like memory management and provides constructs like objects, functions, and modules, allowing developers to focus on solving problems rather than dealing with system­-level concerns.
Dynamic Typing
Python is dynami­cally typed, meaning you don't need to declare the data type of variables explic­itly. This makes Python code shorter and more flexible.
Object­-Or­iented
Python supports object­-or­iented progra­mming (OOP) paradigms, allowing developers to create reusable and modular code by defining classes and objects.
Extensive Standard Library
Python comes with a vast standard library that provides modules and functions for a wide range of tasks, from file I/O to networking to web develo­pment. This reduces the need for third-­party libraries for many common tasks.
Cross-­Pla­tform Compat­ibility
Python code can run on various platforms such as Windows, macOS, and Linux without modifi­cation, making it highly portable.
Dynamic Memory Allocation
Python uses dynamic memory allocation and garbage collec­tion, automa­tically managing memory usage and freeing up memory when objects are no longer needed.
Strong Community Support
Python has a large and active community of developers who contribute to its growth by creating libraries, framew­orks, and tools. This vibrant community ensures that there are resources and support available for developers at all levels.
Integr­ation Capabi­lities
Python can easily integrate with other languages like C/C++, allowing developers to leverage existing code and libraries written in other languages.
Ease of Learning and Deployment
Python's simplicity and readab­ility make it an excellent choice for beginners, and its extensive docume­ntation and community support make it easy to learn and deploy for both small-­scale and large-­scale projects.
Scalab­ility
While initially known for its simplicity and ease of use, Python is also scalable and can handle large-­scale projects effect­ively. With frameworks like Django and Flask for web develo­pment, and libraries like NumPy and Pandas for data science, Python is suitable for a wide range of applic­ations, from small scripts to enterp­ris­e-level systems.

Comparison Operators

Equal to: ==
Not equal to: !=
Greater than: >
Less than: <
Greater than or equal to: >=
Less than or equal to: <=

Logical Operators

Logical AND: and
Logical OR: or
Logical NOT: not

Functions

Defining a Function
def function_name(parameters):
"""docstring"""
# code block
return value
Calling a Function
result = functi­on_­nam­e(a­rgu­ments)
Positional Parameters
def greet(name):
print(­"­Hel­lo,­", name)
greet(­"­Ali­ce") # Output: Hello, Alice
Keyword Parameters
def greet(­name, greeting):
print(­gre­eting, name)
greet(­nam­e="B­ob", greeting="Hi")
# Output: Hi Bob
Default Parameters
def greet(­name, greeting="Hello"):
print(­gre­eting, name)
greet("Alice")
# Output: Hello Alice
*args (Non-k­eyword Arguments)
def add(*args):
return sum(args)
add(1, 2, 3) # Output: 6
**kwargs (Keyword Arguments)
def details(**kwargs):
print(kwargs)
detail­s(n­ame­="Al­ice­", age=30)
# Output: {'name': 'Alice', 'age': 30}
Docstrings
def function_name(parameters):
"­"­"­Des­cri­ption of the function"""
# code block
return value
print(­fun­cti­on_­nam­e._­_doc__)
Return Statement
def add(a, b):
return a + b
result = add(3, 5) # Output: 8
Local Scope
Variables defined inside a function have local scope.
Global Scope
Variables defined outside functions have global scope.
Lambda Functions
double = lambda x: x * 2
print(­dou­ble(5)) # Output: 10
Recursive Functions
def factorial(n):
if n == 0:
return 1
else:
return n * factorial(n-1)
print(­fac­tor­ial(5)) # Output: 120

Exception Handling

What is an Exception?
An exception is an error that occurs during the execution of a program. It disrupts the normal flow of the program's instru­ctions.
try-except block
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
try-ex­cep­t-else block
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
else:
# Code to execute if no exception occurs
try-ex­cep­t-f­inally block
try:
# Code that may raise an exception
except ExceptionType:
# Code to handle the exception
finally:
# Code that will execute no matter what
Built-in Exceptions
Examples include TypeError, ValueE­rror, ZeroDi­vis­ion­Error, etc.
Raising Exceptions
raise Except­ion­Typ­e("Error messag­e")
Custom Exceptions
class CustomError(Exception):
def __init­__(­self, message):
self.m­essage = message
Handling Multiple Exceptions
try:
# Code
except (Excep­tio­nType1, Except­ion­Type2) as e:
# Handle both exceptions

File Handling

Opening a File
file = open("f­ile­nam­e.t­xt", "­r")
Closing a File
file.c­lose()
Reading from a File
content = file.r­ead()
Writing to a File
file.w­rit­e("H­ello, world!­")
Appending to a File
file = open("f­ile­nam­e.t­xt", "­a") 
file.write("New conten­t")
Iterating Over Lines
for line in file:
print(­line)
Checking File Existence
import os.path
if os.path.exists("filename.txt"):
print(­"File exists­")
File Handling with Context Managers
with open("f­ile­nam­e.t­xt", "­r") as file:
content = file.read()
# file automa­tically closed after exiting the 'with' block
 

Arithmetic Operators

Addition: +
Subtra­ction: -
Multip­lic­ation: *
Division: /
Modulus: %
Expone­nti­ation: **

Common Functions

print()
Output text or variables to the console.
input()
Receive user input from the console.
len()
Calculate the length of a sequence (e.g., string, list, tuple).
range()
Generate a sequence of numbers within a specified range.
type()
Determine the type of a variable or value.
int()
Convert a value to an integer.
float()
Convert a value to a floati­ng-­point number.
str()
Convert a value to a string.
list()
Convert a sequence (e.g., string, tuple) to a list.
tuple()
Convert a sequence (e.g., string, list) to a tuple.
dict()
Create a dictionary or convert a sequence of key-value pairs into a dictio­nary.
sorted()
Return a new sorted list from the elements of an iterable.
max()
Return the largest item in an iterable or the largest of two or more arguments.
min()
Return the smallest item in an iterable or the smallest of two or more arguments.
sum()
Return the sum of all elements in an iterable.
abs()
Return the absolute value of a number.
round()
Round a floati­ng-­point number to a specified precision.
zip()
Combine multiple iterables into tuples.
enumer­ate()
Return an enumerate object, which yields pairs of index and value.
map()
Apply a function to every item in an iterable.
filter()
Construct an iterator from those elements of an iterable for which a function returns true.
reduce()
Apply a rolling comput­ation to sequential pairs of values in an iterable.
any()
Return True if any element of the iterable is true.
all()
Return True if all elements of the iterable are true.
dir()
Return a list of valid attributes for the specified object.
help()
Access Python's built-in help system.

Condit­ional Statements

If Statement
if condition:
# Code to execute if condition is True
If-else Statement
if condition:
# Code to execute if condition is True
else:
# Code to execute if condition is False
If-eli­f-else Statement
if condition1:
# Code to execute if condition1 is True
elif condition2:
# Code to execute if condition2 is True
else:
# Code to execute if all conditions are False
Nested If Statements
if condition1:
if condition2:
# Code to execute if both condition1 and condition2 are True
Ternary Condit­ional Operator
result = true_value if condition else false_­value
Short Circuit Evaluation
# Example using 'and'
if x > 0 and y < 10:
# Code here

# Example using 'or'
if a == 0 or b == 0:
# Code here
Membership Test
if item in list:
# Code to execute if item is present in list
Identity Test
if x is y:
# Code to execute if x and y refer to the same object

Bitwise Operators

Bitwise AND: &
Bitwise OR: |
Bitwise XOR: ^
Bitwise NOT: ~
Left shift: <<
Right shift: >>

Assignment Operators

Assign value: =
Add and assign: +=
Subtract and assign: -=
Multiply and assign: *=
Divide and assign: /=
Modulus and assign: %=
Expone­nti­ation and assign: **=

Variables

Variable
Variables are used to store data values.
Variable Declar­ation
No explicit declar­ation needed. Just assign a value to a name.
Variable Naming
Follow naming conven­tions. Use descri­ptive names, avoid reserved words, and start with a letter or unders­core.
Data Types
Variables can hold various data types such as integers, floats, strings, lists, tuples, dictio­naries, etc.
Dynamic Typing
Python is dynami­cally typed, meaning you can reassign variables to different data types.
Example
# Variable assignment 
x = 10
name = "­Ali­ce"
is_student = True
Variable Reassi­gnment:
x = 10 print(x)  # Output: 10 
x = "­Hel­lo"
print(x) # Output: Hello
Multiple Assignment
a, b, c = 1, 2, 3
Constants
PI = 3.14159

Best Practices for Identi­fiers

Use descri­ptive names for better code readab­ility.
Avoid using single letters or abbrev­iations that may be ambiguous.
Follow naming conven­tions (e.g., snake_case for variables and functions, PascalCase for class names).

Tokens

Identi­fiers
These are names given to entities like variables, functions, classes, etc. They must start with a letter or underscore and can be followed by letters, digits, or unders­cores.
Keywords
Python has reserved words that have special meanings and cannot be used as identi­fiers. Examples include if, else, for, while, def, class, etc.
Literals
These are the raw data values used in a program. Common types of literals in Python include integers, floati­ng-­point numbers, strings, and boolean values.
Operators
Operators are symbols used to perform operations on operands. Python supports various types of operators such as arithmetic operators (+, -, *, /), assignment operators (=, +=, -=), comparison operators (==, !=, <, >), logical operators (and, or, not), etc.
Delimiters
Delimiters are characters used to define the structure of a program. Examples include parent­heses (), braces {}, square brackets [], commas ,, colons :, etc.
Comments
Comments are used to annotate code and are ignored by the Python interp­reter. They start with the # symbol for single­-line comments or are enclosed within triple quotes "­"­" for multi-line comments.

Applic­ations of Python

Web Develo­pment
Python's frameworks like Django and Flask are widely used for building web applic­ations due to their simplicity and scalab­ility.
Data Science
Python's libraries like NumPy, Pandas, and Matplotlib make it a preferred choice for data analysis, visual­iza­tion, and machine learning tasks.
Artificial Intell­igence and Machine Learning
Python provides extensive libraries such as Tensor­Flow, Keras, and PyTorch, making it popular for AI and ML projects.
Automation and Scripting
Python's ease of use and readab­ility make it ideal for automating repetitive tasks and scripting.
Game Develo­pment
Python's simplicity and versat­ility are leveraged in game develo­pment frameworks like Pygame.
Desktop GUI Applic­ations
Libraries such as Tkinter and PyQt allow developers to create cross-­pla­tform desktop GUI applic­ations easily.
Scientific Computing
Python is widely used in scientific computing for simula­tions, mathem­atical modeling, and data analysis in fields such as physics, engine­ering, and biology.
Finance and Trading
Python is extens­ively used in finance for tasks like algori­thmic trading, risk manage­ment, and quanti­tative analysis due to its robust libraries and ease of integr­ation.
Education
Python's readab­ility and simplicity make it an excellent choice for teaching progra­mming to beginners, as well as for educat­ional software develo­pment.
Networking
Python's libraries like socket and Twisted are used for network progra­mming, making it a popular choice for developing networ­k-r­elated applic­ations.

Paradigms of Python

Imperative Progra­mming
Focuses on describing how a program operates through a sequence of statem­ents. Python's imperative style involves defining functions, loops, and condit­ional statements to control program flow.
Object­-Or­iented Progra­mming (OOP)
Emphasizes the creation of objects which encaps­ulate data and behavior. Python supports classes, inheri­tance, polymo­rphism, and encaps­ula­tion, enabling developers to structure their code in a modular and reusable manner.
Functional Progra­mming
Treats comput­ation as the evaluation of mathem­atical functions. Python supports functional progra­mming concepts such as higher­-order functions, lambda expres­sions, and immutable data struct­ures. Functional progra­mming encourages writing pure functions without side effects, enhancing code readab­ility and testab­ility.
Procedural Progra­mming
Involves organizing code into procedures or functions to perform tasks. Python supports procedural progra­mming by allowing the creation of functions and modules to break down tasks into smaller, manageable units.
Aspect­-Or­iented Progra­mming (AOP)
Focuses on separating cross-­cutting concerns such as logging, authen­tic­ation, and error handling from the main program logic. While Python doesn't provide built-in AOP support, libraries like AspectLib and Pythoscope offer AOP capabi­lities through decorators and metapr­ogr­amming.

Modules

What are Modules?
Modules in Python are files containing Python code.
They can define functions, classes, and variables.
Python code in one module can be reused in another module.
Why Use Modules?
Encaps­ula­tion: Keep related code together for better organi­zation.
Reusability: Write code once and reuse it in multiple places.
Namespacing: Avoid naming conflicts by using module namesp­aces.
Importing Modules
Use the import keyword to import a module.
import module­_name
Use from keyword to import specific items from a module.
from module­_name import item1, item2
Standard Library Modules
Python comes with a rich standard library of modules for various tasks.
Examples: math, os, datetime, random, json, csv, etc.
Third-­Party Modules
Extensive collection of third-­party modules available via the Python Package Index (PyPI).
Install third-­party modules using pip, the Python package manager.
pip install module­_name
Creating Modules
To create your own module, simply save Python code in a .py file.
Functions, classes, and variables defined in the file become accessible when the module is imported.
Special Attributes
__name__: Name of the module. When a module is run as a script, its __name__ is set to "__main__".
__file__: Path to the module's source file.
Best Practices
Use meaningful names for modules.
Document your modules using docstrings.
Avoid polluting the global namespace by importing only what you need.
Follow PEP 8 guidelines for code style.
Importing standard library module:
import math
print(math.pi)
Importing specific items
from math import pi, sqrt 
print(pi)

Object Oriented Progra­mming

Object­-Or­iented Progra­mming (OOP) in Python
Object­-Or­iented Progra­mming (OOP) is a progra­mming paradigm that revolves around the concept of objects, which can contain data (attri­butes) and code (methods). Python supports OOP princi­ples, making it versatile and powerful for building complex systems.
Class
A class is a blueprint for creating objects.
Object
An object is an instance of a class, repres­enting a specific entity in your program.
Encaps­ulation
Encaps­ulation refers to bundling data (attri­butes) and methods that operate on the data within a single unit, i.e., a class.
It helps in data hiding and abstra­ction, enabling better control over data access and modifi­cation.
Inheri­tance
Inheri­tance allows a class (subcl­ass­/child class) to inherit attributes and methods from another class (super­cla­ss/­parent class).
It promotes code reuse and facili­tates building hierar­chical relati­onships between classes.
Polymo­rphism
Polymo­rphism enables a single interface to be used for different data types or objects.
It allows methods to behave differ­ently based on the object they are called on, promoting flexib­ility and extens­ibi­lity.
Modularity
OOP promotes modular design, making code more organized and easier to maintain.
Reusab­ility
Through inheri­tance and polymo­rphism, code reuse is facili­tated, reducing redund­ancy.
Scalab­ility
OOP supports building large-­scale applic­ations by struct­uring code into manageable units.
Abstra­ction
OOP allows developers to focus on high-level functi­onality without worrying about implem­ent­ation details.