python programming

Python Cheat Sheet

Whether you’re a beginner just starting with Python or a seasoned developer needing a quick refresher, this Python Cheat Sheet has you covered! This concise guide includes essential syntax, common functions, data structures, loops, conditionals, file handling, and more. Keep it handy while coding or studying to boost your productivity and confidence. Dive in and supercharge your Python skills with this all-in-one reference! Basic Syntax Python uses clean, readable syntax without semicolons or curly braces. Indentation matters – it defines code blocks! Variables and Data Types Python is dynamically typed – you don’t need to declare variable types. Just assign and go! # Variables (no declaration needed) name = “Alice” age = 25 height = 5.6 is_student = True # Data types str_var = “Hello” # String int_var = 42 # Integer float_var = 3.14 # Float bool_var = True # Boolean list_var = [1, 2, 3] # List tuple_var = (1, 2, 3) # Tuple dict_var = {“key”: “value”} # Dictionary set_var = {1, 2, 3} # Set Control Structures These are the building blocks that control how your program flows and makes decisions. If Statements Make your program smart by adding decision-making logic. if age >= 18: print(“Adult”) elif age >= 13: print(“Teenager”) else: print(“Child”) Loops Automate repetitive tasks – let Python do the boring work for you! # For loop for i in range(5): print(i) for item in [1, 2, 3]: print(item) # While loop count = 0 while count < 5: print(count) count += 1 Data Structures Python’s built-in containers for organizing and storing your data efficiently. Lists The Swiss Army knife of Python data structures – ordered, changeable, and versatile. # Creating and modifying lst = [1, 2, 3, 4, 5] lst.append(6) # Add to end lst.insert(0, 0) # Insert at index lst.remove(3) # Remove first occurrence lst.pop() # Remove last item lst[0] = 10 # Change item len(lst) # Length Dictionaries Key-value pairs that let you store and retrieve data like a real-world dictionary. # Creating and accessing person = {“name”: “Alice”, “age”: 25} person[“name”] # Access value person[“city”] = “NYC” # Add new key-value del person[“age”] # Delete key person.keys() # Get all keys person.values() # Get all values person.get(“name”, “Unknown”) # Safe access Sets Collections of unique items – perfect when you need to eliminate duplicates or check membership. # Creating and operations s1 = {1, 2, 3, 4} s2 = {3, 4, 5, 6} s1.add(5) # Add element s1.remove(1) # Remove element s1 & s2 # Intersection s1 | s2 # Union s1 – s2 # Difference Functions Write reusable code blocks that make your programs modular and easier to maintain. Basic Functions Define once, use everywhere – functions are your best friend for organized code. def greet(name, greeting=”Hello”): return f”{greeting}, {name}!” def add_numbers(*args): return sum(args) def person_info(**kwargs): for key, value in kwargs.items(): print(f”{key}: {value}”) # Lambda functions square = lambda x: x**2 List Comprehensions Python’s elegant way to create lists in a single line – concise and powerful! # Basic list comprehension squares = [x**2 for x in range(10)] # With condition evens = [x for x in range(20) if x % 2 == 0] # Dictionary comprehension square_dict = {x: x**2 for x in range(5)} # Set comprehension unique_chars = {char for char in “hello world”} String Operations Text manipulation made easy – Python treats strings like first-class citizens. File Operations Read from and write to files – your gateway to persistent data storage. # Reading files with open(“file.txt”, “r”) as f: content = f.read() lines = f.readlines() # Writing files with open(“file.txt”, “w”) as f: f.write(“Hello World”) f.writelines([“Line 1\n”, “Line 2\n”]) Exception Handling Handle errors gracefully – because things don’t always go as planned! try: result = 10 / 0 except ZeroDivisionError: print(“Cannot divide by zero”) except Exception as e: print(f”An error occurred: {e}”) else: print(“No errors occurred”) finally: print(“This always executes”) Classes and Objects Object-oriented programming in Python – create your custom data types and behaviors. class Person: def __init__(self, name, age): self.name = name self.age = age def greet(self): return f”Hi, I’m {self.name}” def __str__(self): return f”Person(name='{self.name}’, age={self.age})” # Usage person = Person(“Alice”, 25) print(person.greet()) Common Built-in Functions Python’s toolbox of ready-to-use functions that save you time and effort. # Math functions abs(-5) # Absolute value min(1, 2, 3) # Minimum max(1, 2, 3) # Maximum sum([1, 2, 3]) # Sum of iterable round(3.14159, 2) # Round to 2 decimals # Type functions type(42) # Get type isinstance(42, int) # Check type len([1, 2, 3]) # Length # Iteration functions enumerate([1, 2, 3]) # Returns (index, value) pairs zip([1, 2], [‘a’, ‘b’]) # Combine iterables reversed([1, 2, 3]) # Reverse iterator sorted([3, 1, 2]) # Return sorted list Import and Modules Extend Python’s capabilities by using libraries – standing on the shoulders of giants! import math from math import pi, sqrt import numpy as np from datetime import datetime, timedelta # Using imports math.sqrt(16) pi np.array([1, 2, 3]) datetime.now() Common Patterns Real-world examples of frequently used Python patterns that every developer should know. Working with the Os module Files and Directories Navigate and manipulate your file system like a pro. import os os.listdir(‘.’) # List directory contents os.path.exists(‘file.txt’) # Check if file exists os.path.join(‘folder’, ‘file.txt’) # Join paths Date and Time Work with dates and times – essential for logging, scheduling, and data analysis. from datetime import datetime, timedelta now = datetime.now() tomorrow = now + timedelta(days=1) formatted = now.strftime(‘%Y-%m-%d %H:%M:%S’) Regular Expressions Pattern matching and text processing – powerful tools for working with strings. import re pattern = r’\d+’ # Match digits re.findall(pattern, “I have 5 apples and 3 oranges”) re.search(pattern, “Age: 25”) re.sub(r’\d+’, ‘X’, “I have 5 apples”) # Replace Useful Tips Pro tips and Python idioms that will make you more productive and your code more Pythonic. Please download the Full PDF.

Python Cheat Sheet Read More »