Python Cheat Sheet pdf

Python is a popular, high-level, general-purpose programming language used in a variety of fields, including web development, scientific computing, data analysis, artificial intelligence, and more.

It has a simple and intuitive syntax that allows for quick and easy development of programs.

Python also comes with a wide range of built-in functions and libraries that can be used to perform various tasks, from manipulating data to creating graphical user interfaces.

This cheat sheet provides a quick reference guide to some of the most commonly used Python functions and libraries, along with explanations and examples, to help you quickly and efficiently write Python programs.

Here’s a cheat sheet with some commonly used Python commands along with examples and explanations:

Python Cheat Sheet pdf

  1. Variables and Data Types
  • To declare a variable, simply assign a value to it using the ‘=’ symbol:
x = 5
  • Python has several built-in data types, including integers, floating-point numbers, strings, booleans, and lists:
a = 10  # integer
b = 3.14  # floating-point number
c = "hello"  # string
d = True  # boolean
e = [1, 2, 3]  # list
  1. Arithmetic Operators
  • Python supports standard arithmetic operators such as +, -, *, /, and %:
x = 5
y = 3
z = x + y  # z is now 8
  • Python also supports the ** operator for exponentiation:
x = 2
y = 3
z = x ** y  # z is now 8
  1. Strings
  • Strings can be declared using single or double quotes:
a = 'hello'
b = "world"
  • Strings can be concatenated using the + operator:
a = 'hello'
b = 'world'
c = a + ' ' + b  # c is now 'hello world'
  • Strings can be indexed and sliced using square brackets:
a = 'hello world'
b = a[0]  # b is 'h'
c = a[6:]  # c is 'world'
  1. Lists
  • Lists can be declared using square brackets:
a = [1, 2, 3]
  • Lists can be indexed and sliced just like strings:
a = [1, 2, 3, 4, 5]
b = a[0]  # b is 1
c = a[2:4]  # c is [3, 4]
  • Lists can be modified using various methods, such as append(), pop(), and remove():
a = [1, 2, 3]
a.append(4)  # a is now [1, 2, 3, 4]
b = a.pop()  # b is 4, a is now [1, 2, 3]
a.remove(2)  # a is now [1, 3]
  1. Conditional Statements
  • Python supports if/elif/else statements for conditional logic:
x = 5
if x > 0:
    print("x is positive")
elif x < 0:
    print("x is negative")
else:
    print("x is zero")
  1. Loops
  • Python supports for and while loops:
# for loop over a list
a = [1, 2, 3]
for x in a:
    print(x)

# while loop
x = 0
while x < 10:
    print(x)
    x += 1
  1. Functions
  • Python allows you to define your own functions using the def keyword:
def square(x):
    return x ** 2

y = square(5)  # y is 25
  1. Modules
  • Python has a large number of built-in modules that can be imported and used in your code:
import math

x = math.sqrt(16)  # x is 4

9. Dictionary

  • A dictionary is a collection of key-value pairs, declared using curly braces:
person = {'name': 'John', 'age': 30, 'location': 'New York'}
  • You can access the value associated with a key using square brackets:
name = person['name']  # name is 'John'
  • You can add or update a key-value pair using the same square brackets:
person['job'] = 'programmer'  # person is now {'name': 'John', 'age': 30, 'location': 'New York', 'job': 'programmer'}

10. Tuples

  • A tuple is an ordered collection of values, declared using parentheses:
point = (3, 4)
  • You can access individual elements using square brackets, just like with lists:
x = point[0]  # x is 3
  • Tuples are immutable, meaning you can’t change their values once they’re created.

11. Sets

  • A set is an unordered collection of unique values, declared using curly braces:
numbers = {1, 2, 3, 4, 5}
  • You can add or remove elements using the add() and remove() methods:
numbers.add(6)
numbers.remove(3)

12. File I/O

  • You can open and read files in Python using the open() function:
file = open('filename.txt', 'r')
content = file.read()
file.close()
  • You can write to files using the write() method:
file = open('filename.txt', 'w')
file.write('Hello, world!')
file.close()

13. List Comprehensions

  • List comprehensions provide a concise way to create lists based on existing lists:
numbers = [1, 2, 3, 4, 5]
squares = [x ** 2 for x in numbers]  # squares is [1, 4, 9, 16, 25]

15. Map, Filter, and Reduce

  • The map() function applies a function to each element of a list:
numbers = [1, 2, 3, 4, 5]
squares = map(lambda x: x ** 2, numbers)  # squares is [1, 4, 9, 16, 25]
  • The filter() function returns a new list containing only the elements that satisfy a given condition:
numbers = [1, 2, 3, 4, 5]
evens = filter(lambda x: x % 2 == 0, numbers)  # evens is [2, 4]
  • The reduce() function applies a function to pairs of elements in a list until only one element remains:
from functools import reduce

numbers = [1, 2, 3, 4, 5]
product = reduce(lambda x, y: x * y, numbers)  # product is 120

16. Classes and Objects

  • Python supports object-oriented programming using classes and objects:
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
  • You can create an instance of a class by calling its constructor:
person = Person('John', 30)
  • You can access an object’s attributes using dot notation:
name = person.name  # name is 'John'
  • You can define methods on a class:
class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age
    
    def say_hello(self):
        print('Hello, my name is', self.name)

person = Person('John', 30)
person.say_hello()  # prints 'Hello, my name is John'

17. Inheritance

  • Python supports inheritance, allowing you to create subclasses that inherit attributes and methods from a parent class:
class Student(Person):
    def __init__(self, name, age, major):
        super().__init__(name, age)
        self.major = major
    
    def say_hello(self):
        super().say_hello()
        print('I am a', self.major, 'major')

student = Student('Jane', 20, 'Computer Science')
student.say_hello()  # prints 'Hello, my name is Jane' and 'I am a Computer Science major'

18. Modules

  • You can import modules in Python using the import statement:
import math

result = math.sqrt(25)  # result is 5.0
  • You can also import specific functions or classes from a module:
from math import sqrt

result = sqrt(25)  # result is 5.0
  • You can create your own modules by defining functions and classes in a separate file and importing them into your main script.

19. Virtual Environments

  • A virtual environment is a self-contained Python environment that allows you to install packages and dependencies without affecting the global Python installation on your machine.
  • You can create a new virtual environment using the venv module:
python -m venv myenv
  • You can activate the virtual environment by running the activate script:
source myenv/bin/activate  # on Unix/Mac
myenv\Scripts\activate.bat  # on Windows
  • You can install packages using pip, which is automatically installed with Python:
pip install package_name
  1. Regular Expressions
  • Regular expressions are a powerful tool for searching and manipulating text in Python:
import re

text = 'Hello, my name is John. My email is john@example.com.'
matches = re.findall(r'\b[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b', text)
  • The findall() method returns a list of all matches in the text that match the specified pattern.
  • Regular expressions can be complicated, so it’s recommended to use an online tool or library like the re module to help you build and test your patterns.
  1. JSON
  • JSON is a lightweight data format that is easy to read and write:
import json

data = {'name': 'John', 'age': 30, 'location': 'New York'}
json_string = json.dumps(data)  # json_string is '{"name": "John", "age": 30, "location": "New York"}'
  • You can convert JSON strings to Python objects using the loads() method:
python_object = json.loads(json_string)  # python_object is {'name': 'John', 'age': 30, 'location': 'New York'}
  1. Datetime
  • The datetime module provides classes

for working with dates and times in Python:

from datetime import datetime, timedelta

now = datetime.now()  # current date and time
today = datetime.today()  # current date and time, but without timezone info

yesterday = now - timedelta(days=1)  # subtract one day
tomorrow = now + timedelta(days=1)  # add one day

formatted_date = now.strftime('%Y-%m-%d %H:%M:%S')  # format datetime as string
parsed_date = datetime.strptime('2022-03-26', '%Y-%m-%d')  # parse string as datetime object
  1. Exception Handling
  • You can handle exceptions in Python using try/except blocks:
try:
    result = 10 / 0
except ZeroDivisionError:
    print('Cannot divide by zero')
  • The code inside the try block is executed, and if an exception occurs, the code inside the except block is executed instead.
  1. List Comprehensions
  • List comprehensions are a concise way to create lists in Python:
squares = [x**2 for x in range(10)]  # squares is [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

evens = [x for x in range(10) if x % 2 == 0]  # evens is [0, 2, 4, 6, 8]
  1. Dictionary Comprehensions
  • You can also create dictionaries using comprehensions:
squares_dict = {x: x**2 for x in range(10)}  # squares_dict is {0: 0, 1: 1, 2: 4, 3: 9, 4: 16, 5: 25, 6: 36, 7: 49, 8: 64, 9: 81}
  1. Generator Expressions
  • Generator expressions are similar to list comprehensions, but they return a generator object instead of a list:
squares = (x**2 for x in range(10))  # squares is a generator object
for square in squares:
    print(square)
  1. Lambda Functions
  • Lambda functions are anonymous functions that can be defined in a single line:
square = lambda x: x**2
result = square(5)  # result is 25
  • Lambda functions are often used as arguments to higher-order functions like map() and filter().
  1. Map and Filter
  • The map() and filter() functions are higher-order functions that operate on iterables:
numbers = [1, 2, 3, 4, 5]

squares = map(lambda x: x**2, numbers)  # squares is [1, 4, 9, 16, 25]

evens = filter(lambda x: x % 2 == 0, numbers)  # evens is [2, 4]

Sure, here are 10 more Python cheat sheet items:

  1. Args and Kwargs
  • Args and kwargs allow you to pass variable-length argument lists to functions:
def my_function(*args):
    for arg in args:
        print(arg)

my_function(1, 2, 3)  # prints 1, 2, 3

def my_function(**kwargs):
    for key, value in kwargs.items():
        print(key, value)

my_function(name='John', age=30)  # prints name John, age 30
  1. Decorators
  • Decorators allow you to modify the behavior of functions without changing their code:
def my_decorator(func):
    def wrapper():
        print('Before function')
        func()
        print('After function')
    return wrapper

@my_decorator
def my_function():
    print('Hello, world!')

my_function()  # prints "Before function", "Hello, world!", "After function"
  1. Generators
  • Generators allow you to create iterators using a function:
def my_generator(n):
    for i in range(n):
        yield i**2

squares = my_generator(5)
for square in squares:
    print(square)  # prints 0, 1, 4, 9, 16
  1. Collections
  • The collections module provides additional data structures:
from collections import Counter, defaultdict, OrderedDict

# Counter
c = Counter('hello')
print(c)  # prints Counter({'l': 2, 'h': 1, 'e': 1, 'o': 1})

# defaultdict
d = defaultdict(int)
d['key'] += 1
print(d)  # prints defaultdict(<class 'int'>, {'key': 1})

# OrderedDict
od = OrderedDict()
od['a'] = 1
od['b'] = 2
print(od)  # prints OrderedDict([('a', 1), ('b', 2)])
  1. Set Operations
  • You can perform set operations like union and intersection:
set1 = {1, 2, 3}
set2 = {3, 4, 5}

union = set1.union(set2)  # union is {1, 2, 3, 4, 5}
intersection = set1.intersection(set2)  # intersection is {3}
  1. Regular Expressions
  • Regular expressions allow you to search for patterns in strings:
import re

text = 'Hello, my name is John'
pattern = r'name is (\w+)'
match = re.search(pattern, text)
print(match.group(1))  # prints "John"

I hope this helps! Let me know if you have any more questions.

Sure, here are some more Python cheat sheet items:

  1. File I/O
  • You can read from and write to files using the open function:
# Reading from a file
with open('file.txt', 'r') as f:
    contents = f.read()

# Writing to a file
with open('file.txt

I’m sorry for the mistake. Here are some more unique Python cheat sheet items:

  1. File I/O
  • You can read from and write to files using the open function:
# Reading from a file
with open('file.txt', 'r') as f:
    contents = f.read()

# Writing to a file
with open('file.txt', 'w') as f:
    f.write('Hello, world!')
  1. Exceptions
  • Exceptions allow you to handle errors and unexpected situations in your code:
try:
    x = 1 / 0
except ZeroDivisionError:
    print('Cannot divide by zero')
  1. Debugging
  • You can use the built-in debugger to step through your code:
import pdb

def my_function():
    x = 1
    y = 2
    pdb.set_trace()  # start debugger
    z = x + y
    print(z)

my_function()
  1. Virtual Environments
  • Virtual environments allow you to create isolated Python environments for your projects:
# Creating a virtual environment
python -m venv myenv

# Activating the virtual environment
source myenv/bin/activate

# Installing packages in the virtual environment
pip install package_name

# Deactivating the virtual environment
deactivate
  1. Multithreading
  • Multithreading allows you to run multiple threads of execution in parallel:
import threading

def my_function():
    print('Starting function')
    # do some work
    print('Ending function')

t = threading.Thread(target=my_function)
t.start()  # start the thread
t.join()  # wait for the thread to finish
  1. Functional Programming
  • Python supports functional programming techniques:
# Map
items = [1, 2, 3]
squared = list(map(lambda x: x**2, items))

# Filter
numbers = [1, 2, 3, 4, 5]
even = list(filter(lambda x: x % 2 == 0, numbers))

# Reduce
from functools import reduce
numbers = [1, 2, 3, 4, 5]
total = reduce(lambda x, y: x + y, numbers)
  1. Third-Party Packages
  • Python has a vast library of third-party packages that you can install and use in your projects:
# Installing a package
pip install package_name

# Importing a package
import package_name

I hope this helps.

Leave a Comment