Language: EN

cheatsheet-python

Python Cheatsheet

Python is an interpreted, high-level programming language with a clear and easy-to-understand syntax.

It is widely used in various areas such as web development, data analysis, artificial intelligence, among others.

Installation

You can download Python from its official site and follow the installation instructions for your operating system.

Hello, World in Python

print("Hello, World!")

Fundamentals of Python

Printing to the screen

To display text or variables in the console.

print("Hello, world")

Comments

Comments begin with # and are not executed.

# This is a comment

Variables and Data Types

Variable Declaration

Python is dynamic, it does not require explicit variable type declaration.

x = 5       # Integer
y = 3.14    # Float
name = "Python"  # String
active = True  # Boolean

Data Types

  • int: Integer with no size limit
  • float: Floating-point number
  • str: String of characters
  • bool: Boolean value (True or False)

Basic Operators

Arithmetic operators like addition, subtraction, multiplication, and division.

a = 5 + 3
b = 10 - 2
c = 6 * 3
d = 10 / 2

String Concatenation

greeting = "Hello, " + "World!"

Control Structures

Conditionals

If, elif, else

Basic conditional that evaluates a condition and executes a block of code.

if x > 5:
    print("x is greater than 5")
elif x == 5:
    print("x is equal to 5")
else:
    print("x is less than 5")

Loops

For Loop

Iterates over a sequence of elements, such as lists or strings.

for i in range(5):
    print(i)

While Loop

Executes the block while the condition is true.

i = 0
while i < 5:
    print(i)
    i += 1

Break and Continue Statements

To interrupt or skip iterations.

for i in range(10):
    if i == 5:
        break  # Breaks the loop
    elif i % 2 == 0:
        continue  # Skips this iteration
    print(i)

Data Structures

Lists

Lists are ordered and mutable collections.

my_list = [1, 2, 3, 4, 5]
print(my_list[0])  # Access the first element
my_list.append(6)  # Add an element
my_list.remove(3)  # Remove an element

Slicing

Access sublists using indices.

sublist = my_list[1:4]  # From the second to the fourth element

Tuples

Tuples are immutable and ordered.

my_tuple = (1, 2, 3)

Dictionaries

Dictionaries store key-value pairs.

my_dict = {"name": "Python", "year": 1991}
print(my_dict["name"])  # Access the value of a key
my_dict["year"] = 2023  # Modify a value

Sets

A set does not allow duplicates.

my_set = {1, 2, 3, 4, 4}
my_set.add(5)  # Add an element
my_set.remove(3)  # Remove an element

List Comprehensions

Create lists concisely.

squares = [x**2 for x in range(10)]

Functions

Function Declaration

def add(a, b):
    return a + b

Function Call

result = add(5, 3)

Optional Arguments and Default Values

def greet(name="Friend"):
    print(f"Hello, {name}")

Lambda Functions

Single-line anonymous function.

add = lambda x, y: x + y
print(add(2, 3))

Modules and Packages

Importing Modules

import math
print(math.sqrt(16))  # Print the square root of 16

Importing a Specific Function

from math import sqrt
print(sqrt(16))

Object-Oriented Programming (OOP)

Class Declaration

class Person:
    def __init__(self, name, age):
        self.name = name
        self.age = age

    def introduce(self):
        print("Hello, I am", self.name, "and I am", self.age, "years old.")

Creating Objects

person1 = Person("Luis", 30)
person1.introduce()

Encapsulation and Properties

Control access to attributes and methods.

class Person:
    def __init__(self, name, age):
        self._name = name  # Protected attribute
        self.__age = age  # Private attribute

    def get_age(self):
        return self.__age

Inheritance

A child class inherits from a parent class.

class Vehicle:
    def __init__(self, type):
        self.type = type

class Car(Vehicle):
    def __init__(self, make, model):
        super().__init__("Car")
        self.make = make
        self.model = model

my_car = Car("Toyota", "Corolla")

Polymorphism

person2 = Employee("Maria", 25, "Developer")
person2.introduce()

Exception Handling

Try-except

Error and exception handling.

try:
    x = 1 / 0
except ZeroDivisionError:
    print("Cannot divide by zero")
finally:
    print("This block always executes")

Raising Exceptions

Generating custom exceptions.

if x < 0:
    raise ValueError("x cannot be negative")

File Input and Output

Reading Files

with open("file.txt", "r") as file:
    content = file.read()

Writing Files

with open("file.txt", "w") as file:
    file.write("New content")

Line-by-line File Manipulation

Read a file line by line.

with open("file.txt", "r") as file:
    for line in file:
        print(line.strip())

Advanced Python

Generators

Function that returns a value with yield and remembers its state.

def counter():
    i = 0
    while i < 5:
        yield i
        i += 1

gen = counter()
print(next(gen))  # Prints 0
print(next(gen))  # Prints 1

Decorators

Function that modifies the behavior of another function.

def decorator(function):
    def new_function(*args, **kwargs):
        print("Before executing the function")
        result = function(*args, **kwargs)
        print("After executing the function")
        return result
    return new_function

@decorator
def greet():
    print("Hello")

greet()

Context Managers

To manage resources like files, network connections, etc.

class MyContext:
    def __enter__(self):
        print("Entering the context")
        return self

    def __exit__(self, exc_type, exc_val, exc_tb):
        print("Exiting the context")

with MyContext():
    print("Inside the block")

Common Libraries

NumPy

Library for numerical computation.

import numpy as np
a = np.array([1, 2, 3])
print(np.mean(a))  # Arithmetic mean

Pandas

Library for data analysis.

import pandas as pd
df = pd.DataFrame({"A": [1, 2], "B": [3, 4]})
print(df)

Matplotlib

Library for graph visualization.

import matplotlib.pyplot as plt
plt.plot([1, 2, 3], [4, 5, 6])
plt.show()

Requests

Library for making HTTP requests.

import requests
response = requests.get('https://api.example.com')
print(response.status_code)

Flask

Lightweight framework for creating web applications.

from flask import Flask
app = Flask(__name__)

@app.route('/')
def index():
    return "Hello, world"

if __name__ == "__main__":
    app.run()

Debugging Tools

Using assert

Verifies a condition during execution.

assert x > 0, "x must be greater than 0"

Debugging with pdb

Starts the interactive debugger.

import pdb; pdb

.set_trace()