Networking, Security & Cloud Knowledge

Friday, October 25, 2024

Python Cheat Sheet

Python Cheat Sheet

Python Cheat Sheet

Basic Syntax

# Comments 
# This is a comment

# Variables 
x = 5
name = "Alice"

# Data Types 
integer = 10
float_num = 10.5
string = "Hello"
boolean = True
list_example = [1, 2, 3]
tuple_example = (1, 2, 3)
dict_example = {"key": "value"}

Control Structures

# If Statements
if x > 0:
    print("Positive")
elif x < 0:
    print("Negative")
else:
    print("Zero")

# Loops
# For Loop
for i in range(5):
    print(i)

# While Loop
while x < 5:
    x += 1

Functions

# Defining Functions
def my_function(param1, param2):
    return param1 + param2

# Lambda Functions
square = lambda x: x ** 2

Data Structures

# Lists
my_list = [1, 2, 3]
my_list.append(4)

# Dictionaries
my_dict = {"name": "Alice", "age": 25}
age = my_dict["age"]

# Sets
my_set = {1, 2, 3}
my_set.add(4)

# Tuples
my_tuple = (1, 2, 3)

List Comprehensions

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

String Methods

# Common Methods
my_string = "Hello, World!"
my_string.lower()
my_string.upper()
my_string.split(", ")

File Handling

# Reading a File
with open('file.txt', 'r') as file:
    content = file.read()

# Writing to a File
with open('file.txt', 'w') as file:
    file.write("Hello, World!")

Exception Handling

try:
    # Code that may raise an exception
    result = 10 / 0
except ZeroDivisionError:
    print("You can't divide by zero!")
finally:
    print("This will always execute.")

Modules and Packages

# Importing Modules
import math
from datetime import datetime

Decorators

def my_decorator(func):
    def wrapper():
        print("Before the function.")
        func()
        print("After the function.")
    return wrapper

@my_decorator
def say_hello():
    print("Hello!")

Generators

def countdown(n):
    while n > 0:
        yield n
        n -= 1

for number in countdown(5):
    print(number)

Common Built-in Functions

# len(), sum(), max(), min(), sorted(), enumerate()

Useful Libraries

# NumPy, Pandas, Matplotlib, Requests, Flask/Django

Common Commands

# Install a Package
pip install package_name

# Run a Python Script
python script.py