Basic Syntax and Types Comments: Single line # comment , Multi-line """comment""" Variables: No explicit type declaration. x = 10 , name = "Alice" Data Types: Numbers: int , float , complex Strings: str (immutable) Booleans: bool ( True , False ) Lists: list (mutable, ordered collection) [1, "a", 3.0] Tuples: tuple (immutable, ordered collection) (1, "a", 3.0) Dictionaries: dict (mutable, key-value pairs) {"a": 1, "b": 2} Sets: set (mutable, unordered, unique elements) {1, 2, 3} Type Conversion: int() , float() , str() , list() , tuple() , dict() , set() Operators Arithmetic: + , - , * , / (float division), // (integer division), % (modulo), ** (exponent) Comparison: == , != , > , < , >= , <= Logical: and , or , not Assignment: = , += , -= , *= , etc. Identity: is , is not (compare object identity) Membership: in , not in (check for presence in sequence) Control Flow Conditional Statements if condition: # code if true elif another_condition: # code if true else: # code if all false Loops For Loop: for item in iterable: # code to execute for i in range(5): # 0, 1, 2, 3, 4 print(i) While Loop: while condition: # code to execute # ensure condition eventually becomes false Loop Control: break : Exits the loop continue : Skips to the next iteration Functions def my_function(param1, param2="default"): """Docstring: Explains what the function does.""" # function body result = param1 + param2 return result # Calling a function output = my_function(10, 20) output_default = my_function(5) Lambda Functions (Anonymous): lambda args: expression Scope: LEGB (Local, Enclosing, Global, Built-in) Strings Indexing: s[0] (first char), s[-1] (last char) Slicing: s[start:end:step] ( s[1:4] , s[::2] ) Methods: len(s) : Length s.lower() , s.upper() s.strip() : Remove whitespace s.split(',') : Split string by delimiter s.join(list_of_strings) : Join elements with string as separator s.replace('old', 'new') s.find('substring') , s.count('char') s.startswith('prefix') , s.endswith('suffix') f-strings (Formatted String Literals): f"Name: {name}, Age: {age}" Lists Creation: my_list = [1, 2, 'a'] Indexing & Slicing: Same as strings Methods: my_list.append(item) : Add to end my_list.insert(index, item) my_list.extend(another_list) my_list.remove(value) : Remove first occurrence my_list.pop(index) : Remove and return item at index (default last) my_list.sort() , sorted(my_list) (returns new list) my_list.reverse() my_list.count(value) my_list.clear() List Comprehensions: [expression for item in iterable if condition] Example: squares = [x**2 for x in range(5)] Tuples Creation: my_tuple = (1, 2, 'a') or 1, 2, 'a' Immutable: Elements cannot be changed after creation. Methods: count() , index() Often used for fixed collections or function return values. Dictionaries Creation: my_dict = {"name": "Alice", "age": 30} Access: my_dict["name"] , my_dict.get("city", "Unknown") Add/Modify: my_dict["city"] = "NY" Remove: del my_dict["age"] , my_dict.pop("name") Methods: my_dict.keys() : View of all keys my_dict.values() : View of all values my_dict.items() : View of (key, value) pairs my_dict.update(another_dict) Dictionary Comprehensions: {key_exp: val_exp for item in iterable} Sets Creation: my_set = {1, 2, 3} , my_set = set([1, 2, 2]) Add/Remove: my_set.add(4) , my_set.remove(1) , my_set.discard(5) Set Operations: set1.union(set2) or set1 | set2 set1.intersection(set2) or set1 & set2 set1.difference(set2) or set1 - set2 set1.symmetric_difference(set2) or set1 ^ set2 Error Handling try: # code that might raise an exception result = 10 / 0 except ZeroDivisionError: # handle specific error print("Cannot divide by zero!") except Exception as e: # handle any other exception print(f"An error occurred: {e}") else: # code to run if no exceptions print("Operation successful.") finally: # code that always runs print("Execution finished.") File I/O # Reading a file with open("my_file.txt", "r") as f: content = f.read() # read all lines = f.readlines() # read lines into a list for line in f: # iterate line by line print(line.strip()) # Writing to a file with open("output.txt", "w") as f: # "a" for append f.write("Hello, Python!\n") f.write("This is a new line.") Classes and Objects (OOP) class MyClass: class_variable = "I am a class variable" def __init__(self, param1, param2): self.instance_variable1 = param1 # instance variable self.instance_variable2 = param2 def my_method(self): return f"Method called: {self.instance_variable1}" @classmethod def class_method(cls): return f"Class method: {cls.class_variable}" @staticmethod def static_method(x, y): return x + y # Create an object (instance) obj = MyClass("value1", "value2") print(obj.instance_variable1) print(obj.my_method()) print(MyClass.class_method()) print(MyClass.static_method(1, 2)) Inheritance: class Child(Parent): Polymorphism: Methods with the same name in different classes. Encapsulation: Using methods to control access to attributes. (Convention: _private , __mangled ) Modules and Packages Import: import math : Access with math.sqrt(16) import math as m : Access with m.pi from math import sqrt, pi : Access directly sqrt(9) , pi from math import * : Imports all (discouraged) Packages: Directories containing modules and an __init__.py file. Useful Built-in Modules: os , sys , datetime , json , re , random , collections . Decorators def my_decorator(func): def wrapper(*args, **kwargs): print("Something before the function call") result = func(*args, **kwargs) print("Something after the function call") return result return wrapper @my_decorator def say_hello(name): print(f"Hello, {name}!") say_hello("Alice") Generators Functions that use yield to produce a sequence of results one at a time. Memory efficient for large sequences. def count_up_to(n): i = 0 while i < n: yield i i += 1 for num in count_up_to(5): print(num) # 0, 1, 2, 3, 4 Context Managers ( with statement) Ensures resources are properly acquired and released (e.g., files, locks). Implemented using __enter__ and __exit__ methods. class MyContext: def __enter__(self): print("Entering context") return self def __exit__(self, exc_type, exc_val, exc_tb): print("Exiting context") # Handle exceptions if needed return False # Propagate exception with MyContext() as mc: print("Inside context")