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

session 19 Git Repository

  🔁 Steps to Create a Branch in Databricks, Pull from Git, and Merge into a Collaborative Branch Create a New Branch in Databricks: Go to the Repos tab in your workspace. Navigate to the Git-linked repo. Click the Git icon (or three dots ⋮) and choose "Create Branch." Give your branch a name (e.g., feature-xyz ) and confirm. Pull the Latest Changes from Git: With your new branch selected, click the Git icon again. Select “Pull” to bring the latest updates from the remote repository into your local Databricks environment. Make Changes & Commit: Edit notebooks or files as needed in your branch. Use the "Commit & Push" option to push changes to the remote repo. Merge into the Collaborative Branch: Switch to the collaborative branch (e.g., dev or main ) in Git or from the Databricks UI. Click "Pull & Merge" . Choose the branch you want to merge into the collaborative branch. Review the c...

Session 18 monitering and logging - Azure Monitor , Log analytics , and job notification

 After developing the code, we deploy it into the production environment. To monitor and logging the jobs run in the real time systems in azure  we have scheduled the jobs under the workflow , we haven't created any monitoring or any matrics . After a few times, the job failed, but we don't know because we haven't set up any monitoring, and every time we can't navigate to workspace-> workflows, under runs to see to check whether the job has been successfully running or not and in real time there will be nearly 100 jobs or more jobs to run  In real time, the production support team will monitor the process. Under the workflow, there is an option called Job notification. After setting the job notification, we can set a notification to email . if we click the date and time its takes us to the notebook which is scheduled there we can able to see the error where it happens . order to see more details, we need to under Spark tab, where we have the option to view logs ( tha...

Transformation - section 6 - data flow

  Feature from Slide Explanation ✅ Code-free data transformations Data Flows in ADF allow you to build transformations using a drag-and-drop visual interface , with no need for writing Spark or SQL code. ✅ Executed on Data Factory-managed Databricks Spark clusters Internally, ADF uses Azure Integration Runtimes backed by Apache Spark clusters , managed by ADF, not Databricks itself . While it's similar in concept, this is not the same as your own Databricks workspace . ✅ Benefits from ADF scheduling and monitoring Data Flows are fully integrated into ADF pipelines, so you get all the orchestration, parameterization, logging, and alerting features of ADF natively. ⚠️ Important Clarification Although it says "executed on Data Factory managed Databricks Spark clusters," this does not mean you're using your own Azure Databricks workspace . Rather: ADF Data Flows run on ADF-managed Spark clusters. Azure Databricks notebooks (which you trigger via an "Exe...