DEV Community

Documendous
Documendous

Posted on

Python Basics Cheat Sheet

Python Cheatsheet

Basics

# Print Statement print("Hello, World!") # Variables x = 5 y = "Hello" # Data Types int_var = 10 # Integer float_var = 10.5 # Float str_var = "Hello" # String bool_var = True # Boolean list_var = [1, 2, 3] # List tuple_var = (1, 2, 3) # Tuple set_var = {1, 2, 3} # Set dict_var = {"key": "value"} # Dictionary 
Enter fullscreen mode Exit fullscreen mode

Control Structures

# If-Else if x > 0: print("Positive") elif x == 0: print("Zero") else: print("Negative") # For Loop for i in range(5): print(i) # While Loop count = 0 while count < 5: print(count) count += 1 
Enter fullscreen mode Exit fullscreen mode

Functions

def my_function(param1, param2): return param1 + param2 result = my_function(5, 3) print(result) 
Enter fullscreen mode Exit fullscreen mode

Classes

class MyClass: def __init__(self, name): self.name = name def greet(self): return f"Hello, {self.name}!" obj = MyClass("Harlin") print(obj.greet()) 
Enter fullscreen mode Exit fullscreen mode

Exception Handling

try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") finally: print("Execution complete.") 
Enter fullscreen mode Exit fullscreen mode

File Operations

# Read from a file with open('file.txt', 'r') as file: content = file.read() print(content) # Write to a file with open('file.txt', 'w') as file: file.write("Hello, World!") 
Enter fullscreen mode Exit fullscreen mode

List Comprehensions

# Basic List Comprehension squares = [x**2 for x in range(10)] print(squares) # Conditional List Comprehension evens = [x for x in range(10) if x % 2 == 0] print(evens) 
Enter fullscreen mode Exit fullscreen mode

Lambda Functions

# Lambda Function add = lambda a, b: a + b print(add(5, 3)) 
Enter fullscreen mode Exit fullscreen mode

Map, Filter, Reduce

from functools import reduce # Map numbers = [1, 2, 3, 4, 5] squared = list(map(lambda x: x**2, numbers)) print(squared) # Filter evens = list(filter(lambda x: x % 2 == 0, numbers)) print(evens) # Reduce sum_numbers = reduce(lambda a, b: a + b, numbers) print(sum_numbers) 
Enter fullscreen mode Exit fullscreen mode

Modules

# Importing a Module import math print(math.sqrt(16)) # Importing Specific Functions from math import pi, sin print(pi) print(sin(0)) 
Enter fullscreen mode Exit fullscreen mode

Numpy Basics

import numpy as np # Creating Arrays arr = np.array([1, 2, 3, 4, 5]) print(arr) # Array Operations print(arr + 5) print(arr * 2) print(np.sqrt(arr)) 
Enter fullscreen mode Exit fullscreen mode

Pandas Basics

import pandas as pd # Creating DataFrame data = { 'Name': ['Alice', 'Bob', 'Charlie'], 'Age': [24, 27, 22] } df = pd.DataFrame(data) print(df) # Basic Operations print(df['Name']) print(df.describe()) print(df[df['Age'] > 23]) 
Enter fullscreen mode Exit fullscreen mode

Matplotlib Basics

import matplotlib.pyplot as plt # Basic Plot x = [1, 2, 3, 4, 5] y = [2, 3, 5, 7, 11] plt.plot(x, y) plt.xlabel('x-axis') plt.ylabel('y-axis') plt.title('Sample Plot') plt.show() 
Enter fullscreen mode Exit fullscreen mode

Top comments (0)