Published on

Python Cheat Sheet

Table of Contents

credit to https://quickref.me/python credit to https://learnxinyminutes.com/docs/python/

================================

Basic Syntax

  • Comments: # This is a comment
  • Indentation: Use 4 spaces (not tabs) for each level of indentation.
  • Variables:
    • Naming: Start with a letter or underscore, case-sensitive (e.g., my_variable = 5).
    • Types: Dynamically typed (inferred from the value).

Data Types

  • Numbers: int (integer), float (floating-point), complex
  • Strings: 'single quotes' or "double quotes"
  • Lists: [1, 2, 'apple'] (ordered, mutable)
  • Tuples: (1, 2, 'banana') (ordered, immutable)
  • Dictionaries: {'key': 'value'} (unordered, mutable)
  • Sets: {1, 2, 3} (unordered, unique elements)
  • Booleans: True, False

Operators

  • Arithmetic: +, -, *, /, // (floor division), % (modulo), ** (exponentiation)
  • Comparison: ==, !=, <, >, <=, >=
  • Logical: and, or, not
  • Assignment: =, +=, -=, *=, etc.
  • Membership: in, not in
  • Identity: is, is not

Control Flow

  • Conditional Statements:

    if condition:
        # code block
    elif another_condition:
        # code block
    else:
        # code block
    
  • Loops:

    for item in iterable:
        # code block
    
    while condition:
        # code block
    

Functions

def function_name(parameters):
    # function body
    return value  # optional

Modules

  • Import standard library modules: import math, import random, etc.
  • Import external modules: pip install module_name

Classes

class MyClass:
    def __init__(self, parameters):
        # constructor
        self.attribute = value

    def method_name(self):
        # method body

Error Handling

try:
    # code that might raise an error
except ExceptionType:
    # code to handle the error
finally:
    # code that always executes

File I/O

with open('filename.txt', 'r') as file:
    data = file.read()  # 'w' for writing, 'a' for appending

Resources