0% found this document useful (0 votes)
166 views26 pages

Python Cheat Sheet

The document provides a comprehensive cheat sheet covering key concepts in Python including variables, data types, operators, conditional statements, loops, functions, lists, dictionaries, strings, tuples, sets, classes, inheritance, polymorphism and more.

Uploaded by

2007190100078
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
166 views26 pages

Python Cheat Sheet

The document provides a comprehensive cheat sheet covering key concepts in Python including variables, data types, operators, conditional statements, loops, functions, lists, dictionaries, strings, tuples, sets, classes, inheritance, polymorphism and more.

Uploaded by

2007190100078
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

PYTHON

CHEAT SHEET
[Link]
Variables and data types

# Variable declaration
variable_name = value

# Basic data types


integer = 5
float_number = 5.5
string = "Hello world!"
boolean = True
none = None

[Link]
Operators

# Arithmetic operators
addition = 5 + 2
subtraction = 5 - 2

multiplication = 5 * 2
division = 5 / 2
floor_division = 5 // 2

exponentiation = 5 ** 2
modulus = 5 % 2

# Logical operators
and_operator = True and False
or_operator = True or False
not_operator = not True

[Link]
Operators

# Comparison operators
greater_than = 5 > 2
less_than = 5 < 2

equal_to = 5 == 2
not_equal_to = 5 != 2

greater_than_or_equal_to = 5 >= 2
less_than_or_equal_to = 5 <= 2

[Link]
Conditional statements

# if statement
if condition:
# code block

# if-else statement
if condition:
# code block
else:
# code block

# if-elif-else statement
if condition:
# code block
elif condition:
# code block
else:
# code block

[Link]
Loops

# for loop
for variable in sequence:
# code block

# while loop
while condition:
# code block

[Link]
Functions

# Function declaration
def function_name(parameter1, parameter2):
# code block
return result

# Function call
function_name(argument1, argument2)

[Link]
Lists
# List declaration
list_name = [item1, item2, item3]

# Accessing list items


first_item = list_name[0]
last_item = list_name[-1]

# Modifying list items


list_name[0] = new_item

# Adding items to a list


list_name.append(new_item)
list_name.insert(index, new_item)

# Removing items from a list


list_name.remove(item)
list_name.pop(index)

# List slicing
sliced_list =
list_name[start_index:end_index:step]

[Link]
Dictionaries

# Dictionary declaration
dictionary_name = {"k1": v1, "k2": v2}

# Accessing dictionary values


value1 = dictionary_name["k1"]

# Modifying dictionary values


dictionary_name["k1"] = new_value

# Adding items to a dictionary


dictionary_name["new_key"] = new_value

# Removing items from a dictionary


del dictionary_name["key"]

# Getting keys and values from a


dictionary
keys = dictionary_name.keys()
values = dictionary_name.values()

[Link]
Strings

# String declaration
string_name = "Hello world!"

# String concatenation
concatenated_string = "Hello" + "world!"

# String interpolation
name = "John"
greeting = f"Hello, {name}!"

# String methods
string_length = len(string_name)
uppercase_string = string_name.upper()
lowercase_string = string_name.lower()

[Link]
Tuples

# Tuple declaration
tuple_name = (item1, item2, item3)

# Accessing tuple items


first_item = tuple_name[0]
last_item = tuple_name[-1]

# Tuple slicing
sliced_tuple =
tuple_name[start_index:end_index:step]

[Link]
Sets

# Set declaration
set_name = {item1, item2, item3}

# Adding items to a set


set_name.add(new_item)

# Removing items from a set


set_name.remove(item)

# Set operations
union_set = [Link](set2)
intersection_set = [Link](set2)
difference_set = [Link](set2)

[Link]
List Comprehensions

# Creating a new list from an existing


list
new_list = [expression for item in
existing_list]

# Conditionally creating a new list from


an existing list
new_list = [expression for item in
existing_list if condition]

[Link]
Error Handling
# try-except block
try:
# code block
except ErrorType:
# code block

# try-except-else block
try:
# code block
except ErrorType:
# code block
else:
# code block

# try-except-finally block
try:
# code block
except ErrorType:
# code block
finally:
# code block

[Link]
Modules and Packages
# Importing a module
import module_name

# Importing a specific function from a


module
from module_name import function_name

# Importing all functions from a module


from module_name import *

# Importing a package
import package_name

# Importing a specific module from a


package
from package_name import module_name

# Importing a specific function from a


module in a package
from package_name.module_name import
function_name

[Link]
Classes and Objects
# Class declaration
class ClassName:
def __init__(self, parameter1,
parameter2):
self.parameter1 = parameter1
self.parameter2 = parameter2

def method_name(self):
# code block

# Object creation
object_name = ClassName(argument1,
argument2)

# Accessing object properties


property_value = object_name.property_name

# Calling object methods


object_name.method_name()

[Link]
Inheritance
# Parent class
class ParentClass:
def parent_method(self):
# code block

# Child class
class ChildClass(ParentClass):
def child_method(self):
# code block

# Object creation
object_name = ChildClass()

# Accessing inherited methods


object_name.parent_method()

[Link]
Polymorphism

# Parent class
class ParentClass:
def polymorphic_method(self):
# code block

# Child class 1
class ChildClass1(ParentClass):
def polymorphic_method(self):
# code block

# Child class 2
class ChildClass2(ParentClass):
def polymorphic_method(self):
# code block

# Object creation
object1 = ChildClass1()
object2 = ChildClass2()

# Polymorphic method calls


object1.polymorphic_method()
object2.polymorphic_method()

[Link]
Lambda Functions

# Lambda function declaration


lambda_function = lambda p1,p2: expression

# Lambda function call


result = lambda_function(a1, a2)

[Link]
Map, Filter, and Reduce

# Map function
new_list = map(function, iterable)

# Filter function
new_list = filter(function, iterable)

# Reduce function
from functools import reduce
result = reduce(function, iterable)

[Link]
Decorators

# Decorator function
def decorator_function(original_function):
def wrapper_function(*args, **kwargs):
# code before original function
result = original_function(*args, **kwargs)
# code after original function
return result
return wrapper_function

# Applying a decorator to a function


@decorator_function
def original_function(*args, **kwargs):
# code block

[Link]
Generators

# Generator function
def generator_function():
for i in range(10):
yield i

# Using a generator
for value in generator_function():
# code block

[Link]
File Handling

# Opening a file
file = open("filename", "mode")

# Reading from a file


file_contents = [Link]()

# Writing to a file
[Link]("text")

# Closing a file
[Link]()

[Link]
Virtual Environments

# Creating a virtual environment


python -m venv virtual_environment_name

# Activating a virtual environment


source virtual_environment_name/bin/activate

# Installing packages in a virtual environment


pip install package_name

# Deactivating a virtual environment


deactivate

[Link]
Context Managers

# Context manager class


class ContextManagerClass:
def __enter__(self):
# code block
return value

def __exit__(self, exc_type, exc_value,


traceback):
# code block

# Using a context manager with 'with' statement


with ContextManagerClass() as value:
# code block

[Link]
Threading and Multiprocessing

import threading
import multiprocessing

# Threading
thread = [Link](target=function_name,
args=(argument1, argument2))
[Link]()

# Multiprocessing
process =
[Link](target=function_name,
args=(argument1, argument2))
[Link]()

[Link]

You might also like