Skip to main content

python cheatsheet


Basics

  • Comments:
    Python
    # This is a single-line comment
    """
    This is a
    multi-line comment
    """
    
  • Variables:
    Python
    x = 5
    name = "Alice"
    is_valid = True
    
    • Dynamically typed (you don't need to declare the type).
    • Case-sensitive (myVar is different from myvar).
  • Data Types:
    • Numeric: int (integer), float (floating-point), complex (complex numbers)
    • Sequence: str (string), list, tuple, range
    • Mapping: dict (dictionary)
    • Set: set, frozenset
    • Boolean: bool (True, False)
    • NoneType: None
  • Operators:
    • Arithmetic: + (add), - (subtract), * (multiply), / (divide), // (floor division), % (modulo), ** (exponent)
    • Comparison: == (equal), != (not equal), > (greater than), < (less than), >= (greater than or equal to), <= (less than or equal to)
    • Logical: and, or, not
    • Assignment: =, +=, -=, *=, /=, //=, %=, **=
    • Identity: is, is not (check if objects are the same in memory)
    • Membership: in, not in (check if a value is present in a sequence)

Control Flow

  • Conditional Statements:
    Python
    if condition:
        # code to execute if condition is True
    elif another_condition:
        # code to execute if another_condition is True
    else:
        # code to execute if none of the above conditions are True
    
  • Loops:
    • for loop: Iterates over a sequence (list, tuple, string, range, etc.)
      Python
      for item in sequence:
          # code to execute for each item
      
      • range(start, stop, step): Generates a sequence of numbers.
      • enumerate(sequence): Returns pairs of (index, item).
    • while loop: Executes as long as a condition is True.
      Python
      while condition:
          # code to execute while condition is True
      
    • Loop Control Statements:
      • break: Exits the loop immediately.
      • continue: Skips the current iteration and proceeds to the next.
      • pass: Does nothing (placeholder).

Data Structures

  • Lists: Ordered, mutable sequences of items.
    Python
    my_list = [1, "hello", 3.14]
    my_list.append(4)       # Add to the end
    my_list.insert(1, "world") # Insert at a specific index
    my_list.remove("hello")  # Remove the first occurrence of a value
    popped_item = my_list.pop(2) # Remove and return item at index (default: last)
    length = len(my_list)
    sliced_list = my_list[1:3] # Slicing (start:end:step)
    
  • Tuples: Ordered, immutable sequences of items.
    Python
    my_tuple = (1, "hello", 3.14)
    # Tuples are often used for fixed collections
    
  • Dictionaries: Unordered collections of key-value pairs.
    Python
    my_dict = {"name": "Bob", "age": 30}
    print(my_dict["name"])   # Access value by key
    my_dict["city"] = "New York" # Add a new key-value pair
    del my_dict["age"]       # Delete a key-value pair
    keys = my_dict.keys()
    values = my_dict.values()
    items = my_dict.items()   # Returns a list of (key, value) tuples
    
  • Sets: Unordered collections of unique elements.
    Python
    my_set = {1, 2, 3, 3, 4} # {1, 2, 3, 4} (duplicates are automatically removed)
    my_set.add(5)
    my_set.remove(3)
    union_set = my_set.union({5, 6})
    intersection_set = my_set.intersection({2, 4})
    

Functions

  • Defining Functions:
    Python
    def greet(name="Guest"): # Default argument
        print(f"Hello, {name}!")
        return "Greeting sent" # Optional return value
    
    message = greet("Charlie")
    greet() # Uses the default argument
    
  • Function Arguments:
    • Positional arguments: Passed in the order they are defined.
    • Keyword arguments: Passed with the parameter name (greet(name="David")).
    • *args: Collects extra positional arguments into a tuple.
    • **kwargs: Collects extra keyword arguments into a dictionary.
  • Lambda Functions (Anonymous Functions):
    Python
    square = lambda x: x**2
    result = square(5) # result is 25
    

Modules and Packages

  • Importing Modules:
    Python
    import math
    print(math.sqrt(16))
    
    import random as rnd # Alias the module
    print(rnd.randint(1, 10))
    
    from datetime import date # Import specific names
    today = date.today()
    
  • Packages: Hierarchical directory structure that organizes modules. Use dot notation to access modules within packages (e.g., my_package.my_module).

Input and Output

  • print(): Displays output to the console.
    Python
    print("Hello, world!")
    print("Value:", x, "Another value:", name) # Multiple arguments
    print(f"Formatted string: {x=}, {name=}") # f-strings (formatted string literals)
    
  • input(): Reads input from the user (returns a string).
    Python
    user_input = input("Enter something: ")
    number = int(input("Enter a number: ")) # Convert to integer
    
  • File Handling:
    Python
    # Reading from a file
    with open("my_file.txt", "r") as file:
        content = file.read()       # Read the entire file
        lines = file.readlines()    # Read all lines into a list
        for line in file:          # Iterate over lines
            print(line.strip())     # Remove leading/trailing whitespace
    
    # Writing to a file
    with open("output.txt", "w") as file: # 'w' for write (overwrites), 'a' for append
        file.write("Hello, file!\n")
        file.writelines(["Line 1\n", "Line 2\n"])
    

Object-Oriented Programming (OOP)

  • Classes: Blueprints for creating objects.
    Python
    class Dog:
        def __init__(self, name, breed): # Constructor
            self.name = name
            self.breed = breed
    
        def bark(self):
            print("Woof!")
    
    my_dog = Dog("Buddy", "Golden Retriever")
    print(my_dog.name)
    my_dog.bark()
    
  • Objects (Instances): Created from classes.
  • Methods: Functions defined within a class.
  • Attributes: Variables associated with an object.
  • Inheritance: Allows a class to inherit properties and methods from a parent class.
  • Polymorphism: Ability of different objects to respond to the same method in their own way.

Error Handling

  • try...except Blocks:
    Python
    try:
        result = 10 / 0
    except ZeroDivisionError as e:
        print(f"Error: {e}")
    except (TypeError, ValueError) as e: # Catch multiple exceptions
        print(f"Another error: {e}")
    else:
        print("No error occurred.") # Executed if no exception
    finally:
        print("This will always be executed.") # Cleanup code
    

List Comprehensions

  • A concise way to create lists.
    Python
    squares = [x**2 for x in range(10)] # [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
    even_numbers = [x for x in range(20) if x % 2 == 0]
    

Generator Expressions

  • Similar to list comprehensions but create iterators (more memory-efficient for large sequences).
    Python
    squares_generator = (x**2 for x in range(10))
    for num in squares_generator:
        print(num)
    

String Formatting

  • f-strings (Formatted String Literals): (Python 3.6+) Preferred method.
    Python
    name = "Eve"
    age = 25
    print(f"My name is {name} and I am {age} years old.")
    print(f"{2 + 2 = }") # Inline expressions
    
  • .format() method:
    Python
    print("My name is {} and I am {} years old.".format(name, age))
    print("My name is {0} and I am {1} years old. Again, {0}.".format(name, age))
    print("My name is {n} and I am {a} years old.".format(n=name, a=age))
    
  • Old % formatting: (Less common in modern Python)
    Python
    print("My name is %s and I am %d years old." % (name, age))
    

Common Built-in Functions

  • len(): Returns the length of a sequence.
  • type(): Returns the type of an object.
  • int(), float(), str(), bool(), list(), tuple(), dict(), set(): Type conversion functions.
  • sum(): Sum of elements in an iterable.
  • min(), max(): Minimum and maximum of elements.
  • sorted(): Returns a new sorted list from the items in an iterable.
  • abs(): Absolute value.
  • round(): Rounds a number.
  • pow(base, exp): Equivalent to base ** exp.
  • zip(): Returns an iterator of tuples, where the i-th tuple contains the i-th element from each of the input iterables.
  • map(function, iterable): Applies a function to all items of an iterable.  
  • filter(function, iterable): Filters elements of an iterable based on a function.

This cheatsheet covers many fundamental aspects of Python. As you continue learning and working with Python, you'll encounter more advanced concepts and libraries. Keep practicing and referring to documentation as needed!

Comments

Popular posts from this blog

Entity Relationship (ER) Diagram Model with DBMS Example

Reference :   Entity Relationship (ER) Diagram Model with DBMS Example What is ER Diagram? ER Diagram  stands for Entity Relationship Diagram, also known as ERD is a diagram that displays the relationship of entity sets stored in a database. In other words, ER diagrams help to explain the logical structure of databases. ER diagrams are created based on three basic concepts: entities, attributes and relationships. ER Diagrams contain different symbols that use rectangles to represent entities, ovals to define attributes and diamond shapes to represent relationships. At first look, an ER diagram looks very similar to the flowchart. However, ER Diagram includes many specialized symbols, and its meanings make this model unique. The purpose of ER Diagram is to represent the entity framework infrastructure. Entity Relationship Diagram Example Table of Content: What is ER Diagram? What is ER Model? History of ER models Why use ER Diagrams? Facts about ER Diagram Model ER Diagram...

SQL Joins and advanced joins and Subqueries

  Refernce :  Expert Guide to Advanced SQL Joins: What You Need to Know It's helpful to visualize how these different SQL joins work. Here's a breakdown in a table-like format, along with explanations: SQL Join Types Overview Join Type Description Key Characteristics Use Cases INNER JOIN Returns rows where there is a match in both tables. - Shows only matching records. - Excludes unmatched rows from both tables. - Retrieving related data that exists in both tables. - Finding records with corresponding entries in another table. LEFT OUTER JOIN (LEFT JOIN) Returns all rows from the left table, and the matched rows from the right table. - Includes all records from the left table. - Fills in NULL values for columns from the right table where there's no match. - Retrieving all records from one table and their related data from another, even if some records don't have matches. - Finding records in one table that don't have corresponding entries in another. RIGHT OUTER JO...

GIT BASH

  Bash Shell: Git Bash uses the Bash (Bourne Again SHell) command-line interpreter. This means you can use many of the same commands you'd find in a Linux or macOS terminal. Git Integration: Git Bash is tightly integrated with Git, making it easy to execute Git commands Essential Commands: Navigation: pwd : Prints the current working directory. ls : Lists files and directories in the current directory. cd <directory> : Changes the current directory. cd .. : Moves to the parent directory. File Management: mkdir <directory> : Creates a new directory. touch <file> : Creates a new file. rm <file> : Removes a file. rmdir <directory> : Removes an empty directory. Git Commands: git init : Initializes a new Git repository. git clone <repository URL> : Clones an existing Git repository. git status : Displays the status of your working directory. git add <file> : Adds a file to the staging area. git commit -m "commit message" : Commits chan...