1. Basics & Syntax Comments: Single line: # This is a comment Multi-line: """This is a multi-line comment""" Variables: No explicit type declaration. x = 10 (int) name = "Alice" (str) pi = 3.14 (float) is_true = True (bool) Output: print("Hello, World!") Input: name = input("Enter your name: ") Indentation: 4 spaces (standard) for code blocks. 2. Data Types & Structures 2.1. Numbers Integers: 10, -5 Floats: 3.14, -0.5 Complex: 1 + 2j Operators: +, -, *, /, // (floor div), % (modulo), ** (exponent) 2.2. Strings Creation: 'hello', "world", '''multi-line''' Concatenation: "a" + "b" Repetition: "a" * 3 Indexing: s[0] (first char), s[-1] (last char) Slicing: s[1:4] (chars from index 1 to 3), s[:3] , s[2:] Methods: .upper(), .lower(), .strip(), .replace('a', 'b'), .split(), .join() f-strings (formatted string literals): f"Name: {name}, Age: {age}" 2.3. Lists (Mutable, Ordered) Creation: my_list = [1, 2, 'a', True] Access: my_list[0] , my_list[-1] , my_list[1:3] Modification: my_list[0] = 5 Methods: .append(x), .insert(idx, x), .remove(x), .pop(idx), .sort(), .reverse(), .count(x) Length: len(my_list) 2.4. Tuples (Immutable, Ordered) Creation: my_tuple = (1, 2, 'a') or 1, 2, 'a' Access: my_tuple[0] Cannot be modified after creation. Use for fixed collections of items. 2.5. Dictionaries (Mutable, Unordered, Key-Value pairs) Creation: my_dict = {'name': 'Alice', 'age': 30} Access: my_dict['name'] Add/Modify: my_dict['city'] = 'NY' Methods: .keys(), .values(), .items(), .get('key', default) Deletion: del my_dict['age'] , my_dict.pop('city') 2.6. Sets (Mutable, Unordered, Unique elements) Creation: my_set = {1, 2, 3} , set([1, 2, 2]) results in {1, 2} Add/Remove: .add(4) , .remove(1) Operations: .union(), .intersection(), .difference() 3. Control Flow 3.1. Conditional Statements if condition1: # code if condition1 is true elif condition2: # code if condition1 is false and condition2 is true else: # code if all conditions are false 3.2. Loops For Loop: for item in iterable: # do something with item for i in range(5): # 0, 1, 2, 3, 4 print(i) for i in range(2, 10, 2): # 2, 4, 6, 8 print(i) While Loop: count = 0 while count Loop Control: break : Exits the loop. continue : Skips current iteration, proceeds to next. 4. Functions Definition: def greet(name): return f"Hello, {name}!" message = greet("Alice") Parameters: Default values: def func(a, b=1): Arbitrary arguments: def func(*args): (tuple) Arbitrary keyword arguments: def func(**kwargs): (dict) Lambda Functions (Anonymous): add = lambda x, y: x + y print(add(2, 3)) # Output: 5 5. Classes & Objects (OOP) Class Definition: class Dog: # Class attribute species = "Canis familiaris" def __init__(self, name, age): self.name = name # Instance attribute self.age = age def bark(self): return f"{self.name} says Woof!" def __str__(self): # String representation for print() return f"Dog({self.name}, {self.age})" Object Creation: my_dog = Dog("Buddy", 3) print(my_dog.name) # Output: Buddy print(my_dog.bark()) # Output: Buddy says Woof! Inheritance: class GoldenRetriever(Dog): def __init__(self, name, age, color): super().__init__(name, age) # Call parent constructor self.color = color def fetch(self): return f"{self.name} fetches the ball." 6. Modules & Packages Importing: import math print(math.pi) from datetime import datetime now = datetime.now() import numpy as np # Alias Creating Modules: Save code in a .py file (e.g., my_module.py ) and import it. Packages: Directories containing modules and an __init__.py file. 7. Error Handling Try-Except Block: try: result = 10 / 0 except ZeroDivisionError: print("Cannot divide by zero!") except TypeError as e: print(f"Type error: {e}") except Exception as e: # Catch any other exception print(f"An unexpected error occurred: {e}") else: print("No error occurred.") finally: print("This always executes.") Raising Exceptions: raise ValueError("Invalid value") 8. File I/O Opening Files: # 'r': read, 'w': write (overwrite), 'a': append, 'x': create (error if exists) # 't': text (default), 'b': binary file = open("my_file.txt", "w") file.write("Hello, Python!\n") file.close() Using with statement (Recommended): Ensures file is closed. with open("my_file.txt", "r") as file: content = file.read() # Reads entire file # content = file.readline() # Reads one line # content = file.readlines() # Reads all lines into a list print(content) 9. Advanced Concepts 9.1. List/Dict/Set Comprehensions List: squares = [x**2 for x in range(10) if x % 2 == 0] Dict: sq_dict = {x: x**2 for x in range(5)} Set: unique_nums = {x for x in [1, 2, 2, 3]} 9.2. Generators Functions that yield values, creating iterators. Memory efficient for large sequences. def fibonacci_gen(): a, b = 0, 1 while True: yield a a, b = b, a + b fib_seq = fibonacci_gen() print(next(fib_seq)) # 0 print(next(fib_seq)) # 1 9.3. Decorators Functions that modify other functions. def my_decorator(func): def wrapper(*args, **kwargs): print("Something is happening before the function is called.") result = func(*args, **kwargs) print("Something is happening after the function is called.") return result return wrapper @my_decorator def say_hello(name): print(f"Hello, {name}!") say_hello("Alice") 9.4. Context Managers ( with statement) Objects that define __enter__ and __exit__ methods. from contextlib import contextmanager @contextmanager def open_file_context(path, mode): f = open(path, mode) try: yield f finally: f.close() with open_file_context("test.txt", "w") as f: f.write("Context manager example.") 9.5. Iterators Objects implementing __iter__ and __next__ . my_list = [1, 2, 3] my_iter = iter(my_list) print(next(my_iter)) # 1 print(next(my_iter)) # 2 9.6. Map, Filter, Reduce map(function, iterable) : Applies function to all items. nums = [1, 2, 3] squares = list(map(lambda x: x*x, nums)) # [1, 4, 9] filter(function, iterable) : Filters items based on a function. evens = list(filter(lambda x: x % 2 == 0, nums)) # [2] functools.reduce(function, iterable) : Applies function cumulatively. from functools import reduce product = reduce(lambda x, y: x * y, nums) # 6 10. Common Built-in Functions len(), type(), str(), int(), float(), bool() min(), max(), sum(), sorted() abs(), round() dir() (attributes of an object) help() (documentation) zip() : Aggregates elements from multiple iterables. list1 = [1, 2, 3] list2 = ['a', 'b', 'c'] zipped = list(zip(list1, list2)) # [(1, 'a'), (2, 'b'), (3, 'c')] enumerate() : Adds counter to an iterable. for i, item in enumerate(['a', 'b']): print(f"{i}: {item}") # 0: a, 1: b 11. Virtual Environments Create: python -m venv myenv Activate: Windows: .\myenv\Scripts\activate Unix/macOS: source myenv/bin/activate Install: pip install package_name Requirements: pip freeze > requirements.txt Install from requirements: pip install -r requirements.txt