# Your first class Source: https://python.datalumina.com/advanced/classes/first-class Create a simple class ## How classes work Working with classes follows a simple pattern: 1. **Define the class** - Create a blueprint with the `class` keyword 2. **Add an `__init__` method** - Set up initial data when objects are created 3. **Create instances** - Make actual objects from your class 4. **Access the data** - Use the attributes you defined Let's go through each step to build your first class. ## Basic class structure Every class starts with the `class` keyword: ```python theme={null} class Dog: # Note: class names use PascalCase pass # Empty class ``` ## Adding an initializer The `__init__` method runs when you create a new object: ```python theme={null} class Dog: def __init__(self, name, breed): self.name = name self.breed = breed # Create dog objects - using positional arguments dog1 = Dog("Buddy", "Golden Retriever") dog2 = Dog("Max", "Beagle") # Or with named arguments (clearer) dog3 = Dog(name="Charlie", breed="Poodle") print(dog1.name) # Buddy print(dog2.breed) # Beagle ``` Yes, `__init__` looks weird with those double underscores! This is called a "dunder" method (double underscore). It's just how Python works - you'll need to type it exactly like this. Don't worry, after writing it a few times it becomes second nature. Think of it as Python's special way of saying "this is the setup method". ## Understanding self `self` refers to the current object. It's how an object keeps track of its own data: When defining methods in a class, you always include `self` as the first parameter. But when calling the method, you don't pass it - Python does that automatically! ```python theme={null} class Dog: def __init__(self, name): self.name = name # self.name belongs to this specific dog # Using positional argument dog1 = Dog("Buddy") # Using named argument (same result) dog2 = Dog(name="Max") # Each dog has its own name print(dog1.name) # Buddy print(dog2.name) # Max ``` ## Real-world example: configuration Here's a practical class for AI engineering: ```python theme={null} class APIConfig: def __init__(self, api_key, model="gpt-3.5-turbo", max_tokens=100): self.api_key = api_key self.model = model self.max_tokens = max_tokens self.base_url = "https://api.openai.com/v1" # Create different configurations # Using positional for required arg, named for optional dev_config = APIConfig("sk-dev-key", max_tokens=50) # Using all named arguments (clearest) prod_config = APIConfig(api_key="sk-prod-key", model="gpt-4", max_tokens=1000) # Access the configuration print(dev_config.model) # gpt-3.5-turbo print(prod_config.model) # gpt-4 print(prod_config.max_tokens) # 1000 ``` ## Class vs instance * **Class**: The blueprint (like a recipe) * **Instance/Object**: What you create from the class (like a cake from the recipe) ```python theme={null} # APIConfig is the class # config1 and config2 are instances config1 = APIConfig(api_key="key1", max_tokens=50) config2 = APIConfig(api_key="key2", max_tokens=200) # Each instance has its own data print(config1.max_tokens) # 50 print(config2.max_tokens) # 200 # Changing one doesn't affect the other config1.max_tokens = 75 print(config1.max_tokens) # 75 print(config2.max_tokens) # 200 (unchanged) ``` Always use clear, descriptive names for your classes. In Python, class names use PascalCase (like `TextProcessor` or `DataLoader`), while variable names use snake\_case (like `text_processor` or `data_loader`). ## Common mistakes ```python theme={null} # Wrong - forgot self parameter class Dog: def __init__(name): # Missing self! name = name # Right - include self class Dog: def __init__(self, name): self.name = name ``` ```python theme={null} # Wrong - creates local variable class Dog: def __init__(self, name): name = name # Just a local variable! # Right - use self class Dog: def __init__(self, name): self.name = name # Instance attribute ``` ```python theme={null} # Wrong - assigns the class itself my_config = APIConfig # Not an instance! # Right - call with parentheses my_config = APIConfig(api_key="api-key") # Creates instance ``` ```python theme={null} # Wrong - modifies the class class Counter: count = 0 c1 = Counter() c1.count += 1 # This affects the class! # Right - instance attribute class Counter: def __init__(self): self.count = 0 # Each instance gets its own ``` ## What's next? Now that you understand how to create classes and store data in them, let's learn how to add behavior with methods. Add behavior to your classes # Classes Source: https://python.datalumina.com/advanced/classes/index Create your own data types ## What is object-oriented programming? Object-oriented programming (OOP) is a way to organize code by grouping related data and functions together. Instead of having separate variables and functions scattered around, you bundle them into objects. Think of it like organizing a toolbox: * **Without OOP**: Tools scattered everywhere * **With OOP**: Tools organized in labeled compartments Classes are a more advanced Python concept. Don't worry if they feel confusing at first - they'll click with practice. Many Python programs work perfectly fine without classes, but they become valuable as your projects grow. ## What is a class? A class is a blueprint for creating objects. It defines: * **Attributes**: What data the object stores * **Methods**: What the object can do ```python theme={null} # Without classes - data and functions separate name = "OpenAI" model = "gpt-4o-mini" def generate_response(prompt): # Process prompt... return response # With classes - everything bundled together class OpenAIClient: def __init__(self, name, model): self.name = name self.model = model def generate_response(self, prompt): # Process prompt... return response ``` ## Why use classes? Classes help you write more understandable programs as they grow. Here's the typical progression of a Python developer: **1. Single file scripts** (where you started): ```python theme={null} # everything.py - All code in one file api_key = "sk-..." prompt = "Explain Python" response = make_api_call(api_key, prompt) print(response) ``` **2. Functions** (where you are now): ```python theme={null} # main.py - Organized with functions def setup_api(key): return {"key": key, "base_url": "https://api.openai.com"} def generate_response(api_config, prompt): # Make API call return response api = setup_api("sk-...") result = generate_response(api, "Explain Python") ``` **3. Multiple files** (getting organized): ```python theme={null} # api_utils.py def setup_api(key): return {"key": key, "base_url": "https://api.openai.com"} # main.py from api_utils import setup_api api = setup_api("sk-...") ``` **4. Classes** (where we are now): ```python theme={null} # client.py class OpenAIClient: def __init__(self, api_key): self.api_key = api_key self.base_url = "https://api.openai.com" def generate(self, prompt): # All logic encapsulated here return response # main.py from client import OpenAIClient client = OpenAIClient("sk-...") response = client.generate("Explain Python") ``` **In the context of AI**, classes specifically help you: * Build clean interfaces to APIs * Manage complex data pipelines * Create reusable components * Organize stateful operations Create a simple class Add functionality to classes Build on existing classes Best practices and guidelines # Inheritance Source: https://python.datalumina.com/advanced/classes/inheritance Build on existing classes ## Introduction Inheritance is an advanced Python concept that you probably won't use when starting out. Most beginner programs work perfectly fine without it. However, as your projects grow, inheritance can make your code much cleaner by avoiding repetition. Don't worry if inheritance feels complex at first. Focus on understanding basic classes, and come back to inheritance when you find yourself writing similar classes with shared functionality. ## What is inheritance? Inheritance lets you create new classes based on existing ones. The new class (child) gets everything from the parent class, plus can add its own stuff. Think of it like this: * All dogs are animals (dogs inherit from animals) * Dogs have everything animals have, plus dog-specific things ## Basic inheritance example ```python theme={null} # Parent class - general animal class Animal: def __init__(self, name): self.name = name def eat(self): return f"{self.name} is eating" def sleep(self): return f"{self.name} is sleeping" # Child class - specific animal class Dog(Animal): def bark(self): return f"{self.name} says woof!" # Create a dog - using positional argument my_dog = Dog("Buddy") # Or with named argument my_dog2 = Dog(name="Max") # Dog can do animal things (inherited) print(my_dog.eat()) # Buddy is eating print(my_dog.sleep()) # Buddy is sleeping # Dog can also do dog things print(my_dog.bark()) # Buddy says woof! ``` ## Adding attributes in child classes Child classes can have their own attributes too: ```python theme={null} class Animal: def __init__(self, name): self.name = name self.is_pet = True class Dog(Animal): def __init__(self, name, breed): super().__init__(name) # Pass name to parent's __init__ self.breed = breed # Dog-specific attribute def describe(self): return f"{self.name} is a {self.breed}" # Create dogs with breeds - positional arguments golden = Dog("Buddy", "Golden Retriever") # Or with named arguments (clearer) poodle = Dog(name="Max", breed="Poodle") print(golden.describe()) # Buddy is a Golden Retriever print(golden.is_pet) # True (inherited from Animal) ``` `super().__init__()` calls the parent class's `__init__` method. This ensures the parent class sets up its attributes properly before the child class adds its own. ## Overriding methods Child classes can change how parent methods work: ```python theme={null} class Animal: def __init__(self, name): self.name = name def make_sound(self): return f"{self.name} makes a sound" class Dog(Animal): def make_sound(self): # Override parent method return f"{self.name} barks: Woof!" class Cat(Animal): def make_sound(self): # Override parent method return f"{self.name} meows: Meow!" # Different animals, different sounds generic = Animal(name="Something") dog = Dog(name="Buddy") cat = Cat(name="Whiskers") print(generic.make_sound()) # Something makes a sound print(dog.make_sound()) # Buddy barks: Woof! print(cat.make_sound()) # Whiskers meows: Meow! ``` ## Real-world use case Here's a practical example for AI applications: ```python theme={null} class BaseModel: def __init__(self, model_name): self.model_name = model_name self.is_loaded = False def load(self): print(f"Loading {self.model_name}...") self.is_loaded = True class TextModel(BaseModel): def __init__(self, model_name, max_length=1000): super().__init__(model_name) self.max_length = max_length def process_text(self, text): if not self.is_loaded: self.load() # Truncate if needed if len(text) > self.max_length: text = text[:self.max_length] return f"Processed: {text}" # Use the model - with named arguments model = TextModel(model_name="gpt-3.5-turbo", max_length=100) # Call method - notice no 'self' parameter needed result = model.process_text(text="Hello world") print(result) # Loading gpt-3.5-turbo... # Processed: Hello world ``` ## When to use inheritance **Use inheritance when**: * You have an "is a" relationship (Dog is an Animal) * Child classes share most behavior with parent * You want to extend functionality, not replace it **Don't use inheritance when**: * Classes are only slightly related * You just want to reuse one or two methods * The relationship feels forced ## Common mistakes ```python theme={null} # Wrong - parent's __init__ not called class Child(Parent): def __init__(self, name): self.name = name # Parent attributes missing! # Right - call parent's __init__ class Child(Parent): def __init__(self, name): super().__init__() self.name = name ``` ```python theme={null} # Wrong - Rectangle is not a Square! class Square: def __init__(self, size): self.size = size class Rectangle(Square): # Doesn't make sense def __init__(self, width, height): self.width = width self.height = height # Better - they're both shapes class Shape: pass class Square(Shape): def __init__(self, size): self.size = size class Rectangle(Shape): def __init__(self, width, height): self.width = width self.height = height ``` ## What's next? Let's explore when to use classes and when to keep things simple. Best practices and guidelines # Methods and attributes Source: https://python.datalumina.com/advanced/classes/methods-attributes Add functionality to classes ## Attributes: storing data Attributes are variables that belong to an object. There are two types: **Instance attributes** (unique to each object): ```python theme={null} class APIClient: def __init__(self, api_key, base_url): self.api_key = api_key # Each client has its own key self.base_url = base_url # Each client has its own URL self.request_count = 0 # Track requests per client # Creating instances with named arguments client1 = APIClient(api_key="key1", base_url="https://api1.com") client2 = APIClient(api_key="key2", base_url="https://api2.com") ``` **Class attributes** (shared by all objects): ```python theme={null} class APIClient: version = "1.0" # Same for all clients max_retries = 3 # Same for all clients def __init__(self, api_key): self.api_key = api_key # Unique to each client ``` ## Methods: adding behavior Methods are functions that belong to a class. They always have `self` as the first parameter, but you don't pass it when calling: ```python theme={null} class DataValidator: def __init__(self): self.errors = [] def validate_email(self, email): if "@" not in email: self.errors.append(f"Invalid email: {email}") return False return True def validate_age(self, age): if age < 0 or age > 150: self.errors.append(f"Invalid age: {age}") return False return True def get_errors(self): return self.errors # Use the validator validator = DataValidator() # Notice: we don't pass self, just the email validator.validate_email(email="bad-email") validator.validate_age(age=200) # Or using positional arguments validator.validate_email("another-bad-email") validator.validate_age(150) print(validator.get_errors()) # ['Invalid email: bad-email', 'Invalid age: 200', 'Invalid email: another-bad-email'] ``` When you call a method like `validator.validate_email("test@example.com")`, Python automatically passes the validator object as `self`. You only provide the other arguments. ## Common mistakes ```python theme={null} # Wrong - shared list! class TodoList: items = [] # Class attribute list1 = TodoList() list1.items.append("Buy milk") list2 = TodoList() print(list2.items) # ['Buy milk'] - Oops! # Right - instance attribute class TodoList: def __init__(self): self.items = [] # Each instance gets its own ``` ```python theme={null} # Wrong - attribute might not exist class Counter: def increment(self): self.count += 1 # Error if count doesn't exist! # Right - initialize in __init__ class Counter: def __init__(self): self.count = 0 def increment(self): self.count += 1 ``` ## What's next? Let's explore inheritance - how classes can build on other classes. Build on existing classes # When to use classes Source: https://python.datalumina.com/advanced/classes/when-to-use Best practices and guidelines ## Programming paradigms Python supports multiple programming styles. The two main ones are: **Functional programming** - Using functions to transform data: ```python theme={null} # Functions operate on data def clean_text(text): return text.strip().lower() def remove_punctuation(text): return text.replace(".", "").replace(",", "") # Chain functions together result = remove_punctuation(clean_text(" Hello, World. ")) ``` **Object-oriented programming** - Using classes to bundle data and behavior: ```python theme={null} # Class bundles data and methods class TextProcessor: def __init__(self, text): self.text = text def clean(self): self.text = self.text.strip().lower() return self def remove_punctuation(self): self.text = self.text.replace(".", "").replace(",", "") return self # Chain methods on object processor = TextProcessor(text=" Hello, World. ") result = processor.clean().remove_punctuation().text ``` Both approaches achieve the same result! Classes don't unlock new features - they're just a different way to organize your code. Choose based on what makes your code clearer. ## When to use classes **Use classes when you need to:** * Keep track of state between operations * Group related data and functions together * Create multiple instances with similar behavior * Model real-world objects or concepts ## When to use functions **Use functions when you have:** * Simple transformations (input → output) * Stateless operations * One-off calculations * Small scripts Start with functions. They're simpler and often sufficient. Only add classes when you find yourself passing the same data between multiple functions or when you need to maintain state. ## Common pitfalls **Over-engineering**: Don't create classes for simple operations. A class with one method is usually better as a function. **God objects**: Classes that do too many things. Keep classes focused on a single responsibility. **Static method classes**: If all methods are static, you probably want a module with functions instead. ## What's next? Now that you understand classes, let's learn about version control with Git - essential for any developer. Track your code changes professionally # Common errors Source: https://python.datalumina.com/advanced/error-handling/common-errors Understand Python's error types ## Errors you'll encounter Here are the most common Python errors and how to fix them. Understanding these will save you hours of debugging. ## FileNotFoundError Happens when a file doesn't exist: ```python theme={null} # This fails if file doesn't exist with open('missing.txt', 'r') as f: content = f.read() ``` **Fix:** ```python theme={null} import os # Check first if os.path.exists('data.txt'): with open('data.txt', 'r') as f: content = f.read() else: print("File not found") # Or use try-except try: with open('data.txt', 'r') as f: content = f.read() except FileNotFoundError: content = "" # Default value ``` ## ValueError Happens when a value is wrong type or format: ```python theme={null} # These cause ValueError int("hello") # Can't convert to number int("12.5") # int() doesn't accept decimals list.remove("x") # Item not in list ``` **Fix:** ```python theme={null} # Validate user input try: age = int(input("Age: ")) except ValueError: print("Please enter a number") # Convert carefully float_str = "12.5" number = int(float(float_str)) # Convert to float first ``` ## KeyError Happens when a dictionary key doesn't exist: ```python theme={null} user = {"name": "Alice", "age": 25} print(user["email"]) # KeyError - no email key ``` **Fix:** ```python theme={null} # Check if key exists if "email" in user: print(user["email"]) # Use get() with default email = user.get("email", "no-email@example.com") # Or handle the error try: print(user["email"]) except KeyError: print("Email not found") ``` ## IndexError Happens when accessing invalid list position: ```python theme={null} numbers = [1, 2, 3] print(numbers[5]) # IndexError - only 3 items ``` **Fix:** ```python theme={null} # Check length first if len(numbers) > 5: print(numbers[5]) # Use negative indexing carefully last_item = numbers[-1] if numbers else None # Handle the error try: print(numbers[5]) except IndexError: print("List too short") ``` ## TypeError Happens when operations use wrong types: ```python theme={null} # These cause TypeError "hello" + 5 # Can't add string and number len(42) # Numbers don't have length int([1, 2, 3]) # Can't convert list to int ``` **Fix:** ```python theme={null} # Convert types explicitly "hello" + str(5) # "hello5" str(42) # "42" # Check type first if isinstance(value, str): print(len(value)) ``` ## AttributeError Happens when accessing non-existent attributes: ```python theme={null} text = "hello" text.append("!") # AttributeError - strings don't have append ``` **Fix:** ```python theme={null} # Use correct methods text = "hello" text = text + "!" # Strings are immutable # Check if attribute exists if hasattr(obj, 'append'): obj.append(item) ``` Error messages are your friends! They tell you: * What went wrong (error type) * Where it happened (file and line number) * Why it happened (error message) Always read the full error message before trying to fix it. ## Reading error messages Python error messages show a "traceback": ``` Traceback (most recent call last): File "script.py", line 5, in result = 10 / 0 ZeroDivisionError: division by zero ``` Read from bottom to top: 1. **Error type**: `ZeroDivisionError` 2. **Error message**: `division by zero` 3. **Location**: `script.py`, line 5 4. **Code that failed**: `result = 10 / 0` ## Common mistake patterns ```python theme={null} # Wrong - lists start at 0 items = ["a", "b", "c"] third_item = items[3] # IndexError # Right third_item = items[2] # "c" ``` ```python theme={null} # Wrong - changes list size during iteration numbers = [1, 2, 3, 4, 5] for num in numbers: if num % 2 == 0: numbers.remove(num) # Dangerous! # Right - create new list odd_numbers = [n for n in numbers if n % 2 != 0] ``` ```python theme={null} # Wrong - same list for all calls! def add_item(item, items=[]): items.append(item) return items # Right - create new list each time def add_item(item, items=None): if items is None: items = [] items.append(item) return items ``` ## What's next? Now that you understand error handling, let's learn about classes - Python's way of organizing code and data together. Object-oriented programming # Error handling Source: https://python.datalumina.com/advanced/error-handling/index Handle errors gracefully ## What is error handling? Errors happen. Files might not exist, APIs might be down, users might enter invalid data. Error handling lets your program deal with these problems gracefully instead of crashing. ## Where do errors come from? **Errors you make** as a programmer: * Typos and syntax mistakes (VS Code shows yellow squiggly lines) * Logic errors like dividing by zero (only show up when code runs) * Using variables before defining them * Calling methods that don't exist **Errors beyond your control**: * User enters "abc" when you need a number * File gets deleted after your program starts * Internet connection drops during API call * External service returns unexpected data You might think "why not just write correct code?" But even perfect code needs error handling because the world is unpredictable. Users do unexpected things, networks fail, and files disappear. ## Types of errors **Syntax errors** happen when Python can't understand your code: ```python theme={null} # Missing colon if x > 5 # SyntaxError print("Big number") ``` **Runtime errors** happen when your code runs: ```python theme={null} # Division by zero result = 10 / 0 # ZeroDivisionError # Variable doesn't exist print(score) # NameError # Wrong type "hello" + 5 # TypeError ``` ## Why handle errors? Here's a program that crashes: ```python theme={null} # This will crash if the file doesn't exist with open('data.txt', 'r') as f: content = f.read() print("Done!") # Never reaches here if file missing ``` Here's a program that handles the error: ```python theme={null} # This keeps running even if file doesn't exist try: with open('data.txt', 'r') as f: content = f.read() except FileNotFoundError: print("Could not find data.txt") content = "default data" print("Done!") # Always reaches here ``` Basic error handling syntax Errors you'll encounter often # Try and except Source: https://python.datalumina.com/advanced/error-handling/try-except Catch errors before they crash ## Basic try-except structure The `try` block contains code that might fail. The `except` block runs if an error happens: ```python theme={null} try: # Code that might cause an error risky_operation() except: # Code that runs if there's an error print("Something went wrong") ``` ## Catching specific errors Different errors need different handling. Catch specific error types: ```python theme={null} try: age = int(input("Enter your age: ")) print(f"In 10 years, you'll be {age + 10}") except ValueError: print("Please enter a number") ``` ## Multiple error types Handle different errors differently: ```python theme={null} try: # Read a number from a file with open('number.txt', 'r') as f: text = f.read() number = int(text) result = 100 / number print(f"Result: {result}") except FileNotFoundError: print("Could not find number.txt") except ValueError: print("File doesn't contain a valid number") except ZeroDivisionError: print("Cannot divide by zero") ``` ## The else clause Code in `else` runs only if no error happened: ```python theme={null} try: with open('data.txt', 'r') as f: data = f.read() except FileNotFoundError: print("File not found") else: # This only runs if the file was opened successfully print(f"File has {len(data)} characters") ``` ## The finally clause Code in `finally` always runs, error or not: ```python theme={null} try: file = open('data.txt', 'r') data = file.read() except FileNotFoundError: print("File not found") finally: # This always runs to clean up if 'file' in locals() and not file.closed: file.close() print("Cleanup complete") ``` Don't catch all errors with a bare `except:`. It hides problems and makes debugging harder. Always catch specific error types when possible. ## Common mistakes ```python theme={null} # Bad - catches everything try: process_data() except: pass # Silent failure! # Good - specific error try: process_data() except ValueError: print("Invalid data format") ``` ```python theme={null} # Bad - ignores the error try: risky_operation() except ValueError: pass # Good - at least log it try: risky_operation() except ValueError: print("Warning: Invalid value encountered") ``` ```python theme={null} # Bad - hides all errors try: critical_operation() except Exception as e: print(f"Error: {e}") # Good - log and re-raise try: critical_operation() except Exception as e: print(f"Critical error: {e}") raise # Let the error propagate ``` ## What's next? Now let's look at the most common errors you'll encounter in Python. Errors you'll see often # Comments Source: https://python.datalumina.com/basics/comments Document your code for humans ## What are comments? Comments are notes for humans that Python ignores. They're like sticky notes in your code that explain what's happening. Why write comments? * Help others understand your code * Help future you remember what you did * Disable code temporarily * Document complex logic ## Single-line comments Use `#` to start a comment: ```python theme={null} # This is a comment print("Hello") # This is also a comment # You can have multiple lines # of comments by starting # each line with a hash age = 25 # Store user's age ``` ## Multi-line comments For longer explanations, use triple quotes: ```python theme={null} """ This is a multi-line comment. It can span several lines. Great for longer explanations. """ def calculate_tip(bill): """ Calculate 20% tip for a restaurant bill. Takes the bill amount and returns the tip. """ return bill * 0.20 ``` Technically, triple quotes create a string that Python doesn't use. Real multi-line comments don't exist in Python, but this works the same way! ## When to use comments **Good comments explain WHY, not WHAT:** ```python theme={null} # Good: Explains why # Using 1.0625 because sales tax in CA is 6.25% total = subtotal * 1.0625 # Bad: States the obvious # Multiply subtotal by 1.0625 total = subtotal * 1.0625 ``` ## Best practices Use descriptive variable names instead of comments when possible. `days_in_week = 7` is clearer than `d = 7 # days`. ## Temporary comments Use comments to disable code temporarily: ```python theme={null} print("Starting process...") # print("Debug info") # Uncomment for debugging new_method() # old_method() # Keeping for reference ``` ## Common mistakes ```python theme={null} # Bad: Says 15% but does 20% # Calculate 15% tip tip = bill * 0.20 # Good: Accurate # Calculate 20% tip (standard) tip = bill * 0.20 ``` ```python theme={null} # Bad: Too obvious x = 5 # Set x to 5 y = 10 # Set y to 10 # Good: Only explain complex parts x = 5 y = 10 position = x + y # Convert to linear index ``` ## What's next? Now that you know the basics and how to document your code, let's explore the different types of data Python can work with! Numbers, text, and more # Code formatting Source: https://python.datalumina.com/basics/formatting Keep your code clean and readable ## What is code formatting? Writing clean, consistent code is important. Code formatting means organizing your code so it's easy to read and follows Python's style guidelines. ## Basic formatting principles Follow these basic rules for readability: ### Indentation Use 4 spaces for indentation (not tabs): ```python theme={null} def greet(name): if name: print(f"Hello, {name}!") else: print("Hello!") ``` ### Spacing Add spaces around operators and after commas: ```python theme={null} # Good x = 1 + 2 numbers = [1, 2, 3, 4] # Bad x=1+2 numbers=[1,2,3,4] ``` ### Blank lines Use blank lines to separate functions and logical sections: ```python theme={null} def first_function(): pass def second_function(): pass ``` ### Line length Keep lines under 80-100 characters. Break long lines for readability: ```python theme={null} # Good - readable long_string = ( "This is a very long string that " "spans multiple lines for readability" ) # Bad - too long long_string = "This is a very long string that spans multiple lines for readability but keeps going and going" ``` Later in the course, you'll learn about Ruff - a tool that automatically formats your code. But understanding these basics first helps you write better code naturally. ## Automatic formatting with Ruff Want to format your code automatically? Check out the Ruff guide in the tools section: Automatically format and lint your code ## What's next? Now that you understand formatting, let's learn about variables! Learn how to store and use data in Python # Python basics Source: https://python.datalumina.com/basics/index Master the building blocks of Python ## Your Python foundation Welcome to Python Basics! This is where you'll learn the fundamental building blocks that every Python program uses. Think of it like learning a new language: * First, you learn words (variables and data types) * Then, you learn how to make sentences (operators and expressions) * Finally, you learn grammar rules (control flow) ## What you'll learn Store and manage data in your programs Numbers, text, and true/false values Math and comparisons in Python Manipulate and format strings Document your code ## How to use this section Each topic builds on the previous one, so I recommend going in order. Every page follows the same format: 1. **What is it?** - Simple explanation of the concept 2. **See it in action** - Live examples you can try 3. **Try it yourself** - Exercises to practice 4. **Common mistakes** - Things to watch out for Use Interactive Python mode (Shift + Enter) to try examples as you go. This makes learning much more fun and effective! ## Ready? Let's start by understanding what programming really is, then dive into Python specifics. Understand the basics before diving into Python # Intro to programming Source: https://python.datalumina.com/basics/intro-to-programming What programming really means ## What is programming? Programming is simply giving instructions to a computer. Think of it like writing a recipe - you tell the computer exactly what to do, step by step. When you cook, you follow steps: "Heat oil, add onions, stir for 2 minutes." Programming is the same, except you're telling a computer what to do instead of cooking. ## Computers are literal Here's the key thing: computers do exactly what you tell them - nothing more, nothing less. They can't guess what you mean. If you tell a friend "make coffee," they know what to do. But a computer needs every detail: 1. Get a cup 2. Add coffee grounds 3. Pour hot water 4. Wait 3 minutes 5. Add milk if desired ## Basic programming operations All programming, regardless of language, boils down to a few basic operations: **Store information** ``` age = 25 name = "Sarah" ``` **Make decisions** ``` if it's raining: take umbrella else: wear sunglasses ``` **Repeat actions** ``` repeat 10 times: do pushup ``` **Calculate things** ``` total = price + tax ``` ## Your journey Right now, this might feel abstract. That's normal! As we move through Python basics, each concept will click into place. Programming is a skill like any other - it takes practice, but anyone can learn it. ## What's next? Now let's dive into Python syntax - the specific rules for writing Python programs. Learn Python's rules # Loops Source: https://python.datalumina.com/basics/loops Repeat code multiple times ## What are loops? Loops let you repeat code without writing it multiple times. Instead of copying and pasting, you tell Python to repeat the code for you. Without loops: ```python theme={null} print("Hello!") print("Hello!") print("Hello!") print("Hello!") print("Hello!") ``` With loops: ```python theme={null} for i in range(5): print("Hello!") ``` Both do the same thing, but the loop is much cleaner! ## For loops The `for` loop is the most common loop in Python. Let's start simple: ### Repeat a specific number of times ```python theme={null} # Print numbers 0 through 4 for i in range(5): print(i) # Output: # 0 # 1 # 2 # 3 # 4 ``` Python starts counting at 0, not 1. This is called "zero-indexing". So `range(5)` gives you 0, 1, 2, 3, 4 (five numbers total). ### Count from different starting points ```python theme={null} # Count from 1 to 5 for i in range(1, 6): print(i) # Output: 1, 2, 3, 4, 5 # Count by 2s for i in range(0, 10, 2): print(i) # Output: 0, 2, 4, 6, 8 ``` ### Loop through text You can loop through each character in a string: ```python theme={null} name = "Python" for letter in name: print(letter) # Output: # P # y # t # h # o # n ``` ### Loop through a list (preview) We'll learn more about lists later, but here's a preview: ```python theme={null} colors = ["red", "blue", "green"] for color in colors: print(f"I like {color}") # Output: # I like red # I like blue # I like green ``` ## While loops A `while` loop continues as long as a condition is true: ```python theme={null} count = 0 while count < 5: print(f"Count is {count}") count = count + 1 # Increase count by 1 # Output: # Count is 0 # Count is 1 # Count is 2 # Count is 3 # Count is 4 ``` Always make sure your while loop will eventually stop! If you forget to update the variable, it will run forever. ## Common mistakes ```python theme={null} # Wrong - missing colon for i in range(5) print(i) # Right - colon after the loop line for i in range(5): print(i) ``` ```python theme={null} # Wrong - not indented for i in range(3): print(i) # Right - indented inside the loop for i in range(3): print(i) ``` ```python theme={null} # Wrong - only goes to 4 for i in range(5): print(f"Item {i}") # 0, 1, 2, 3, 4 # Right - if you want 1-5 for i in range(1, 6): print(f"Item {i}") # 1, 2, 3, 4, 5 ``` Learn about lists, dictionaries, and more # Operators Source: https://python.datalumina.com/basics/operators Math, comparisons, and logic in Python ## What are operators? Operators are symbols that perform operations on values. Think of them as the "verbs" of programming - they make things happen! You already know most operators from math class: * Calculate: `+`, `-`, `*`, `/` * Compare: `>`, `<`, `==` * Combine: `and`, `or`, `not` ## Arithmetic operators These work just like your calculator: ```python theme={null} # Basic math print(10 + 3) # 13 - Addition print(10 - 3) # 7 - Subtraction print(10 * 3) # 30 - Multiplication print(10 / 3) # 3.333... - Division (always gives float) # Special operators print(10 // 3) # 3 - Floor division (rounds down) print(10 % 3) # 1 - Modulo (remainder) print(10 ** 3) # 1000 - Exponent (power) ``` ### Order of operations Python follows math rules (PEMDAS): ```python theme={null} result = 2 + 3 * 4 # 14 (not 20!) result = (2 + 3) * 4 # 20 (parentheses first) ``` ## Comparison operators These compare values and return True or False: ```python theme={null} age = 18 print(age == 18) # True - Equal to print(age != 21) # True - Not equal to print(age > 17) # True - Greater than print(age < 20) # True - Less than print(age >= 18) # True - Greater than or equal print(age <= 18) # True - Less than or equal ``` Don't confuse `=` (assignment) with `==` (comparison)! * `age = 18` stores 18 in age * `age == 18` checks if age equals 18 ## Logical operators These combine boolean values and conditions: ```python theme={null} age = 25 has_license = True # AND - both must be true can_drive = age >= 16 and has_license print(can_drive) # True # OR - at least one must be true day = "Saturday" is_weekend = day == "Saturday" or day == "Sunday" print(is_weekend) # True # NOT - reverses the value is_adult = age >= 18 is_child = not is_adult print(is_child) # False ``` ### Truth tables Understanding how `and`, `or`, and `not` work: ```python theme={null} # AND: Both must be True print(True and True) # True print(True and False) # False print(False and False) # False # OR: At least one must be True print(True or False) # True print(False or False) # False # NOT: Flips the value print(not True) # False print(not False) # True ``` ## Assignment shortcuts These shortcuts update variables in place: ```python theme={null} # Instead of: score = score + 10 # Write: score += 10 # Works with all operators x = 10 x += 5 # x is now 15 x *= 2 # x is now 30 ``` ## Common mistakes ```python theme={null} # Regular division result = 10 / 2 # 5.0 (not 5) # Integer division result = 10 // 2 # 5 ``` ```python theme={null} # Wrong average = 10 + 20 + 30 / 3 # 40.0 # Right average = (10 + 20 + 30) / 3 # 20.0 ``` ```python theme={null} # = assigns a value age = 18 # == compares values if age == 18: print("Just turned adult!") ``` ## What's next? You know operators! Let's dive deeper into working with text strings. Advanced text operations # Python errors Source: https://python.datalumina.com/basics/python-errors Understanding when code doesn't run ## What happens when code breaks? You've learned Python syntax rules. But what happens when you break them? Your code won't run, and Python will show you an error message. This might feel frustrating at first, but errors are actually helpful - they tell you exactly what went wrong and where. ## Your first error Let's create an error on purpose. Try running this code: ```python theme={null} print("Hello World) ``` When you run this, Python shows: ``` File "hello.py", line 1 print("Hello World) ^ SyntaxError: unterminated string literal (detected at line 1) ``` Don't panic! This is Python trying to help you. ## How to read errors Python errors have three parts: 1. **Where it happened**: `File "hello.py", line 1` 2. **What went wrong**: `SyntaxError: unterminated string literal` 3. **The arrow**: Points to the exact spot In our example, we forgot the closing quote mark. Python noticed and told us exactly where. ## Errors are normal Every programmer sees errors daily. The difference between beginners and experts? Experts have seen more errors and learned from them. Reading errors gets easier with practice. At first they look scary, but soon you'll read them like road signs. ## AI helps with errors When you're stuck on an error: 1. Copy the entire error message 2. Paste it into Claude, ChatGPT, or your favorite AI tool 3. Add your code for context AI tools are excellent at explaining errors and suggesting fixes. They've seen millions of errors and can quickly spot what's wrong. Don't feel bad about using AI for errors! Even experienced developers use AI to debug tricky problems. It's a tool, just like Python itself. ## What's next? Now that you understand syntax and errors, let's start writing real Python code with variables! Store and use data in Python # Python syntax Source: https://python.datalumina.com/basics/python-syntax How to write Python code properly ## What is syntax? Every programming language has its own rules - its syntax. It's like grammar in human languages. You can't just write words in any order and expect people to understand. The same goes for programming. Python's syntax is known for being clean and readable. But it still has rules you must follow, or your code won't run. ## The importance of syntax Think about these two sentences: * "The cat sat on the mat" ✓ (correct English) * "Cat the on mat sat the" ✗ (same words, wrong order) Programming is the same: ```python theme={null} # Correct Python if age > 18: print("Adult") # Wrong - Python won't understand age > 18 print("Adult") ``` ## Python's unique feature: Indentation Most languages use `{}` brackets. Python uses indentation (spaces): ```python theme={null} # Python - clean and readable if temperature > 30: print("It's hot!") print("Turn on AC") # Other languages (like JavaScript) if (temperature > 30) { console.log("It's hot!"); console.log("Turn on AC"); } ``` ### Indentation rules ```python theme={null} # CORRECT - consistent 4 spaces if score > 90: print("A grade") if score == 100: print("Perfect!") # WRONG - mixing spaces if score > 90: print("A grade") # 2 spaces if score == 100: # 4 spaces print("Perfect!") # 6 spaces ``` Python won't run if your indentation is wrong. This is the #1 beginner mistake! ## Python style guide (PEP8) Beyond just syntax rules that make code run, Python has style guidelines that make code readable. These are called PEP8 (Python Enhancement Proposal 8) - the official style guide for Python code. PEP8 covers things like: * Using 4 spaces for indentation (not tabs) * Limiting lines to 79 characters * Naming conventions (like `user_name` instead of `userName`) * Where to put spaces around operators Throughout this course, when there are multiple ways to write something, we'll follow PEP8. This means you don't have to think about style choices - just follow the standard and your code will be readable by other Python developers. Following PEP8 isn't required for code to run, but it makes your code look professional and easier for others to read. You can read the full PEP8 guide at [https://peps.python.org/pep-0008/](https://peps.python.org/pep-0008/). ## That's all for now Syntax is just how you write Python code - the rules you follow. Right now, remember these basics: Python cares about spelling, order, and especially indentation. As we move through the course, you'll naturally pick up the specific syntax rules for each concept. ## What's next? Now that you understand Python's rules, let's see what happens when we break them! Understanding when code doesn't run # String manipulation Source: https://python.datalumina.com/basics/string-manipulation Advanced text operations ## Working with text Now that you know what strings are, let's learn how to manipulate them. Python gives you powerful tools to work with text. ## String operations ### Concatenation (joining) ```python theme={null} first_name = "Jane" last_name = "Doe" # Using + full_name = first_name + " " + last_name # "Jane Doe" # Using f-strings (modern Python way!) greeting = f"Hello, {first_name}!" # "Hello, Jane!" # Multiple variables age = 25 intro = f"I'm {first_name} and I'm {age} years old" ``` ### Repetition ```python theme={null} star = "*" stars = star * 10 # "**********" separator = "-" * 20 # "--------------------" ``` ## String methods Python strings come with many built-in methods - functions you can call directly on any string. These methods let you transform text, search for patterns, and clean up data. The best part? You can often guess what they do from their names - `upper()` makes text uppercase, `replace()` replaces text, and so on. ### Changing case ```python theme={null} text = "Python Programming" print(text.lower()) # "python programming" print(text.upper()) # "PYTHON PROGRAMMING" print(text.title()) # "Python Programming" ``` ### Cleaning strings ```python theme={null} messy = " hello world " print(messy.strip()) # "hello world" (removes whitespace) price = "$19.99" print(price.strip("$")) # "19.99" ``` ### Finding and replacing ```python theme={null} message = "I love Python programming with Python" # Check if something exists print("Python" in message) # True print(message.startswith("I")) # True print(message.endswith("Python")) # True # Find position print(message.find("Python")) # 7 (first occurrence) print(message.count("Python")) # 2 (number of times) # Replace new_message = message.replace("Python", "JavaScript") print(new_message) # "I love JavaScript programming with JavaScript" ``` Python has over 40 string methods! We've covered the most common ones here. For a complete list, check the [official Python documentation](https://docs.python.org/3/library/stdtypes.html#string-methods). ## Common mistakes ```python theme={null} # Wrong name = "Alice" message = "Hello {name}" # Prints: "Hello {name}" # Right message = f"Hello {name}" # Prints: "Hello Alice" ``` ```python theme={null} # Wrong - mismatched quotes text = 'It's Python' # Right - escape or use different quotes text = "It's Python" # Double quotes outside text = 'It\'s Python' # Escape the apostrophe ``` ## What's next? You've mastered working with data! Ready to make your programs smart with decision-making? Learn if statements and loops # Variables Source: https://python.datalumina.com/basics/variables Learn to store and name your data ## What are variables? A variable is like a labeled box where you can store information. You give it a name and put a value inside. Later, you can use that name to get the value back. In real life: * Your name is a "variable" that stores what people call you * Your age is a "variable" that stores a number * Your favorite color is a "variable" that stores text In Python, we create variables to store data our programs need to remember. ## Creating your first variable Here's how to create a variable: ```python theme={null} name = "Alice" age = 25 is_student = True ``` Let's break this down: * `name` is the variable name * `=` means "store the value on the right in the variable on the left" * `"Alice"` is the value we're storing ## Naming rules Python has rules for variable names: **Allowed:** ```python theme={null} user_name = "Dave" # lowercase with underscores (Python style) userName = "Dave" # camelCase (works but not Python style) age2 = 30 # numbers are OK (not at start) _private = "secret" # underscore at start is OK ``` **Not allowed:** ```python theme={null} 2age = 30 # Can't start with number my-name = "Dave" # No hyphens (Python thinks it's subtraction) my name = "Dave" # No spaces class = "Python" # Can't use Python keywords ``` ### Python naming convention In Python, we use lowercase letters with underscores between words. This is called "snake\_case" and it's the standard way to name variables in Python. ```python theme={null} # Good Python style first_name = "Alice" user_age = 25 is_logged_in = True shopping_cart_total = 49.99 # Avoid camelCase (this is for other languages) firstName = "Alice" # Works, but not Python style userAge = 25 isLoggedIn = True ``` Use descriptive names for your variables! Instead of `x` or `temp`, use names like `user_score` or `file_path`. Your future self (and teammates) will thank you when reading the code later. ## Changing variables Variables can change (that's why they're called variables!): ```python theme={null} # Start with one value score = 0 print(score) # Shows: 0 # Change it score = 10 print(score) # Shows: 10 # Change it again score = score + 5 print(score) # Shows: 15 ``` ## Common mistakes ```python theme={null} # Wrong name = Alice # Python looks for a variable called Alice # Right name = "Alice" # This creates text ``` ```python theme={null} # Wrong print(score) # Error: score doesn't exist yet score = 10 # Right score = 10 print(score) # Now it works ``` ```python theme={null} # = means "store" age = 25 # == means "compare" (we'll learn this later) if age == 25: print("Quarter century!") ``` ## What's next? Before we explore data types, let's learn about comments - a crucial tool for making your code readable. Document your code clearly # If statements Source: https://python.datalumina.com/control-flow/if-statements Make decisions in your code ## What are if statements? If statements let your program make decisions. They check if something is true or false, then act accordingly. Real-life logic: * IF it's raining THEN take umbrella * IF battery \< 20% THEN charge phone * IF password correct THEN allow access ## Basic if statement ```python theme={null} age = 18 if age >= 18: print("You can vote!") print("You're an adult") ``` How it works: 1. Check the condition (`age >= 18`) 2. If True, run the indented code 3. If False, skip it The colon `:` and indentation are required! This is how Python knows what code belongs to the if statement. ## If-else statements Handle both True and False cases: ```python theme={null} temperature = 25 if temperature > 30: print("It's hot!") else: print("Nice weather!") ``` ## If-elif-else chains For multiple conditions: ```python theme={null} score = 85 if score >= 90: print("A - Excellent!") elif score >= 80: print("B - Good job!") elif score >= 70: print("C - Keep it up!") else: print("F - Need improvement") ``` Python checks each condition in order and runs the first True one. Why `elif` instead of multiple `if` statements? With `elif`, Python stops checking once it finds a true condition. This is more efficient and prevents multiple blocks from running. The order matters - always put more specific conditions first! ## Multiple conditions Combine conditions with `and`, `or`, `not`: ```python theme={null} age = 25 has_license = True # Both must be True if age >= 18 and has_license: print("You can drive!") # At least one must be True if weekend or holiday: print("No work today!") # Reverse the condition if not raining: print("Let's go outside!") ``` ## Nested if statements Put if statements inside other if statements: ```python theme={null} has_ticket = True age = 15 if has_ticket: if age >= 18: print("Enjoy the movie!") else: print("Need adult supervision") else: print("Buy a ticket first") ``` ## Common mistakes ```python theme={null} # Wrong if x > 5 print("Big") # Right if x > 5: print("Big") ``` ```python theme={null} # Wrong (assignment) if x = 5: print("Five") # Right (comparison) if x == 5: print("Five") ``` ```python theme={null} # Wrong if True: print("Hello") # IndentationError # Right if True: print("Hello") ``` ## What's next? Now let's learn about loops to repeat code efficiently! Repeat code without copying # Control flow Source: https://python.datalumina.com/control-flow/index Make your programs smart with decisions ## Making programs think So far, your programs run top to bottom, executing every line. But real programs need to make decisions - "if this, then that". Control flow is what makes programs intelligent! ## What you'll learn Make decisions based on conditions ## Real-world examples Decision-making is everywhere: * **ATM**: IF password correct, THEN allow access * **Apps**: IF user clicks button, THEN perform action * **Weather app**: IF temperature \< 0, THEN show snow icon * **Games**: IF health = 0, THEN game over ## Prerequisites Before starting this section, make sure you understand: * Variables and data types * Operators (especially comparison operators) * Boolean values (True/False) Control flow is where programming gets fun! You'll start building programs that can actually make decisions and respond to different situations. ## Let's begin! Start with the foundation of all program logic: if statements. Learn to make decisions in code # Dictionaries Source: https://python.datalumina.com/data-structures/dictionaries Store data with key-value pairs ## What are dictionaries? Dictionaries store data in key-value pairs. Think of them like a real dictionary where you look up a word (key) to find its definition (value). Real-world examples: * Phone book: name > phone number * Menu: dish > price * User profile: username > user info ## Creating dictionaries ```python theme={null} # Empty dictionary my_dict = {} # Dictionary with data person = { "name": "Alice", "age": 30, "city": "New York" } # Different ways to create scores = dict(math=95, english=87, science=92) ``` Dictionaries use curly braces `{}` with key-value pairs separated by colons. Keys must be unique! ## Accessing values ```python theme={null} person = {"name": "Alice", "age": 30, "city": "New York"} # Get values by key print(person["name"]) # "Alice" print(person["age"]) # 30 # Safer with get() print(person.get("job")) # None (no error) print(person.get("job", "Unknown")) # "Unknown" (default) ``` ## Changing dictionaries ```python theme={null} person = {"name": "Alice", "age": 30} # Add or update person["email"] = "alice@email.com" # Add new person["age"] = 31 # Update existing # Remove items del person["email"] # Remove by key age = person.pop("age") # Remove and return person.clear() # Remove all items ``` ## Dictionary methods ```python theme={null} person = {"name": "Alice", "age": 30, "city": "New York"} # Get all keys, values, or items print(person.keys()) # dict_keys(['name', 'age', 'city']) print(person.values()) # dict_values(['Alice', 30, 'New York']) print(person.items()) # dict_items([('name', 'Alice'), ...]) # Check if key exists if "name" in person: print("Name found!") # Update multiple values person.update({"age": 31, "job": "Engineer"}) ``` ### Nested dictionaries ```python theme={null} # Dictionary of dictionaries students = { "alice": {"age": 20, "grade": "A"}, "bob": {"age": 21, "grade": "B"}, "charlie": {"age": 19, "grade": "A"} } # Access nested data print(students["alice"]["grade"]) # "A" ``` ## Common mistakes ```python theme={null} # Wrong person = {"name": "Alice"} print(person["age"]) # KeyError! # Right - use get() print(person.get("age", 0)) # Returns 0 if missing ``` ```python theme={null} # Wrong - lists can't be keys bad_dict = {[1, 2]: "value"} # TypeError! # Right - use immutable types good_dict = {(1, 2): "value"} # Tuple is OK good_dict = {"1,2": "value"} # String is OK ``` ## What's next? Let's explore tuples - like lists but unchangeable! Immutable sequences # Data structures Source: https://python.datalumina.com/data-structures/index Store multiple values together ## Beyond single values So far, you've stored one value per variable. But what if you need to store multiple values? That's where data structures come in. Think of data structures as containers: * **Lists**: Like a shopping list (ordered items) * **Dictionaries**: Like a phone book (name > number) * **Tuples**: Like coordinates (fixed values) * **Sets**: Like a bag of unique items ## The main structures Ordered, changeable collections Key-value pairs for fast lookup Ordered, unchangeable collections Unique values only ## Which one to use? * **Lists**: When order matters and you need to change items * **Dictionaries**: When you need to look up values by name * **Tuples**: When data shouldn't change (like coordinates) * **Sets**: When you only care about unique values Python counts from 0, not 1! The first item in any collection is at position 0, the second at position 1, and so on. This is called "zero-based indexing" and you'll see it throughout Python. ## Start learning Lists are the most common data structure - let's start there! Your first data structure # Lists Source: https://python.datalumina.com/data-structures/lists Work with ordered collections ## What are lists? Lists are Python's most versatile data structure. They're like containers that can hold multiple items in a specific order. Think of a list like: * A shopping list (milk, eggs, bread) * A to-do list (tasks in order) * A playlist (songs in sequence) ## Creating lists ```python theme={null} # Empty list my_list = [] # List with items fruits = ["apple", "banana", "orange"] numbers = [1, 2, 3, 4, 5] mixed = ["hello", 42, True, 3.14] # Different types OK! ``` Lists use square brackets `[]` and items are separated by commas. You can mix different data types in the same list! ## Accessing items Lists are indexed starting at 0: ```python theme={null} fruits = ["apple", "banana", "orange"] # Get items print(fruits[0]) # "apple" (first item) print(fruits[1]) # "banana" print(fruits[-1]) # "orange" (last item) print(fruits[-2]) # "banana" (second to last) # Slicing print(fruits[0:2]) # ["apple", "banana"] print(fruits[1:]) # ["banana", "orange"] ``` ## Changing lists Lists are mutable - you can change them: ```python theme={null} fruits = ["apple", "banana", "orange"] # Change an item fruits[0] = "mango" print(fruits) # ["mango", "banana", "orange"] # Add items fruits.append("grape") # Add to end fruits.insert(1, "kiwi") # Insert at position # Remove items fruits.remove("banana") # Remove by value last = fruits.pop() # Remove and return last del fruits[0] # Remove by index ``` ## List methods ```python theme={null} numbers = [3, 1, 4, 1, 5, 9] # Information print(len(numbers)) # 6 (length) print(numbers.count(1)) # 2 (count occurrences) print(numbers.index(4)) # 2 (find position) # Sorting numbers.sort() # Sort in place print(numbers) # [1, 1, 3, 4, 5, 9] numbers.reverse() # Reverse order print(numbers) # [9, 5, 4, 3, 1, 1] # Copy new_list = numbers.copy() # Create a copy ``` ## Checking lists ```python theme={null} fruits = ["apple", "banana", "orange"] # Check if item exists if "apple" in fruits: print("Found apple!") # Check if list is empty if fruits: print("List has items") else: print("List is empty") ``` ## Common mistakes ```python theme={null} # Wrong fruits = ["apple", "banana"] print(fruits[2]) # IndexError! # Right - check length first if len(fruits) > 2: print(fruits[2]) ``` ```python theme={null} # Wrong - changes list size during loop numbers = [1, 2, 3, 4] for num in numbers: if num == 2: numbers.remove(num) # Dangerous! # Right - use list comprehension numbers = [num for num in numbers if num != 2] ``` ```python theme={null} # Wrong - both variables point to same list list1 = [1, 2, 3] list2 = list1 list2.append(4) print(list1) # [1, 2, 3, 4] - changed! # Right - make a copy list1 = [1, 2, 3] list2 = list1.copy() list2.append(4) print(list1) # [1, 2, 3] - unchanged ``` ## What's next? Now let's learn about dictionaries - perfect for storing related information! Key-value pairs # Sets Source: https://python.datalumina.com/data-structures/sets Work with unique collections ## What are sets? Sets are collections that only store unique values. They automatically remove duplicates. Think of sets like: * A bag of unique marbles * Guest list (each person once) * Unique tags or categories ## Creating sets You can create sets two ways: with `set()` or with curly braces `{}` (but only when it has values). ```python theme={null} # Empty set (careful!) empty_set = set() # NOT {} - that's a dict! # Set with values - both ways work numbers = {1, 2, 3, 4, 5} fruits = set(["apple", "banana", "orange"]) # From a list (removes duplicates) scores = [85, 90, 85, 92, 90] unique_scores = set(scores) # {85, 90, 92} ``` Use `set()` for empty sets, not `{}`. Empty curly braces create a dictionary! ## Basic operations ```python theme={null} colors = {"red", "blue"} # Add items colors.add("green") print(colors) # {'red', 'blue', 'green'} # Remove items colors.remove("blue") # Error if not found colors.discard("yellow") # No error if not found # Check membership if "red" in colors: print("Red is available") ``` ## Common uses ### Remove duplicates ```python theme={null} names = ["Alice", "Bob", "Alice", "Charlie", "Bob"] unique_names = list(set(names)) print(unique_names) # ['Alice', 'Bob', 'Charlie'] ``` ### Fast membership testing ```python theme={null} allowed_users = {"alice", "bob", "charlie"} if "alice" in allowed_users: # Very fast! print("Access granted") ``` ## Common mistakes ```python theme={null} # Wrong - creates empty dict empty = {} # Right - use set() empty = set() ``` ```python theme={null} # Order is not guaranteed! numbers = {3, 1, 4, 1, 5} print(numbers) # Could be any order # Use list if order matters ordered = [3, 1, 4, 1, 5] ``` ## What's next? Congratulations! You've completed Python Basics. Ready to start building programs? Learn about functions # Tuples Source: https://python.datalumina.com/data-structures/tuples Work with immutable sequences ## What are tuples? Tuples are like lists, but they can't be changed once created. They're immutable (unchangeable) sequences. Use tuples for data that shouldn't change: * Coordinates (x, y) * RGB colors (255, 0, 0) * Database records * Function return values ## Creating tuples ```python theme={null} # Empty tuple empty = () # Tuple with items point = (3, 5) colors = ("red", "green", "blue") # Single item tuple needs comma! single = (42,) # Note the comma not_tuple = (42) # This is just 42 in parentheses # Without parentheses (implicit) coordinates = 10, 20 ``` A single-item tuple needs a comma: `(42,)` not `(42)`. Without the comma, Python thinks it's just parentheses around a number! ## Accessing items Just like lists, tuples use indexing: ```python theme={null} point = (3, 5) colors = ("red", "green", "blue") # Get items print(point[0]) # 3 print(colors[-1]) # "blue" # Slicing works too print(colors[0:2]) # ("red", "green") ``` ## Tuple unpacking Python's coolest tuple feature: ```python theme={null} # Unpack values point = (3, 5) x, y = point # x = 3, y = 5 # Multiple assignment a, b, c = 1, 2, 3 # Same as (1, 2, 3) # Swap variables elegantly x, y = y, x # Swaps values! ``` ## Common mistakes ```python theme={null} # Wrong - not a tuple single = (42) print(type(single)) # # Right - include comma single = (42,) print(type(single)) # ``` ```python theme={null} # Wrong - tuples are immutable point = (3, 5) point[0] = 4 # TypeError! # Right - create a new tuple point = (4, point[1]) # Or convert to list, modify, convert back temp = list(point) temp[0] = 4 point = tuple(temp) ``` ## What's next? Finally, let's explore sets - collections of unique items! Unique collections # Booleans Source: https://python.datalumina.com/data-types/booleans True and False values for decisions ## What are booleans? Booleans are the simplest data type - they can only be `True` or `False`. Think of them as yes/no answers. ```python theme={null} is_logged_in = True is_admin = False has_permission = True ``` Boolean values are `True` and `False` with capital letters. Using `true` or `false` will cause an error! ## Creating booleans Booleans often come from comparisons: ```python theme={null} # Direct assignment is_ready = True # From comparisons age = 18 can_vote = age >= 18 # True score = 75 passed = score > 60 # True ``` ## Comparison operators These operators compare values and return `True` or `False`: ```python theme={null} age = 25 # Equality print(age == 25) # True - equals print(age != 30) # True - not equals # Greater/Less than print(age > 20) # True - greater than print(age < 30) # True - less than print(age >= 25) # True - greater or equal print(age <= 25) # True - less or equal ``` Remember: `=` assigns a value, while `==` compares values. This is a common source of bugs! ## Common mistakes ```python theme={null} # Wrong is_ready = true # NameError! is_done = TRUE # NameError! # Right is_ready = True is_done = False ``` ```python theme={null} # Wrong - this assigns, not compares! if is_logged_in = True: print("Welcome") # Right - but redundant if is_logged_in == True: print("Welcome") # Best - booleans are already True/False if is_logged_in: print("Welcome") ``` ## What's next? Now that you understand data types, let's learn how to work with them using operators! Math, comparisons, and more # Data types Source: https://python.datalumina.com/data-types/index Different kinds of information in Python ## What are data types? Just like in real life, Python works with different kinds of information. You can't add someone's name to their age - they're different types of data. Python has four main data types you'll use constantly: * **Numbers** for counting and calculations * **Text** for words and messages * **True/False** for decisions Each type has its own rules and abilities. Let's explore them. ## The main types Integers and decimals for math Text, words, and characters True or False values ## Why we need data types Python needs to know what type of data you're working with: ```python theme={null} # Numbers can do math total = 10 + 5 # 15 # Strings combine differently name = "Hello" + "World" # "HelloWorld" # Can't mix without converting # age = "25" + 5 # Error! age = int("25") + 5 # 30 (converted string to number) ``` ## Checking types You can always check what type something is with `type()`: ```python theme={null} # Check different types print(type(42)) # print(type(3.14)) # print(type("Hello")) # print(type(True)) # # Check variables age = 25 name = "Alice" print(type(age)) # print(type(name)) # ``` ## Start learning Pick a data type to explore - numbers are a great place to start! Integers and floats # Numbers Source: https://python.datalumina.com/data-types/numbers Working with integers and decimals ## Two types of numbers Python has two ways to store numbers: **Integers** - Whole numbers without decimals ```python theme={null} age = 25 score = -10 ``` **Floats** - Numbers with decimal points ```python theme={null} price = 19.99 temperature = -5.5 pi = 3.14159 ``` Python uses a dot (.) for decimals, not a comma. Writing `3,14` creates a tuple, not the number 3.14! ## Why two types? Python separates integers and floats for efficiency - computers can work with whole numbers faster and more precisely. But here's the reassuring part: in practice, you rarely need to think about this. Python handles the conversion automatically when needed, and most of the time you'll just use whatever makes sense - whole numbers for counting things, decimals for measurements and calculations. ## Basic math operations Numbers work just like a calculator: ```python theme={null} # Addition and subtraction total = 10 + 5 # 15 change = 20 - 7 # 13 # Multiplication and division area = 6 * 4 # 24 half = 10 / 2 # 5.0 (always returns float) # Powers squared = 5 ** 2 # 25 cubed = 2 ** 3 # 8 ``` ## Integer vs float division Division has two forms: ```python theme={null} # Regular division (always float) result = 10 / 3 # 3.333... # Integer division (rounds down) result = 10 // 3 # 3 ``` These are just the basics! Python can solve complex math problems too. When you need square roots, trigonometry, or advanced calculations, ask AI to help with the specific syntax - no need to memorize every math symbol right now. ## Common mistakes ```python theme={null} # Even when dividing evenly result = 10 / 2 print(result) # 5.0 (not 5) print(type(result)) # # Use // for integer result result = 10 // 2 # 5 ``` ```python theme={null} # Wrong million = 1,000,000 # Creates a tuple, not a number! # Right million = 1000000 # Hard to read million = 1_000_000 # Python style ``` ## What's next? Now let's learn about working with text in Python! Text and characters # Strings Source: https://python.datalumina.com/data-types/strings Working with text in Python ## What are strings? Strings are text - any characters inside quotes. Python doesn't care if you use single or double quotes, just be consistent. ```python theme={null} name = "Alice" message = 'Hello, World!' ``` ## Creating strings Three ways to make strings: ```python theme={null} # Single quotes first = 'Python' # Double quotes second = "Python" # Triple quotes for multiple lines paragraph = """This is a multi-line string""" ``` Use double quotes when your text contains apostrophes: `"It's Python!"` ## Combining strings Join strings together with `+`: ```python theme={null} first_name = "John" last_name = "Doe" # Concatenation full_name = first_name + " " + last_name print(full_name) # John Doe # Repetition stars = "*" * 5 print(stars) # ***** ``` ## String length Use `len()` to count characters: ```python theme={null} message = "Hello" print(len(message)) # 5 empty = "" print(len(empty)) # 0 ``` ## Converting to string Turn other types into strings with `str()`: ```python theme={null} age = 25 message = "I am " + str(age) + " years old" print(message) # I am 25 years old # Or use f-strings (we'll learn more later) message = f"I am {age} years old" ``` ## Common mistakes ```python theme={null} # Wrong - mismatched quotes text = "Hello' # Right - matching quotes text = "Hello" text = 'Hello' ``` ```python theme={null} # Wrong result = "Age: " + 25 # TypeError! # Right - convert number first result = "Age: " + str(25) ``` ```python theme={null} # Wrong name = Alice # Python looks for variable Alice # Right name = "Alice" # String literal ``` ## What's next? Let's explore True/False values - essential for making decisions in your code! True and False values # Defining functions Source: https://python.datalumina.com/functions/defining-functions Create your own reusable functions ## Your first function A function is a named block of code that performs a specific task. You define it once, then call it whenever you need that task done. ```python theme={null} def greet(): print("Hello, world!") print("Welcome to Python!") # Call the function greet() ``` ## Function syntax Every function follows this pattern: ```python theme={null} def function_name(): # Code goes here # Must be indented pass ``` Key parts: * `def` - keyword that creates a function * Function name followed by parentheses `()` * Colon `:` to start the function body * Indented code block (the function body) ## Naming functions Follow these rules for function names: * Use lowercase letters * Separate words with underscores * Be descriptive about what it does ```python theme={null} # Good names def calculate_total(): pass def send_email(): pass def validate_password(): pass # Bad names def func1(): # Not descriptive pass def Calculate(): # Should be lowercase pass ``` ## Calling functions To use a function, call it by name with parentheses: ```python theme={null} def say_goodbye(): print("Goodbye!") print("See you later!") # Call it multiple times say_goodbye() say_goodbye() say_goodbye() ``` The power of functions: write once, use many times. The above code prints 6 lines with just 3 function calls! ## Functions with logic Functions can contain any Python code: ```python theme={null} def check_weather(): temperature = 25 if temperature > 30: print("It's hot!") else: print("Nice weather!") # Use the function check_weather() ``` ## Variable scope: Local vs Global Variables in Python have a "scope" - where they can be accessed and used. ### Local variables Variables created inside a function only exist within that function: ```python theme={null} def calculate_price(): price = 100 tax = price * 0.1 print(f"Total: {price + tax}") calculate_price() # Total: 110 # This fails - price doesn't exist outside the function print(price) # NameError: name 'price' is not defined ``` ### Global variables Variables created outside functions can be accessed anywhere: ```python theme={null} discount_rate = 0.15 # Global variable def apply_discount(price): discount = price * discount_rate # Can read global variable return price - discount result = apply_discount(100) print(result) # 85.0 ``` ### Modifying global variables To change a global variable inside a function, use the `global` keyword: ```python theme={null} counter = 0 # Global variable def increment(): global counter # Declare we want to modify the global variable counter += 1 increment() increment() print(counter) # 2 ``` Avoid using `global` when possible. It makes code harder to understand and debug. Instead, pass values as parameters and return results. ### Best practice: Use parameters and returns ```python theme={null} # Bad - using global variable total = 0 def add_to_total(amount): global total total += amount # Good - using parameters and return def add_amounts(current_total, amount): return current_total + amount total = 0 total = add_amounts(total, 10) total = add_amounts(total, 20) print(total) # 30 ``` When a local and global variable have the same name, the local variable "shadows" the global one inside the function. Python always uses the local version first. ## Common mistakes ```python theme={null} # Wrong - this doesn't call the function greet # Right - parentheses are required greet() ``` ```python theme={null} # Wrong def greet() print("Hello") # Right def greet(): print("Hello") ``` ```python theme={null} # Wrong - not indented def greet(): print("Hello") # Right - must indent function body def greet(): print("Hello") ``` ## What's next? Functions become powerful when they can accept input. Let's learn about parameters! Pass data to functions # Functions Source: https://python.datalumina.com/functions/index Create reusable blocks of code ## Building with functions Functions are reusable blocks of code that do specific tasks. Instead of writing the same code multiple times, you write it once as a function and call it whenever needed. Think of functions like: * A recipe you can follow multiple times * A machine that takes input and produces output * A named shortcut for complex operations ## Why use functions? * **Don't repeat yourself**: Write code once, use it many times * **Stay organized**: Break complex programs into smaller pieces * **Fix bugs easier**: Change code in one place, affects everywhere * **Test your code**: Test each function separately ## What you'll learn Create your own functions Pass data to functions Get results from functions ## Real-world examples Functions are everywhere in programming: * `print()` - displays text (built-in function) * `len()` - counts items (built-in function) * `calculate_tax()` - your custom function * `send_email()` - your custom function ## Let's begin! Start by learning how to create your first function. Create your first function # Parameters Source: https://python.datalumina.com/functions/parameters Pass data into your functions ## What are parameters? Parameters let you pass data into functions. Instead of hardcoding values, you make functions flexible to work with different inputs. ```python theme={null} # Without parameters (inflexible) def greet_alice(): print("Hello, Alice!") # With parameters (flexible) def greet(name): print(f"Hello, {name}!") # Now it works for anyone greet("Alice") greet("Bob") greet("Charlie") ``` ## Basic parameters Add parameters inside the parentheses when defining a function: ```python theme={null} def introduce(name, age): print(f"My name is {name}") print(f"I am {age} years old") # Call with values introduce("Alice", 25) introduce("Bob", 30) ``` The values you pass when calling a function are called "arguments". The variables in the function definition are "parameters". Many people use these terms interchangeably. ## Multiple parameters Functions can have multiple parameters: ```python theme={null} def calculate_total(price, tax_rate, discount): tax = price * tax_rate final_price = price + tax - discount print(f"Total: ${final_price}") # Order matters! calculate_total(100, 0.08, 10) # $98 ``` ## Default values Give parameters default values for optional arguments: ```python theme={null} def greet(name, greeting="Hello"): print(f"{greeting}, {name}!") # Use default greet("Alice") # Hello, Alice! # Override default greet("Bob", "Hi") # Hi, Bob! greet("Charlie", "Hey") # Hey, Charlie! ``` Put parameters with defaults at the end. Required parameters come first, optional ones last. ## Keyword arguments Call functions using parameter names for clarity: ```python theme={null} def create_profile(name, age, city): print(f"{name}, {age}, from {city}") # Positional arguments (order matters) create_profile("Alice", 25, "NYC") # Keyword arguments (order doesn't matter) create_profile(city="NYC", age=25, name="Alice") create_profile(name="Bob", city="LA", age=30) ``` ## Common mistakes ```python theme={null} def greet(name, age): print(f"Hi {name}, you're {age}") # Wrong - too few arguments greet("Alice") # TypeError! # Wrong - too many arguments greet("Alice", 25, "NYC") # TypeError! # Right greet("Alice", 25) ``` ```python theme={null} # Wrong - don't use lists as defaults def add_item(item, list=[]): list.append(item) return list # Right - use None and create new list def add_item(item, list=None): if list is None: list = [] list.append(item) return list ``` ## What's next? Functions become truly powerful when they can return values. Let's learn how! Get results from functions # Return values Source: https://python.datalumina.com/functions/return-values Get results back from your functions ## Getting results from functions So far, our functions have printed output. But often you want functions to calculate something and give you the result to use elsewhere. ```python theme={null} # This function only prints def add_print(a, b): print(a + b) # This function returns a value def add_return(a, b): return a + b # Now you can use the result result = add_return(5, 3) print(f"The result is {result}") # The result is 8 ``` ## The return statement Use `return` to send a value back from a function: ```python theme={null} def calculate_area(width, height): area = width * height return area # Store the returned value room_area = calculate_area(10, 12) print(f"Room size: {room_area} sq ft") # Room size: 120 sq ft ``` When Python hits a `return` statement, it immediately exits the function. Any code after `return` won't run. ## Using returned values Returned values can be used in many ways: ```python theme={null} def double(number): return number * 2 # Store in variable result = double(5) # Use in expressions total = double(5) + double(3) # 10 + 6 = 16 # Pass to other functions print(double(10)) # 20 # Use in conditions if double(7) > 10: print("Big number!") ``` ## Returning multiple values Python can return multiple values as a tuple: ```python theme={null} def get_min_max(numbers): return min(numbers), max(numbers) # Get both values minimum, maximum = get_min_max([5, 2, 8, 1, 9]) print(f"Min: {minimum}, Max: {maximum}") # Min: 1, Max: 9 # Or as a tuple result = get_min_max([5, 2, 8, 1, 9]) print(result) # (1, 9) ``` ## Return vs print Understanding the difference is crucial: ```python theme={null} def get_greeting_print(name): print(f"Hello, {name}!") # Just displays def get_greeting_return(name): return f"Hello, {name}!" # Gives back value # Can't use print version's output message = get_greeting_print("Alice") # Prints but returns None print(message) # None # Can use return version's output message = get_greeting_return("Alice") # Returns the string print(message.upper()) # HELLO, ALICE! ``` Use `return` when you need to use the result elsewhere. Use `print` when you just want to display information. ## Functions without return Functions without explicit `return` statements return `None`: ```python theme={null} def greet(name): print(f"Hello, {name}!") # No return statement result = greet("Alice") # Prints: Hello, Alice! print(result) # None ``` ## Common mistakes ```python theme={null} # Wrong - calculates but doesn't return def calculate_total(items): total = sum(items) # Forgot return! # Right def calculate_total(items): total = sum(items) return total ``` ```python theme={null} # Wrong - code after return never runs def get_status(): return "Done" print("This never prints!") # Unreachable # Right - return last def get_status(): print("Checking status...") return "Done" ``` ```python theme={null} # Wrong - prints instead of returning def multiply(a, b): print(a * b) result = multiply(3, 4) # Prints 12 total = result + 10 # Error! result is None # Right - return the value def multiply(a, b): return a * b ``` ## What's next? Now that you know functions, let's learn how to use external libraries and APIs to extend Python's capabilities! Use libraries and APIs # Course resources Source: https://python.datalumina.com/getting-started/course-resources Download all templates, files, and cheat sheets ## Access your course materials All resources you need for this course are available in the resource hub. This includes templates, example files, cheat sheets, and reference materials you'll use throughout the course. Get all course resources (templates, files, and cheat sheets) for free To access the resources: fill in \$0 (or any tip you want to give), click "I want this", then enter your email to receive the download links. ## What's included The resource hub contains: * Cheat sheets for quick reference * Example files for hands-on practice * Project templates for later sections You'll need these resources for upcoming sections of the course. Access the hub now and download what you need as you progress. Learn how to manage Python environments # First Python file Source: https://python.datalumina.com/getting-started/first-python-file Write and run your first Python program ## Create a new file With your `python-for-ai` project open in VS Code: 1. Click the "New File" button in the Explorer (looks like a page with a +) 2. Name it `hello.py` 3. Press Enter Make sure to include the `.py` extension! This tells VS Code and Python that this is a Python file. ## Understanding file extensions File extensions tell your computer and VS Code what type of file you're working with. There are many files type, here are some examples: * `.txt` - Plain text file, no special formatting * `.md` - Markdown file, for documentation * `.py` - Python file, contains Python code When you save a file with `.py`, VS Code: * Adds syntax highlighting (colors your code) * Enables Python-specific features * Shows Python in the bottom-right corner ## Write your first program In your `hello.py` file, type: ```python theme={null} print("Hello, World!") print("I'm learning Python for AI") ``` The `print()` function displays text or values on your screen - we'll use it throughout this course to see what our code is doing. Notice how VS Code colors your code: * `print` is highlighted as a function * Text in quotes is shown in a different color * This helps you spot errors quickly ## Select Python interpreter Before running your code, make sure VS Code is using the right Python: 1. Look at the bottom-right corner of VS Code 2. You should see something like "Python 3.x.x" 3. If not, click the area that says "Select Python Interpreter" 4. Choose the Python version you installed earlier We're using the main Python installation for now. Later in the course, you'll learn about virtual environments for more advanced project management. ## Run your program There are three ways to run your Python code: **Method 1: Run button** (easiest) * Click the triangle "Run" button in the top-right corner * Or select the down arrow next to it and select "Run Python File" **Method 2: Right-click menu** * Right-click anywhere in your code * Select "Run Python File in Terminal" **Method 3: Keyboard shortcut** * Press `Ctrl + F5` (Windows/Linux) or `Cmd + F5` (macOS) ## Understanding the output When you run your code, the terminal opens at the bottom. You'll see something like this (yours will look slightly different): ```bash theme={null} cd /path/to/your/project /path/to/python /path/to/your/project/hello.py Hello, World! I'm learning Python for AI ``` What's happening here: 1. **First line**: VS Code navigates to your project folder 2. **Second line**: VS Code runs Python with the full path to your file 3. **Following lines**: Your program's output! Don't worry about the long paths - VS Code handles all of this automatically. The important part is seeing your output: "Hello, World!" ## What's happening behind the scenes? When you click the "Run" button in VS Code, it's actually running a command in the terminal for you. Let's understand what's really happening: ### The basic command At its core, running a Python file is simple: ```bash theme={null} python hello.py ``` This tells your computer: 1. **python** - Find the Python program 2. **hello.py** - Open this file and execute the code inside ### How Python executes your code Here's what happens when you run `python hello.py`: 1. **Python reads your file** - Opens `hello.py` and reads the text 2. **Python interprets the code** - Converts your code into instructions the computer understands 3. **Python executes line by line** - Runs each instruction from top to bottom, left to right 4. **Output appears in terminal** - Any `print()` statements display their results Python always executes code **top to bottom** (one line after another) and **left to right** (within each line). This means the order of your code matters! ```python theme={null} print("Hello, World!") # Line 1: Python reads this # Python converts it to machine instructions # Python executes: display "Hello, World!" # You see: Hello, World! print("I'm learning Python") # Line 2: Same process ``` This execution order means: * Line 2 can't run before Line 1 * What you write first happens first * Later in the course, you'll see how to control this flow with conditions and loops ### Running manually from the terminal You can run Python files directly in the terminal without using VS Code's button: ```bash theme={null} # Make sure you're in the same folder as your file python hello.py ``` Or with the full path: ```bash theme={null} # You can run from anywhere if you use the full path python /Users/yourname/python-for-ai/hello.py ``` VS Code's "Run" button is just a convenient way to run `python your_file.py` in the terminal. The underlying process is exactly the same! ### Python vs python3 On some systems (especially Mac/Linux), you might need to use `python3` instead of `python`: ```bash theme={null} python3 hello.py ``` This ensures you're using Python 3.x instead of the older Python 2.x. VS Code usually handles this automatically. ### Why this matters Understanding this is important because: * You can run Python files from any terminal, not just VS Code * You'll see these commands in tutorials and documentation * Later, you'll pass arguments to your programs: `python script.py --option value` * This is how Python works everywhere: on servers, in production, in automation scripts Think of VS Code as a fancy wrapper around the terminal. When you click "Run," you're really just typing `python hello.py` into the terminal. VS Code makes it easier, but the fundamentals stay the same. ## The integrated terminal The terminal at the bottom is the same as your system's terminal, but inside VS Code. Here's how to work with it: ### Opening and closing the terminal * **Open**: View > Terminal (or press `` Ctrl + ` `` on Windows/Linux, `` Cmd + ` `` on macOS) * **Hide**: Click the X or press the same shortcut again * **New terminal**: Click the + button or Terminal > New Terminal ### Terminal basics * You can type commands directly * Try typing `python --version` and press Enter * Type `cls` (Windows) or `clear` (Mac/Linux) to clear the screen * Use the up arrow to recall previous commands The integrated terminal means you never have to leave VS Code. You can write code, run it, install packages, and manage files all in one place. ## Experiment Try changing your code and running it again: ```python theme={null} print("Hello, World!") print("I'm learning Python for AI") print("My name is [Your Name]") print("Today is a great day to code!") ``` Each `print()` statement creates a new line of output. ## Save your work Remember to save your file: * Press `Ctrl + S` (Windows/Linux) or `Cmd + S` (macOS) * Or use File > Save VS Code shows a dot next to unsaved files in the tab. ## What you've learned Congratulations! You've: * Created your first Python file * Written Python code * Selected the Python interpreter * Run a Python program * Understood the terminal output This is the foundation for everything else you'll learn in Python. Download all templates, files, and cheat sheets # Getting started Source: https://python.datalumina.com/getting-started/index Set up your Python development environment ## Here's what we will cover In this section, you'll set up everything needed to start writing Python code. We'll install Python, configure your code editor, and run your first program. Understanding programming basics Get Python on your computer Write and run your first code ## Ready to begin? Learn what programming is all about # Installing Python Source: https://python.datalumina.com/getting-started/installing-python Get Python running on your computer ## Choose your operating system Installing Python differs based on your operating system. Select your platform below for specific instructions. Don't worry - Python works the same way once installed. The installation process is just different for each system. Windows 10 or 11 Mac computers Ubuntu, Debian, etc. # Install on Linux Source: https://python.datalumina.com/getting-started/installing-python-linux Installing Python on Linux distributions ## Check existing Python Most Linux distributions come with Python pre-installed. Let's check: ```bash theme={null} python3 --version ``` If you see a recent Python 3 version, you're ready! Most modern Linux distributions include Python 3. Linux uses `python3` to distinguish from the older Python 2. Some distributions let you use just `python`, but `python3` always works. ## Install or update Python Choose your Linux distribution below: ### Update package lists ```bash theme={null} sudo apt update ``` ### Install Python and essential tools ```bash theme={null} sudo apt install python3 python3-pip python3-venv ``` ### Install development headers (for compiling packages) ```bash theme={null} sudo apt install python3-dev build-essential ``` ### For the latest Python version If your distribution doesn't have the latest Python: ```bash theme={null} # Add the deadsnakes PPA sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update # Install specific version (example: 3.13) sudo apt install python3.13 python3.13-venv python3.13-dev ``` ### Install Python and pip ```bash theme={null} sudo dnf install python3 python3-pip python3-devel ``` ### Install compilation tools ```bash theme={null} sudo dnf groupinstall "Development Tools" ``` ### For newer Python versions ```bash theme={null} # Check available versions dnf search python3 # Install specific version sudo dnf install python3.13 ``` ### Python is usually pre-installed ```bash theme={null} # If needed, install Python sudo pacman -S python python-pip ``` ### Install base development tools ```bash theme={null} sudo pacman -S base-devel ``` ### For specific versions ```bash theme={null} # Search available versions pacman -Ss python3 # Install from AUR if needed yay -S python313 ``` ### Install Python and pip ```bash theme={null} sudo zypper install python3 python3-pip python3-devel ``` ### Install development pattern ```bash theme={null} sudo zypper install -t pattern devel_basis ``` ### Install Python and pip ```bash theme={null} apk add python3 py3-pip python3-dev ``` ### Install build tools ```bash theme={null} apk add build-base ``` ## Verify installation Check that Python and pip are installed: ```bash theme={null} python3 --version pip3 --version ``` You should see version numbers for both. ## Test Python 1. Start Python: ```bash theme={null} python3 ``` 2. You'll see the Python prompt: ``` Python 3.13.5 (main, Jul 29 2025, 12:03:01) [GCC 11.2.0] on linux Type "help", "copyright", "credits" or "license" for more information. >>> ``` 3. Try a simple command: ```python theme={null} print("Hello from Linux!") ``` 4. Exit Python: * Type `exit()` or press `Ctrl + D` ## Troubleshooting **For system packages**: Always use `sudo`: ```bash theme={null} sudo apt install python3-pip ``` **For pip packages**: Install in user space: ```bash theme={null} pip3 install --user package-name ``` **Best practice**: Use virtual environments to avoid permission issues entirely. Python isn't installed. Install it using your package manager: ```bash theme={null} # Ubuntu/Debian sudo apt update && sudo apt install python3 # Fedora sudo dnf install python3 # Arch sudo pacman -S python ``` pip isn't installed. Fix it. ```bash theme={null} # Ubuntu/Debian sudo apt install python3-pip # Fedora sudo dnf install python3-pip # From Python python3 -m ensurepip ``` Your distribution has an old Python. Options:

**Option 1**: Use deadsnakes PPA (Ubuntu/Debian): ```bash theme={null} sudo add-apt-repository ppa:deadsnakes/ppa sudo apt update sudo apt install python3.13 ``` **Option 2**: Compile from source: ```bash theme={null} # Install dependencies sudo apt install build-essential zlib1g-dev libncurses5-dev \ libgdbm-dev libnss3-dev libssl-dev libreadline-dev \ libffi-dev libsqlite3-dev wget libbz2-dev # Download and compile wget https://www.python.org/ftp/python/3.13.5/Python-3.13.5.tgz tar -xf Python-3.13.5.tgz cd Python-3.13.5 ./configure --enable-optimizations make -j $(nproc) sudo make altinstall ``` **Option 3**: Use pyenv for version management

Modern Linux prevents pip from installing system-wide. Solutions:

**Use virtual environments** (recommended): ```bash theme={null} python3 -m venv myenv source myenv/bin/activate pip install package-name ``` **Install in user directory**: ```bash theme={null} pip3 install --user package-name ``` **Use pipx for applications**: ```bash theme={null} sudo apt install pipx pipx install application-name ```
## Next steps Great! Python is ready on your Linux system. Let's set up your development environment. Install and configure Visual Studio Code # Install on macOS Source: https://python.datalumina.com/getting-started/installing-python-macos Installing Python on Mac computers ## Check existing Python macOS includes an older Python version for system use. Let's check what you have: 1. Open Terminal: * Press `Cmd + Space` to open Spotlight * Type "Terminal" and press Enter * Or find Terminal in Applications > Utilities 2. Check Python version: ```bash theme={null} python3 --version ``` If you see a recent Python 3 version, you might already be set! Some Mac users can use just `python` instead of `python3`, but this depends on your system configuration. When in doubt, use `python3`. ## Download Python 1. Go to [python.org/downloads](https://www.python.org/downloads/) 2. The site will detect you're on macOS and show the latest version 3. Click the download button to get the `.pkg` installer Always download from python.org to ensure you get the official, secure version. ## Install Python 1. Open the downloaded `.pkg` file 2. The Python installer will open 3. Click "Continue" through the introduction and license screens 4. Click "Agree" to accept the license 5. Click "Install" (you'll need to enter your Mac password) 6. Wait for installation to complete 7. Click "Close" when you see "The installation was successful" ## Verify installation Open a **new** Terminal window (important!) and check the version: ```bash theme={null} python3 --version ``` You should see the version you just installed. The exact number depends on when you download. ## Test Python Let's make sure Python works properly: 1. In Terminal, type: ```bash theme={null} python3 ``` 2. You'll see something like: ``` Python 3.13.5 (v3.13.5:0fa1754080, Jul 29 2025, 09:45:56) [Clang 15.0.0] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> ``` 3. Try your first Python command: ```python theme={null} print("Hello from Python!") ``` 4. Press `Enter` and you should see: ``` Hello from Python! ``` 5. To exit Python: * Type `exit()` and press Enter * Or press `Ctrl + D` ## Troubleshooting The Terminal might not see the new installation yet.

**Solution 1**: Close Terminal completely and open a new window.

**Solution 2**: Check if Python is installed but not in PATH: ```bash theme={null} ls /Library/Frameworks/Python.framework/Versions/ ``` **Solution 3**: Add Python to your PATH manually: ```bash theme={null} echo 'export PATH="/Library/Frameworks/Python.framework/Versions/Current/bin:$PATH"' >> ~/.zshrc source ~/.zshrc ```
This is normal on macOS. You have three options:

**Option 1**: Always use `python3` (recommended)

**Option 2**: Create an alias: ```bash theme={null} echo 'alias python=python3' >> ~/.zshrc echo 'alias pip=pip3' >> ~/.zshrc source ~/.zshrc ``` **Option 3**: Check if the installer created a `python` link: ```bash theme={null} which python ```
You forgot to install certificates. Fix it by

Running from Terminal: ```bash theme={null} /Applications/Python\ 3.*/Install\ Certificates.command ``` Or manually installing certificates: ```bash theme={null} pip3 install --upgrade certifi ```
macOS can have multiple Python versions. To manage them:

**See all installed versions**: ```bash theme={null} ls -la /usr/local/bin/python* ``` **Use a specific version**: ```bash theme={null} python3.13 --version python3.12 --version ``` **Set a default** (example for 3.13): ```bash theme={null} ln -s -f /usr/local/bin/python3.13 /usr/local/bin/python3 ```
## Alternative: Homebrew installation If you prefer using a package manager: ```bash theme={null} /bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)" ``` ```bash theme={null} brew install python@3 ``` ```bash theme={null} python3 --version ``` Homebrew Python might use different paths than the official installer. Both work fine. ## Next steps Perfect! Python is now installed on your Mac. Let's set up your code editor. Install and configure Visual Studio Code # Install on Windows Source: https://python.datalumina.com/getting-started/installing-python-windows Installing Python on Windows 10/11 ## Download Python 1. Go to [python.org/downloads](https://www.python.org/downloads/) 2. The site will detect you're on Windows and show the latest version 3. Click the download button to get the installer 4. Save it to your Downloads folder Always get Python from the official website to ensure it's secure and up-to-date. ## Install Python This is the most important part - pay close attention to step 2! 1. Find and run the downloaded installer 2. **Important**: Check ✓ "Add python.exe to PATH" at the bottom If you miss the "Add to PATH" checkbox, Python won't work from Terminal. This is the #1 installation mistake. 3. Click "Install Now" (not "Customize installation" unless you know what you're doing) 4. If Windows asks "Do you want to allow this app to make changes?", click "Yes" 5. Wait for installation (usually takes 1-2 minutes) 6. Click "Close" when you see "Setup was successful" ## Verify installation Let's make sure Python installed correctly: 1. Open Terminal: * Press `Windows + R` * Type `wt` and press `Enter` * Or search "Terminal" in Start menu Windows Terminal is the modern app that can run Command Prompt (cmd), PowerShell, or other shells. It's the recommended way to use Python on Windows. 2. Type this command: ```bash theme={null} python --version ``` 3. You should see the Python version you just installed On Windows, you can usually use `python` (not `python3` like on Mac/Linux). ## Test Python Let's run Python for the first time: 1. In Terminal, type: ```bash theme={null} python ``` 2. You'll see something like: ``` Python 3.13.5 (tags/v3.13.5:0fa1754, Jul 29 2025, 12:03:01) [MSC v.1935 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> ``` 3. The `>>>` means Python is running! Try: ```python theme={null} print("Hello from Python!") ``` 4. Press `Enter` to see: ``` Hello from Python! ``` 5. To exit Python: * Type `exit()` and press `Enter` * Or press `Ctrl + Z` then `Enter` ## Troubleshooting This means Python wasn't added to PATH. Here's how to fix it.

**Quick Fix**: Try `py` instead of `python`: ```bash theme={null} py --version ``` **Solution 1**: Reinstall Python 1. Uninstall Python from Settings > Apps 2. Download and run installer again 3. CHECK the "Add to PATH" box this time! **Solution 2**: Add to PATH manually 1. Search "Environment Variables" in Start menu 2. Click "Environment Variables" button 3. Under "System variables", find and double-click "Path" 4. Click "New" and add these two paths: ``` C:\Users\[YourName]\AppData\Local\Programs\Python\Python313 C:\Users\[YourName]\AppData\Local\Programs\Python\Python313\Scripts ``` 5. Replace `[YourName]` with your Windows username 6. Replace `Python313` with your actual Python version folder 7. Click OK on all windows 8. **Close and reopen** Terminal
**During installation**: * Right-click the installer * Select "Run as administrator" **When running Python**: * Open Terminal as administrator * Right-click Terminal > Run as administrator Windows might flag Python as suspicious: 1. When warning appears, click "More info" 2. Click "Run anyway" 3. Or add Python to Windows Defender exceptions: * Settings > Windows Security > Virus & threat protection * Add an exclusion > Folder * Add Python installation folder Windows can have multiple Python versions. To manage them:

**See all versions**: ```bash theme={null} py -0 ``` **Use specific version**: ```bash theme={null} py -3.13 --version py -3.12 script.py ``` **Set default version**: Create `py.ini` in your home folder with: ```ini theme={null} [defaults] python=3.13 ```
If typing `python` opens Microsoft Store: 1. Settings > Apps > Apps & features 2. Click "App execution aliases" 3. Turn OFF the Python aliases 4. Use the python.org installer instead The Microsoft Store version has limitations for development.
Install and configure Visual Studio Code # Interactive Python Source: https://python.datalumina.com/getting-started/interactive-python My favorite way to write Python code ## The best of both worlds Interactive Python mode is my favorite way to write Python code, and I rarely use anything else. It combines the organization of Python files with the interactivity of Jupyter notebooks. This is how I'll be coding throughout the entire course. Once you try it, you'll understand why it's so powerful for learning and developing AI applications. ## What is Interactive Python? Imagine you're cooking and tasting as you go, rather than waiting until the entire meal is done. That's Interactive Python: * Write code in a `.py` file (organized and clean) * Run pieces of it instantly with `Shift + Enter` * See results immediately in a side panel * Keep all your variables in memory ## Why it's perfect for AI development When working with AI and data: * You're constantly inspecting data * Testing transformations * Checking outputs * Experimenting with different approaches Running an entire file every time (like we did with `hello.py`) would be slow and frustrating. Interactive mode lets you work iteratively. ## Prerequisites Interactive Python requires the IPython kernel. Let's install it: 1. Make sure your virtual environment is activated: ```bash theme={null} # You should see (venv) in your terminal ``` 2. Install the required package: ```bash theme={null} pip install ipykernel ``` This package allows Jupyter to run Python code interactively. ## Set up Interactive Python Now let's enable the interactive feature: 1. Open VS Code settings: * Press `Ctrl/Cmd + ,` (comma) * Or File > Preferences > Settings 2. Search for "execute selection" 3. Find this setting: **Jupyter > Interactive Window > Text Editor: Execute Selection** 4. Check the box to enable it What this does: When you press `Shift + Enter`, your selected code will run in the Jupyter interactive window instead of the Python terminal. This gives you a much richer, more visual experience. That's it! You're ready to use interactive mode. ## Your first interactive session 1. Create a new file called `interactive_demo.py` 2. Type this code: ```python theme={null} # Let's explore interactive mode name = "Python Learner" print(f"Hello, {name}!") # Some data to work with numbers = [1, 2, 3, 4, 5] print(f"Numbers: {numbers}") # Calculate something total = sum(numbers) print(f"Total: {total}") ``` 3. Place your cursor on the first line 4. Press `Shift + Enter` Watch what happens: * An Interactive window opens on the right * Your code runs line by line * You see output immediately ## Interactive superpowers ### Run selected code * Highlight any code * Press `Shift + Enter` * Only that selection runs ### Variables stay in memory Run this step by step: ```python theme={null} # First, create a variable message = "Hello" # Later, use it (even in a different cell) print(message + " World!") # Modify it message = message.upper() print(message) ``` The variable `message` stays available throughout your session! Your environment is perfect. Let's dive into Python fundamentals! # Packages and pip Source: https://python.datalumina.com/getting-started/packages-and-pip Understanding Python's package ecosystem ## Standing on the shoulders of giants One of Python's superpowers is its massive collection of packages. Instead of writing everything from scratch, you can use code that others have already written, tested, and shared. ## What are packages? **Packages** are collections of Python code that solve specific problems: * **requests** - Download web pages and data * **pandas** - Work with spreadsheets and data * **numpy** - Fast mathematical operations * **openai** - Connect to AI models * **beautifulsoup4** - Extract data from websites Each package is like a toolbox with specialized tools for a specific job. ## Meet pip **pip** (Pip Installs Packages) is Python's package manager. It: * Downloads packages from the internet * Installs them in your environment * Manages versions and dependencies pip comes with Python, so you already have it! When you activated your virtual environment, you got your own copy of pip. ## Your first package installation Now we need to use the terminal - your command center for managing packages. ### Understanding the terminal The terminal is where you type commands to control Python. Most of the time, VS Code handles everything automatically (like running your code). But for installing packages, we need to type commands ourselves. Open your terminal: * **Keyboard shortcut**: Press `` Ctrl + ` `` (Windows/Linux) or `` Cmd + ` `` (macOS) * **Menu**: View > Terminal When the terminal opens, you'll see something like: ```bash theme={null} (.venv) PS C:\...\python-for-ai> ``` That `(.venv)` at the beginning? That's VS Code telling you "I've activated your virtual environment for you!" This means any packages you install will go into your project, not your computer's main Python. ### Install your first package Let's install the `requests` package: ```bash theme={null} pip install requests ``` Just type that command and press Enter. You'll see output like: ``` Collecting requests Downloading requests-2.31.0-py3-none-any.whl (62 kB) Installing collected packages: requests Successfully installed requests-2.31.0 ``` ### What just happened? No magic here! When you ran `pip install requests`, here's what happened: 1. **pip connected to PyPI** (Python Package Index) - a huge website where developers share their code 2. **Downloaded the requests package** - just a bunch of Python files that someone else wrote 3. **Saved it in your `.venv` folder** - specifically in `.venv/lib/python3.x/site-packages/` That's it! You just downloaded someone else's Python code and saved it in your project. Now you can use their code as if you wrote it yourself. Want to see the actual files? Look in your `.venv` folder and navigate to `lib` > `python3.x` > `site-packages` > `requests`. It's just Python files! ## Using installed packages Now you can use this package in your Python code: ```python theme={null} import requests # Download a web page response = requests.get("https://api.github.com") print(response.status_code) # Should print 200 ``` Without the requests package, downloading web data would require dozens of lines of complex code. With it, it's just two lines! ## See what's installed To check which packages you have: ```bash theme={null} pip list ``` Output: ``` Package Version ------------------ -------- certifi 2024.2.2 charset-normalizer 3.3.2 idna 3.6 pip 24.0 requests 2.31.0 urllib3 2.2.0 ``` Notice how installing `requests` also installed other packages it needs (like `urllib3`). pip handles this automatically! ## Install specific versions Sometimes you need a specific version of a package: ```bash theme={null} # Install exact version pip install requests==2.30.0 # Install minimum version pip install requests>=2.28.0 # Install compatible version pip install requests~=2.31.0 ``` ## Uninstall packages Made a mistake or no longer need something? ```bash theme={null} pip uninstall requests ``` pip will ask for confirmation before removing it. ## Where packages come from pip downloads packages from [PyPI](https://pypi.org/) (Python Package Index), which hosts over 500,000 packages! Anyone can upload packages there, which is why Python has tools for everything. ## Common issues Your virtual environment might not be activated: 1. Check for `(.venv)` in your terminal prompt 2. If missing, activate it using VS Code's Python interpreter selection 3. Or activate manually with the terminal commands from the previous section You're probably trying to install in system Python: * Make sure your virtual environment is activated * Never use `sudo pip install` * Always see `(.venv)` before installing The package name might be different from what you expect: * Check the exact name on [pypi.org](https://pypi.org) * Example: "Beautiful Soup" is actually `beautifulsoup4` * Example: "OpenAI" is just `openai` (lowercase) ## Ready for interactive Python Now that you understand packages, let's install what we need for interactive Python mode! Learn my favorite way to write Python code # Virtual environments Source: https://python.datalumina.com/getting-started/virtual-environments Keep your Python projects organized ## Your Python installation Remember when we installed Python? That installation lives in a specific folder on your computer: * **Windows**: `C:\Users\[YourName]\AppData\Local\Programs\Python\Python313\` * **macOS**: `/Library/Frameworks/Python.framework/Versions/3.13/` * **Linux**: `/usr/bin/python3` This is your "system Python" - it's shared by everything on your computer. ## The problem with sharing Imagine you're working on two projects: * **Project A** needs version 1.0 of a tool * **Project B** needs version 2.0 of the same tool If you install version 2.0 for Project B, you just broke Project A! This is where virtual environments save the day. ## What are virtual environments? A virtual environment is like a private copy of Python for each project. Think of it as: * A separate folder for each project * Its own Python installation * Its own place to install packages * Complete isolation from other projects Virtual environments are so important that I create a new one for EVERY project. It's a Python best practice that will save you from many headaches. ## Understanding packages Before we continue, let's understand what packages are: **Packages** are pre-written code that others have created for us to use. Instead of writing everything from scratch, we can import these packages. For example: * `requests` - for downloading web pages * `pandas` - for working with data * `openai` - for using AI models Each package has different versions, and different projects might need different versions. ## Create your first virtual environment Let's create one for our `python-for-ai` project. You have two methods: ### Method 1: VS Code Command Palette (easier) 1. Open your project in VS Code 2. Press `Ctrl/Cmd + Shift + P` 3. Type "Python: Create Environment" 4. Select "Venv" 5. Select your Python installation 6. VS Code creates and activates everything for you! ### Method 2: Terminal command 1. Open the terminal in VS Code (View > Terminal) 2. Make sure you're in your project folder 3. Run this command: ```bash theme={null} python -m venv .venv ``` ```bash theme={null} python3 -m venv .venv ``` What this does: * `python -m venv` - Run Python's virtual environment module * `.venv` - The name of the folder to create (convention is to use ".venv" with a dot) ## What just happened? Look at your project folder - you now have a new `.venv` folder: ``` python-for-ai/ ├── .venv/ # Your virtual environment (hidden folder) ├── hello.py # Your code └── python-for-ai.code-workspace ``` The dot in `.venv` makes it a hidden folder on Mac/Linux. This keeps your project clean since you don't need to see this folder often. This `.venv` folder contains: * A copy of Python * A place to install packages * Scripts to activate/deactivate ## Activate your virtual environment VS Code makes activation super easy: 1. Press `Ctrl/Cmd + Shift + P` to open Command Palette 2. Type "Python: Select Interpreter" 3. Choose the one that says `.venv` (it will show the full path like `./.venv/bin/python`) 4. That's it! VS Code automatically activates it for you You'll know it's working when you see `(.venv)` in your terminal: ```bash theme={null} (.venv) PS C:\...\python-for-ai> ``` This is my recommended approach. VS Code remembers your choice and automatically activates the environment every time you open the project! ## Common issues If `python -m venv` doesn't work, you might need to install it: **Ubuntu/Debian**: ```bash theme={null} sudo apt install python3-venv ``` **Other systems**: It should come with Python by default On macOS/Linux, you might need to make the activate script executable: ```bash theme={null} chmod +x .venv/bin/activate ``` 1. Reload VS Code window: `Ctrl/Cmd + Shift + P` > "Developer: Reload Window" 2. Manually select interpreter again 3. Make sure the Python extension is installed ## What about Anaconda? You might have heard of Anaconda - it's another tool that manages Python environments and packages. It's popular in the data science world because it comes pre-loaded with many data science packages. However, I don't recommend using Anaconda unless you have a specific reason to. Stick with Python's built-in virtual environments unless your company or a specific project requires Anaconda. You'll have a lighter, faster, and simpler setup. ## What's next? Your virtual environment is ready! Now let's learn about Python packages and how to install them. Understanding pip and package management # Why VS Code Source: https://python.datalumina.com/getting-started/vscode-introduction The best editor for Python development ## The #1 code editor for Python Visual Studio Code (VS Code) is the most popular code editor for Python development right now, including popular forks like Cursor and Windsurf. **It's completely free** and gives you everything you need to write professional Python code. No limitations, no trial periods, just a powerful tool that millions of developers use every day. ## Works with AI coding tools If you've heard about AI-powered coding assistants like **Cursor** or **Windsurf**, here's something important: they're actually built on VS Code. Everything you learn in VS Code transfers directly to these tools. Same interface, same shortcuts, same extensions. You're learning a skill that works everywhere. ## Why I recommend it I've been using VS Code (and now Cursor) for the past 5 years for all development projects we do for our clients at Datalumina. There's literally nothing you can't do with it or would need another tool for. ## What is an IDE? IDE stands for **Integrated Development Environment**. Think of it as a smart text editor designed specifically for coding. Instead of just typing text, an IDE: * Highlights your code in different colors * Shows errors before you run your program * Suggests code as you type * Runs your programs with one click * Helps you organize large projects VS Code is technically a "code editor" but with extensions, it becomes a full IDE. Let's get VS Code installed on your computer # Install VS Code Source: https://python.datalumina.com/getting-started/vscode-setup Download and install Visual Studio Code ## Download VS Code Visual Studio Code is available for all operating systems. The installation is quick and straightforward. 1. Go to [code.visualstudio.com](https://code.visualstudio.com/) 2. Click the big download button (it detects Windows automatically) 3. Run the downloaded installer 4. **Important**: Check these options during installation: * ✓ Add "Open with Code" action to Windows Explorer file context menu * ✓ Add "Open with Code" action to Windows Explorer directory context menu * ✓ Register Code as an editor for supported file types * ✓ Add to PATH 5. Click "Next" and "Install" 6. Click "Finish" when done 1. Go to [code.visualstudio.com](https://code.visualstudio.com/) 2. Click the download button (it detects macOS automatically) 3. Open the downloaded `.zip` file 4. Drag **Visual Studio Code** to your **Applications** folder 5. Optional but recommended: * Right-click VS Code in Applications * Select "Options" > "Keep in Dock" **First time opening**: * You might see "Visual Studio Code is from an unidentified developer" * Go to System Preferences > Security & Privacy * Click "Open Anyway" VS Code is available through multiple installation methods: **Ubuntu/Debian** (recommended): ```bash theme={null} # Download the .deb package wget -O vscode.deb "https://code.visualstudio.com/sha/download?build=stable&os=linux-deb-x64" # Install it sudo apt install ./vscode.deb ``` **Snap package** (works on most distributions): ```bash theme={null} sudo snap install code --classic ``` **Other distributions**: Visit [code.visualstudio.com](https://code.visualstudio.com/) and select your package format (.rpm, .tar.gz, etc.) ## Verify installation Once installed, let's make sure VS Code is working: 1. Open VS Code: * **Windows**: Search "Visual Studio Code" in Start menu * **macOS**: Find it in Applications or press `Cmd + Space` and search * **Linux**: Type `code` in terminal or find it in your applications menu 2. You should see the Welcome tab 3. The interface should look clean and modern ## Install Python extension VS Code needs the [Python extension](https://marketplace.visualstudio.com/items?itemName=ms-python.python) to work properly with Python files: 1. Click the Extensions icon in the left sidebar (it looks like 4 squares) 2. Search for "Python" 3. Find the one by **Microsoft** (it has millions of downloads) 4. Click "Install" 5. Wait for installation to complete The Python extension adds syntax highlighting, code completion, debugging, and more. It's essential for Python development. ## Configure Python execution After installing the Python extension, enable this important setting: 1. Open Settings (`Ctrl/Cmd + ,`) 2. Search for "Python Terminal Execute In File Dir" 3. Check the box to enable it **What this does**: When you run a Python file, VS Code will execute it from the file's directory instead of your workspace root. **Why I recommend it**: This prevents common path-related errors. For example, if your script reads a file with `open('data.csv')`, it will look for the file in the same folder as your script, which is usually what you want. Without this setting, it would look in your project root instead, causing "file not found" errors. ## Additional recommended extensions While VS Code works great with just the Python extension, here are a few more I recommend: ### Pylance * Search for "Pylance" by Microsoft * Provides even better code completion and error detection * Works alongside the Python extension ### Jupyter * Search for "Jupyter" by Microsoft * Enables interactive Python mode (we'll use this later) * Essential for data science and AI work ## Customize appearance (optional) I've been using these settings for years - they're easy on the eyes: ### Theme * Install "Atom One Dark Theme" * Press `Ctrl/Cmd + K`, then `Ctrl/Cmd + T` to select it ### Icons * Install "Material Icon Theme" by Philipp Kief * Makes file types easier to recognize ### Tree indentation * Open Settings (`Ctrl/Cmd + ,`) * Search for "tree indent" * Change from 8 to 20 for clearer folder structure **View keyboard shortcuts**: Open Command Palette (`Ctrl/Cmd + Shift + P`) and search "keyboard shortcuts". You can search for any command and change its shortcut by clicking the pencil icon. ## Check Python detection After setting up VS Code: 1. Press `Ctrl + Shift + P` (Windows/Linux) or `Cmd + Shift + P` (macOS) 2. Type "Python: Select Interpreter" 3. You should see your Python installation listed 4. If not, we'll fix this in the next section Learn how to organize your Python projects # Creating projects Source: https://python.datalumina.com/getting-started/vscode-workspace Organize your Python projects in VS Code ## Create a projects folder Before we start coding, let's create a dedicated place for all your Python projects. Having one folder for all your projects keeps your computer organized and makes it easy to find your code later. 1. **Create a main folder** for all your Python work: * **Windows**: Create a folder called `PythonProjects` in your Documents * **macOS**: Create a folder called `PythonProjects` in your home directory * **Linux**: Create a folder called `PythonProjects` in your home directory 2. **Create your first project folder**: * Inside your PythonProjects folder, create a new folder called `python-for-ai` (all lowercase) * This will be our learning project for this course You can name your project folder anything you like, but I usually use lowercase letters with dashes (called "kebab-case") like `python-for-ai` or `my-first-project`. This matches how projects appear on GitHub (more on that later). ## Open folder in VS Code Now let's open this folder in VS Code. There are several ways: **Method 1: From VS Code** 1. Open VS Code 2. Click "File" > "Open Folder" (or press `Ctrl/Cmd + O`) 3. Navigate to your `python-for-ai` folder 4. Click "Select Folder" (Windows) or "Open" (Mac/Linux) **Method 2: From file explorer** * **Windows**: Right-click the folder > "Open with Code" * **macOS**: Drag the folder onto the VS Code icon * **Linux**: Right-click the folder > "Open with Code" ## Understanding the interface When you open a folder in VS Code: * **Left sidebar**: Shows all files in your project (currently empty) * **Main area**: Where you'll write code * **Bottom panel**: Terminal, problems, output * **Top**: Menu and tabs for open files VS Code always works with folders, not individual files. This helps it understand your project structure and provide better suggestions. ## Save as workspace A workspace saves your project settings and makes it easy to return to your project later. 1. With your `python-for-ai` folder open, click "File" > "Save Workspace As..." 2. Save it in the same `python-for-ai` folder 3. Name it `python-for-ai.code-workspace` 4. Click "Save" ## What's a workspace? A workspace is like a bookmark for your project. It remembers: * Which folder you're working in * Your editor settings for this project * Which files you had open * Your debugging configuration ## Test your workspace Let's make sure the workspace works: 1. Close VS Code completely 2. Go to your `python-for-ai` folder 3. Double-click the `python-for-ai.code-workspace` file 4. VS Code opens with your project ready! You can create a desktop shortcut to your workspace file for even quicker access to your project. ## Project structure Your folder should now look like this: ``` PythonProjects/ └── python-for-ai/ └── python-for-ai.code-workspace ``` We're ready to create our first Python file! Create and run your first Python program # What is Python Source: https://python.datalumina.com/getting-started/what-is-python Understanding programming and Python basics ## What is programming? Programming is writing instructions for computers to follow. Just like you might write a recipe for someone to cook a meal, you write code to tell a computer what to do. Computers are powerful but not smart. They need extremely detailed, step-by-step instructions for everything. A programming language is how we write these instructions in a way both humans and computers can understand. ## Why do we need programming languages? Computers only understand binary (1s and 0s). Writing in binary would be impossible for humans, so we use programming languages as a middle ground: 1. **You write** code in Python (looks like English) 2. **Python translates** your code into instructions 3. **Computer executes** those instructions ## What makes Python special? Python looks almost like plain English Designed to be easy to learn Works for websites, AI, automation, and more Millions of people ready to help ## Your first taste of Python Here's what Python code looks like: ```python theme={null} # This is Python code - it almost reads like English! name = "Sarah" age = 25 print(f"Hello, my name is {name} and I am {age} years old") # Making a simple decision if age >= 18: print("I can vote!") else: print("I'm too young to vote") ``` Notice how readable it is? That's Python's superpower. ## Python versions explained * **Python 3** (current version): This is what you'll learn and use. Check the versions [here](https://devguide.python.org/versions/). * **Python 2** (outdated): Stopped being supported in 2020. You might see old code mentioning it, but ignore it - it's like using Windows XP. Always use Python 3. If you see tutorials mentioning Python 2, find newer ones. ## Ready to install? Let's get Python on your computer # Introduction Source: https://python.datalumina.com/index Complete beginner course for AI development Learn Python for AI Hero Learn Python for AI Hero Dark ## Welcome to Python for AI Learn Python from scratch and start building real AI applications. This is the fastest, beginner-friendly course for Python and AI development. Whether you've never written a line of code or you're switching from another language, this course takes you from zero to confidently building Python projects for AI. No prior experience needed. This handbook accompanies the [Complete Python for AI Course on YouTube](https://youtu.be/ygXn5nV5qFc), giving you everything in written form with extra details, code snippets you can copy, and reference materials to come back to. No programming experience required Python specifically for AI development Practice with real code examples ## What you'll learn Master the Python fundamentals essential for AI development: Master VS Code, Git, and the exact workflow used in real AI companies Variables, functions, APIs, and everything you need for AI development Apply what you learn to create real AI-powered applications ## Start learning Meet your instructor and start learning Follow along with the video course # AI assistants Source: https://python.datalumina.com/introduction/ai-assistants Use AI tools to learn Python faster ## Learning with AI assistants AI tools can accelerate your Python learning when used correctly. Here's how to use them effectively. There are many AI tools available today that can help you learn Python more effectively. Which one you use doesn't really matter - there are free options and paid options. Some are simple chat interfaces where you can ask questions. Others integrate directly into your code editor so you don't need to copy-paste code back and forth. Pick a tool you already have or are familiar with. Explore paid options if you have the budget. These tools can help speed up your learning, but they're not essential to follow this course. ## Best tools for learning General coding help and explanations Complex problem solving and debugging Code completion in your editor AI-powered code editor ## How to ask for help **Bad prompt:** ``` My code is not working, plz fix ``` **Good prompt:** ``` I'm learning Python and trying to create a list of numbers from 1 to 10. My code: numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10] Is there a more efficient way? ``` ## Effective strategies "Explain Python functions in simple terms" Share your code and the exact error message "Show me 3 ways to solve this problem" Test AI suggestions and ask follow-up questions AI assistants are tools to enhance learning, not replace it. The goal is understanding, not just working code. ## Create your personal Python tutor Get a customized AI tutor that follows the Learn Python for AI curriculum. Use this system prompt: ``` You are a patient Python tutor specializing in teaching beginners Python for AI development. Follow these guidelines: TEACHING APPROACH: - Explain concepts simply, as if to someone who has never coded before - Focus on practical understanding over theoretical knowledge - Use everyday analogies to explain programming concepts - Build confidence by celebrating small wins RESPONSE STRUCTURE: 1. First, acknowledge what the student is trying to do 2. Explain any errors in simple terms 3. Provide a corrected solution with clear comments 4. Explain why this approach works 5. Suggest one next step to build on their learning CODE STYLE: - Write clean, simple Python code - Add comments explaining what each line does - Use descriptive variable names - Keep examples under 10 lines when possible IMPORTANT RULES: - Never provide solutions without explanations - If asked to "just fix it," still explain what was wrong and why - Encourage students to understand errors as learning opportunities - When students are stuck, guide them with questions rather than immediate answers Remember: The goal is understanding, not just working code. Every interaction should build the student's confidence and skills. ``` **Requirements:** ChatGPT Plus (\$20/month) 1. Open ChatGPT and click **Explore GPTs** 2. Click **Create** 3. In the **Configure** tab, paste the prompt above in the Instructions field 4. Name it "Python Tutor" 5. Save visibility as **Only me** [View official documentation](https://help.openai.com/en/articles/8554397-creating-a-gpt) **Requirements:** Claude Pro (\$20/month) 1. Click **Projects** in the sidebar 2. Click **Create project** 3. Name it "Python Tutor" 4. Click **Create project** to start 5. Paste the prompt in **Set project instructions** [View official documentation](https://support.anthropic.com/en/articles/9517075-what-are-projects) **No subscription required** 1. Open ChatGPT or Claude 2. Start a new conversation 3. Paste the entire prompt above 4. Add your Python question after the prompt 5. The AI will follow the tutor guidelines **Note:** You'll need to paste the prompt at the start of each new conversation ## Ready to start coding? Set up your Python development environment # How to follow this course Source: https://python.datalumina.com/introduction/how-to-follow Get the most out of your learning experience ## Two ways to learn This course exists as both a YouTube video and this handbook. The video walks you through every concept in real-time. This handbook contains everything from the video plus additional details, code snippets, and deeper explanations. Keep this handbook open while watching. I'll reference specific sections you can jump to, you can copy code directly instead of typing from the video, and you can dive deeper into topics that interest you. ## Adjust to your pace Going too fast? Pause the video and read the handbook chapter carefully. Use ChatGPT to explain concepts in simpler terms - think of AI as your personal tutor available 24/7. Some concepts need multiple passes, that's normal. Going too slow? The YouTube video has timestamps for every section, so skip to what you need. Watch at 1.5x or 2x speed. Skim the handbook to decide what to focus on. ## About the code examples As we progress, you'll see increasingly complex code. The goal isn't to understand every single line immediately - it's exposure to what's possible. We start simple and build complexity over time. Real learning happens when you build your own projects, not just from watching. If you see a large code example and think "this is too much," that's okay. You're building foundations, and gaps will fill in as you practice. ## Use AI to learn faster ChatGPT and other AI assistants are incredibly powerful for learning: ``` Example prompts: "Explain this Python code in simple terms: [paste code]" "What does this error mean? [paste error message]" "Show me 3 different ways to solve this problem in Python" ``` ## This handbook stays updated Unlike the video which is fixed, this handbook gets updated regularly. If something doesn't work in the video (outdated syntax, changed tools), check here first. When students find issues, I update these docs so everyone benefits. ## How to approach this course Watch actively and code along. Make mistakes and fix them. Use the handbook to go deeper and copy code. Ask AI when stuck. After each major section, try building something similar on your own. Accept that you don't need to master everything before moving forward - understanding deepens with practice. ## Ready to dive in? Discover why Python dominates AI development # Is this for you? Source: https://python.datalumina.com/introduction/is-this-for-you Find out if this course matches your goals ## Who this is for This course works whether you've never written a line of code or you're coming from another programming language. We start from absolute zero and build up systematically, but move quickly enough that experienced programmers won't get bored. The key difference: you'll learn Python with professional tools and workflows from day one. Not simplified "beginner" versions you'll have to unlearn later. The same setup used in real companies. ## This course is for you if: You want to build AI applications and need Python skills to make that happen. You prefer learning by doing rather than spending hours on theory. You're ready to install software, write code, and build real projects. ## This course is NOT for you if: You want a slow, exhaustive reference covering every Python feature. This course is focused and practical - we teach what you need for AI development, not everything Python can do. If you're looking for casual hobby-level coding without proper tooling, this might feel more structured than you want. ## Ready to start? Learn the best way to approach this course # Course welcome Source: https://python.datalumina.com/introduction/welcome Meet your instructor and course overview ## Welcome to Python for AI I'm [Dave Ebbelaar](https://www.youtube.com/@daveebbelaar?sub_confirmation=1), and I'll be your guide on this journey into Python and AI development. I started learning Python in 2013 when I began my bachelor's in Artificial Intelligence. Today, I have over a decade of Python experience and have taught this language to over 30,000 students through my courses and YouTube channel. But it didn't start smoothly. I actually *failed* my first Python class in uni. That experience taught me something crucial: there are two parts to learning Python. First, there's the syntax - how to write the code. Python is quite easy here; you can almost write it like plain English, and AI assistants can help with any syntax questions. The second part is what most courses skip: your workflow. What tools do you use? How do you set them up? How do you start projects, save files, debug code, and structure your work? These skills are just as important as the code itself. When you understand your workflow, your learning accelerates dramatically. Combine that with AI tools, and you'll progress faster than ever before. This is the course I wish I had 12 years ago. After running an AI software development company for five years and completing over 50 projects across industries, I'm bringing all that experience to help you learn effectively. ## What's next? Find out if this course matches your goals # Why Python Source: https://python.datalumina.com/introduction/why-python The perfect language for AI development ## The best choice for AI Python is the dominant language in AI research and development: OpenAI, Google, Anthropic (and many others) use Python heavily for prototyping, experimentation, and tooling around their LLMs. It has also been the backbone of modern machine learning, powering the entire ecosystem of frameworks like TensorFlow, PyTorch, scikit-learn, and XGBoost – the tools that made deep learning and AI breakthroughs possible in the first place. ## Python dominates AI Python reads almost like English TensorFlow, PyTorch, scikit-learn built-in Used by every major AI company Millions of developers and resources ## Simple yet powerful Compare Python to other languages: ```python theme={null} # Python: Calculate average numbers = [10, 20, 30, 40, 50] average = sum(numbers) / len(numbers) print(f"Average: {average}") ``` ```java theme={null} // Java: Same task, more complexity public class Average { public static void main(String[] args) { int[] numbers = {10, 20, 30, 40, 50}; int sum = 0; for (int num : numbers) { sum += num; } double average = (double) sum / numbers.length; System.out.println("Average: " + average); } } ``` ## The best language to learn AI has created many opportunities in the job market: * **High demand**: Python AI developers earn \$130,000+ starting salaries * **Remote work**: Code from anywhere in the world * **Growing field**: 40% annual growth in AI jobs * **Creative freedom**: Build things impossible before ## Essential for AI work Every AI application uses Python: Built with Python using transformers and neural networks Image recognition and processing with OpenCV and PyTorch Process millions of data points with pandas and NumPy Create intelligent systems with scikit-learn and TensorFlow ## Ready to start? Learn how AI tools accelerate your Python learning # Import packages Source: https://python.datalumina.com/libraries-apis/importing-modules Use Python packages and libraries ## Using packages Python packages add new functionality to your programs. There are two types: * **Built-in**: Come with Python (no installation needed) * **External**: Need to install first with pip ## Understanding the terminology Let's clarify what these terms mean: * **Module**: A single Python file (like `math.py`) * **Package**: A folder containing multiple modules * **Function**: A reusable block of code (like `print()` or `sqrt()`) * **Class**: A blueprint for creating objects (we'll cover this later) Think of it like this: * A **module** is like a toolbox * A **package** is like a garage with multiple toolboxes * A **function** is like a specific tool (hammer, screwdriver) * A **class** is like a blueprint for building tools ## Import patterns explained ```python theme={null} # Pattern 1: Import the whole module import math # Now use: math.sqrt(16) # Pattern 2: Import specific items from a module from math import sqrt, pi # Now use: sqrt(16) ``` What's happening: * `import math` - brings in the entire math toolbox * `from math import sqrt` - takes just the sqrt tool from the math toolbox ## Built-in modules Python includes many useful modules: ```python theme={null} # Import entire module import random # Use module functions number = random.randint(1, 10) choice = random.choice(["apple", "banana", "orange"]) ``` ### Common built-in modules ```python theme={null} # Date and time import datetime today = datetime.date.today() print(today) # 2024-01-15 # Operating system import os current_dir = os.getcwd() print(current_dir) # JSON data import json data = {"name": "Alice", "age": 30} json_string = json.dumps(data) ``` ## Import methods Different ways to import: ```python theme={null} # Import entire module import math result = math.sqrt(16) # Import specific functions from math import sqrt, pi result = sqrt(16) circle_area = pi * radius ** 2 # Import with alias import pandas as pd df = pd.DataFrame(data) # Import everything (avoid this!) from math import * ``` Avoid `from module import *` as it can cause naming conflicts and makes code harder to understand. ## Installing packages External packages need installation: ```bash theme={null} # Install a package pip install requests # Install specific version pip install requests==2.28.0 # Install multiple packages pip install pandas numpy matplotlib ``` Always ensure your virtual environment is activated before installing! This is the #1 source of import errors. If you get "ModuleNotFoundError" after installing, you probably installed to the wrong environment. [Learn more about virtual environments](/getting-started/virtual-environments). ## Sharing your project: requirements.txt When you share your Python project, others need to know which packages to install. The standard way is using a `requirements.txt` file: ### Creating requirements.txt List all your project's packages: ```bash theme={null} pip freeze > requirements.txt ``` This creates a file like: ``` certifi==2024.2.2 charset-normalizer==3.3.2 idna==3.6 requests==2.31.0 urllib3==2.2.0 ``` ### Installing from requirements.txt When someone gets your project, they run: ```bash theme={null} pip install -r requirements.txt ``` This installs all the packages at once! Later in the course, we'll learn about `uv` - a modern, faster alternative to pip that makes package management even easier. ## Using external packages After installation, import and use: ```python theme={null} # Web requests import requests response = requests.get("https://api.example.com/data") data = response.json() # Data analysis import pandas as pd # Create a simple DataFrame data = { 'name': ['Alice', 'Bob', 'Charlie'], 'age': [25, 30, 35], 'city': ['NYC', 'LA', 'Chicago'] } df = pd.DataFrame(data) print(df) ``` Always use virtual environments for projects. They prevent package conflicts between different projects. ## Finding packages Where to find packages: * [PyPI](https://pypi.org) - Official Python package index * [Awesome Python](https://github.com/vinta/awesome-python) - Curated list * **ChatGPT** - Ask "What Python package should I use for \[task]?" - Great for recommendations and comparisons * Google "Python package for \[task]" ChatGPT is excellent for finding packages. Try asking: "What's the best Python package for reading Excel files?" or "Compare pandas vs polars for data analysis." It can explain which package to use and why. ## Common mistakes ```python theme={null} # Wrong - package not installed or venv not activated import pandas # ModuleNotFoundError # Right - install first # Run: pip install pandas import pandas ``` ```python theme={null} # Wrong - overwrites built-in import datetime datetime = "2024-01-01" # Now module is gone! # Right - use different names import datetime date_string = "2024-01-01" ``` ## What's next? Learn to connect to APIs and fetch data from the internet! Connect to online services # External tools Source: https://python.datalumina.com/libraries-apis/index Extend Python with packages ## Beyond built-in Python Python comes with many built-in functions, but its real power comes from external packages. These are pre-written code libraries that add new capabilities. ## What are packages really? Packages are just Python files containing code - typically combinations of functions (which you've learned) and classes (coming later). When you import a package, you're bringing that functionality into your project. Two types of packages: * **Built-in**: Come with Python installation (already in your environment) * **External**: Downloaded from the internet into your virtual environment folder ## Python's ecosystem Python has packages for everything: * **Web scraping**: Extract data from websites * **Data analysis**: Process spreadsheets and databases * **AI/ML**: Build intelligent applications * **APIs**: Connect to online services * **Automation**: Control your computer ## What you'll learn Use external code Connect to services Process data efficiently ## Package examples Here are packages you'll likely use: * `requests` - Make web requests * `pandas` - Work with data tables * `beautifulsoup4` - Parse HTML * `openai` - Use AI models * `python-dotenv` - Manage secrets When you need to do something, search "Python package for \[task]" and you'll likely find options. ## Let's begin! Start by learning how to import and use packages. Add new capabilities # Working with APIs Source: https://python.datalumina.com/libraries-apis/working-with-apis Pull data from web services ## What is an API? An API (Application Programming Interface) is like a waiter at a restaurant. You tell it what you want, and it brings you the data. But APIs do more than just fetch information. They're the bridges that connect your code to other systems. With APIs, you can: * Pull customer data from your CRM (Salesforce, HubSpot) * Get order information from Shopify or WooCommerce * Send messages through Slack or email services * Use AI models from OpenAI or Anthropic In the context of AI, APIs are essential. They let you connect AI capabilities to real business data and systems. ## Your first API call Let's get real weather data using a free weather API: ```python theme={null} import requests # We need coordinates to get weather data latitude = 48.85 # Paris latitude longitude = 2.35 # Paris longitude # Build the API URL with our parameters url = f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m" # Make the request response = requests.get(url) data = response.json() print(data) ``` First install requests: `pip install requests` ## Understanding the response The API sends back data in JSON format (like a Python dictionary): ```python theme={null} { 'latitude': 48.84, 'longitude': 2.36, 'timezone': 'GMT', 'elevation': 46.0, 'current_units': { 'temperature_2m': '°C' }, 'current': { 'time': '2025-08-01T08:30', 'temperature_2m': 20.0 } } ``` The temperature is nested inside `current`, so to get it: ```python theme={null} temperature = data['current']['temperature_2m'] print(f"Temperature in Paris: {temperature}°C") # Output: Temperature in Paris: 20.0°C ``` **What is JSON?** JSON (JavaScript Object Notation) is just a way to structure data, similar to CSV or Excel files. While CSV stores data in rows and columns, JSON uses key-value pairs like Python dictionaries. ## Extract what you need Now you can pull out specific information: ```python theme={null} import requests def get_weather(latitude, longitude): response = requests.get(f"https://api.open-meteo.com/v1/forecast?latitude={latitude}&longitude={longitude}¤t=temperature_2m,wind_speed_10m") data = response.json() return data['current']['temperature_2m'] # Get temperature for different cities paris_temp = get_weather(48.85, 2.35) london_temp = get_weather(51.50, -0.12) tokyo_temp = get_weather(35.68, 139.69) print(f"Paris: {paris_temp}°C") print(f"London: {london_temp}°C") print(f"Tokyo: {tokyo_temp}°C") ``` ## How it works 1. **You send a request** to the API's URL with parameters (like coordinates) 2. **The API processes** your request and finds the data 3. **You receive JSON data** back with the information 4. **You extract** the specific parts you need The pattern is always the same: connect to an API, send requests, get data back, use it in your code. APIs are how modern software talks to each other. Process data efficiently with pandas # Working with data Source: https://python.datalumina.com/libraries-apis/working-with-data Analyze and visualize data from APIs ## Building on APIs Let's take the weather API from the previous page and create something useful. We'll get weather data for the past 7 days, analyze it, visualize it, and save it. This brings together everything you've learned: APIs, data processing, file handling, and visualization. Install required libraries: `pip install requests pandas matplotlib` ## Get 7 days of weather The Open-Meteo API can give us historical data: ```python theme={null} import requests from datetime import datetime, timedelta # Calculate dates today = datetime.now() week_ago = today - timedelta(days=7) # Format dates for API (YYYY-MM-DD) start_date = week_ago.strftime("%Y-%m-%d") end_date = today.strftime("%Y-%m-%d") # Get Paris weather for past week url = f"https://api.open-meteo.com/v1/forecast?latitude=48.85&longitude=2.35&start_date={start_date}&end_date={end_date}&daily=temperature_2m_max,temperature_2m_min" response = requests.get(url) data = response.json() print(data) ``` ## Load into pandas Now let's organize this data: ```python theme={null} import pandas as pd # Extract the daily data daily_data = data['daily'] # Create a DataFrame df = pd.DataFrame({ 'date': daily_data['time'], 'max_temp': daily_data['temperature_2m_max'], 'min_temp': daily_data['temperature_2m_min'] }) # Convert date strings to datetime df['date'] = pd.to_datetime(df['date']) print(df) ``` Output: ``` date max_temp min_temp 0 2024-01-08 12.3 5.1 1 2024-01-09 11.8 4.2 2 2024-01-10 13.5 6.0 ... ``` ## Visualize the data Create a simple line chart: ```python theme={null} import matplotlib.pyplot as plt # Create the plot plt.figure(figsize=(10, 6)) plt.plot(df['date'], df['max_temp'], marker='o', label='Max Temp') plt.plot(df['date'], df['min_temp'], marker='o', label='Min Temp') # Add labels and title plt.xlabel('Date') plt.ylabel('Temperature (°C)') plt.title('Paris Weather - Past 7 Days') plt.legend() # Rotate x-axis labels for readability plt.xticks(rotation=45) plt.tight_layout() # Save the plot plt.savefig('weather_chart.png') plt.show() ``` ## Save to CSV Let's save our data for later use: ```python theme={null} import os # Create data folder if it doesn't exist if not os.path.exists('data'): os.makedirs('data') # Save to CSV df.to_csv('data/paris_weather.csv', index=False) print("Data saved to data/paris_weather.csv") ``` ## Complete example Here's everything together: ```python theme={null} import requests import pandas as pd import matplotlib.pyplot as plt from datetime import datetime, timedelta import os # 1. Get weather data today = datetime.now() week_ago = today - timedelta(days=7) start_date = week_ago.strftime("%Y-%m-%d") end_date = today.strftime("%Y-%m-%d") url = f"https://api.open-meteo.com/v1/forecast?latitude=48.85&longitude=2.35&start_date={start_date}&end_date={end_date}&daily=temperature_2m_max,temperature_2m_min" response = requests.get(url) data = response.json() # 2. Process with pandas df = pd.DataFrame({ 'date': pd.to_datetime(data['daily']['time']), 'max_temp': data['daily']['temperature_2m_max'], 'min_temp': data['daily']['temperature_2m_min'] }) # 3. Calculate average df['avg_temp'] = (df['max_temp'] + df['min_temp']) / 2 # 4. Create visualization plt.figure(figsize=(10, 6)) plt.plot(df['date'], df['max_temp'], 'r-o', label='Max') plt.plot(df['date'], df['min_temp'], 'b-o', label='Min') plt.plot(df['date'], df['avg_temp'], 'g--', label='Average') plt.xlabel('Date') plt.ylabel('Temperature (°C)') plt.title('Paris Weather - Past Week') plt.legend() plt.grid(True, alpha=0.3) plt.xticks(rotation=45) plt.tight_layout() # 5. Save everything if not os.path.exists('data'): os.makedirs('data') plt.savefig('data/weather_chart.png') df.to_csv('data/paris_weather.csv', index=False) print(f"Average temperature: {df['avg_temp'].mean():.1f}°C") print("Files saved in 'data' folder") ``` ## What you've accomplished Look at what you just did: * Connected to a real API * Worked with dates and time * Processed data with pandas * Created a visualization * Handled files and folders * Saved your results This is exactly how data analysis works in the real world! Try modifying the code to get weather for your city. Find your coordinates at [latlong.net](https://www.latlong.net/). ## Next steps Ready to organize your code like a pro? Let's learn proper project structure! Build real programs with proper structure # Continue learning Source: https://python.datalumina.com/next-steps/ai-agents Build AI agents in Python ## You made it to the end Thank you for completing this course. I really appreciate it. If you found it helpful, make sure to leave a like and a comment on YouTube. It helps others discover the course too. This is the course I wish I had 12 years ago. I hope it's given you the clarity and confidence to take your next steps. ## Ready to build AI agents? Now that you have a solid Python foundation, you're ready to build real AI applications. **If you're serious about learning AI, this was just the starting point.** Continue your journey in the **Datalumina Academy**, where you'll find: * This entire Python course with bonus videos * Next steps to build AI agents in Python * Structured learning paths from foundations to advanced AI systems Access bonus videos plus my FREE AI agent course ### Don't have access yet? Download the course resources to get your invite to the academy: Get your resources and academy access With this foundation, you're ready to build great things that make the world a better place. # Course summary Source: https://python.datalumina.com/next-steps/course-summary Quick recap of what you've learned ## Congratulations 🎉 You've completed the course! You now have a solid foundation in Python and the confidence to work with Python in AI applications. Celebration ## What you've learned You started with no Python experience. Now you can write real programs that solve actual problems. * Work with variables, data types, and control flow * Organize code with functions and data structures * Set up Python environments and manage dependencies * Use Git, GitHub, and professional developer tools * Connect to APIs, handle errors, and work with files You're no longer a beginner. You have the skills to work confidently with Python and tackle real projects. ## Help spread the word Help others find this course by leaving a comment # Leave feedback Source: https://python.datalumina.com/next-steps/feedback Help others find this course ## Help spread the word ❤️ This course is completely free. If you enjoyed it, here's how you can help others discover it. Share what you learned or what you're building next. Your comment helps the YouTube algorithm show this course to more people who want to learn Python. Like the video and leave a comment about your experience ## That's all I ask By liking the video and leaving a comment, you help this free course reach more beginners. That's my only ask if you found value in what you learned. ## Ready for AI agents? Build AI agents in Python - the perfect follow-up course # Practical Python Source: https://python.datalumina.com/practical-python/index Build real programs with proper structure ## From scripts to programs You've learned the building blocks. Now let's put them together into organized, maintainable programs. In this section, you'll learn how real Python projects are structured and how to work with files, organize your code, and build programs that actually do useful things. ## What you'll build Throughout this section, you'll build a sales analysis project step by step: 1. **Set up a project** - Create organized folder structure 2. **Understand paths** - Learn how Python finds your files 3. **Work with data** - Read CSV files and save as JSON 4. **Organize code** - Split code into reusable functions By the end, you'll have a complete data analysis program and understand how real Python projects work. Create your first organized project Understand how Python finds files Read and write data files Create reusable functions # Organizing code Source: https://python.datalumina.com/practical-python/organizing-code Split code into reusable functions ## Why organize your code? As your scripts grow, they become harder to read and maintain. The solution? Split your code into functions and separate files. Benefits: * **Reusable** - Write once, use many times * **Readable** - Main script stays simple and clear * **Testable** - Easy to test individual functions ## Creating helper functions Let's create simple helper functions for our sales analysis. In your `sales-analysis` folder, create a new file called `helpers.py`: ```python theme={null} # helpers.py def calculate_total(quantity, price): """Calculate total for a single item""" return quantity * price def format_currency(amount): """Format number as currency""" return f"${amount:,.2f}" ``` The `:.2f` in the format string rounds floating point numbers to 2 decimal places - perfect for displaying money! That's it! Two simple functions that do one thing each. ## Using your functions Now update `analyzer.py` to use these helpers: ```python theme={null} # analyzer.py import pandas as pd from helpers import calculate_total, format_currency # Read data df = pd.read_csv('data/sales.csv') # Calculate total for each row totals = [] for index, row in df.iterrows(): total = calculate_total(row['quantity'], row['price']) totals.append(total) # Add totals to our data df['total'] = totals # Display with formatted totals print("Sales Data:") for index, row in df.iterrows(): formatted_total = format_currency(row['total']) print(f"{row['product']}: {formatted_total}") # Show grand total grand_total = df['total'].sum() formatted_grand_total = format_currency(grand_total) print(f"\nGrand Total: {formatted_grand_total}") ``` ## How imports work When you write `from helpers import calculate_total`: 1. Python looks for `helpers.py` in the same folder 2. It runs that file and makes the functions available 3. You can now use `calculate_total()` directly The file must be in the same folder for this simple import to work. We covered more complex imports in the Python paths section. ## What you've accomplished Look at what you've built! You started with a single Python file and now have: * An organized project structure * Understanding of how Python finds files * Code that reads real data and saves results * Reusable functions in separate files This is how real Python projects work. You're ready to build bigger things! Handle errors gracefully in your code # Project structure Source: https://python.datalumina.com/practical-python/project-structure Organize your Python projects ## Working with multiple files So far, you've been writing single Python files. But real projects have multiple files, folders, and resources. Good organization makes your code easier to understand and maintain. Let's organize your existing `python-for-ai` workspace with a proper structure. ## Organize your workspace You already have a `python-for-ai` workspace from the beginning of the course. Let's create a folder for this project: 1. Open your `python-for-ai` workspace in VS Code 2. Create a `sales-analysis` folder 3. Inside `sales-analysis`, create these subfolders: ``` python-for-ai/ ├── hello.py # Your existing practice file └── sales-analysis/ # New project folder ├── data/ # CSV files and data └── output/ # Generated files ``` Create folders in VS Code by right-clicking in the Explorer panel and selecting "New Folder", or click the new folder icon at the top of the Explorer. ## Create the data file Inside your `sales-analysis/data` folder, create a file called `sales.csv`: ```csv theme={null} date,product,quantity,price 2024-01-01,Laptop,2,999.99 2024-01-01,Mouse,5,29.99 2024-01-02,Keyboard,3,79.99 2024-01-02,Monitor,1,299.99 2024-01-03,Laptop,1,999.99 2024-01-03,Mouse,10,29.99 2024-01-04,Keyboard,2,79.99 2024-01-05,Monitor,2,299.99 ``` Copy and paste this data into a new file called `sales.csv` in your `data` folder. Make sure the file extension is `.csv`, not `.txt`. ## Understanding file paths When your code needs to find files, you need to understand paths: ```python theme={null} # When your script runs from sales-analysis folder "data/sales.csv" # Look in the data subfolder "output/report.json" # Save to the output subfolder # Your project structure # python-for-ai/ # └── sales-analysis/ # ├── analyzer.py <- Your script is here # ├── data/sales.csv <- Your data is here # └── output/ <- Results go here ``` ## Create your first script In the `sales-analysis` folder (not in a subfolder), create `analyzer.py`: ```python theme={null} import os # Check if we're in the right place print("Current directory:", os.getcwd()) # Check if our data file exists data_path = "data/sales.csv" if os.path.exists(data_path): print(f"✅ Found {data_path}") else: print(f"❌ Cannot find {data_path}") print("Make sure you're running from the sales-analysis folder!") ``` ## Running your code In VS Code, you have two simple ways to run Python code: ### Option 1: The play button 1. Open `analyzer.py` in VS Code 2. Click the ▶️ (play) button in the top right 3. The code runs and shows output in the terminal below ### Option 2: Interactive mode (recommended) 1. Open `analyzer.py` in VS Code 2. Select the code you want to run (or place cursor on a line) 3. Press **Shift+Enter** 4. Code runs in the interactive window with instant feedback Interactive mode (Shift+Enter) is great for testing code step by step. You can run one line at a time and see results immediately! By keeping `analyzer.py` in the same folder as `data` and `output`, the file paths stay simple and work with both the play button and interactive mode. ## Best practices 1. **Keep data separate** - Don't mix code and data files 2. **Use clear names** - `data` for input files, `output` for results 3. **Simple structure** - Keep your main script at the project level 4. **Test as you go** - Use Shift+Enter to run code step by step Understand how Python finds files # Python paths Source: https://python.datalumina.com/practical-python/python-paths Understanding how Python finds files ## The most confusing part of Python Understanding paths is probably the most confusing part when starting with Python. You'll make mistakes with file paths and imports, and that's totally fine. That's how everyone learns. This page gives you a quick introduction. Some parts might not be completely clear right now, but as you practice, it will click. Come back to this page when you run into path issues - it happens to everyone! ## The mental model When working with multiple files, always think about two things: 1. **Where am I?** - What folder is my Python script in? 2. **Where do I want to go?** - What file or module do I need? Then navigate: * **Going down** into subfolders: Use `/` for files, `.` for imports * **Going up** to parent folders: Use `../` for files, add to sys.path for imports * **Same folder**: Just use the filename ```python theme={null} # From script.py, accessing different locations: "data/sales.csv" # Down into data folder "../config.json" # Up one level "helper.py" # Same folder # For imports: import helper # Same folder - no path needed! import data.processor # Down into data folder # Parent folder imports need sys.path: import sys sys.path.append("..") # Add parent to path import parent_module # Now you can import ``` ## The simple rule When Python runs, it has a "current working directory" - the folder it's currently in. All file paths start from there. ```python theme={null} import os # See where Python is right now print(os.getcwd()) ``` Try this - it shows you exactly where Python is looking for files. ## Finding your files Let's say you have this structure: ``` my-project/ ├── script.py ├── data.txt └── folder/ └── other.txt ``` If you run `script.py`: ```python theme={null} # Python can find these: open("data.txt") # Same folder open("folder/other.txt") # Subfolder # Python CAN'T find these (they don't exist from here): open("other.txt") # Wrong! It's in a subfolder open("../parent.txt") # Looking in parent folder ``` ## Files vs modules - key difference Python handles regular files and Python modules differently: **Regular files (CSV, TXT, JSON):** * Use `open()` or file-reading functions * Need the exact path from your current directory * Use forward slashes: `data/sales.csv` ```python theme={null} # Reading a CSV file - needs exact path with open("data/sales.csv", "r") as file: content = file.read() ``` **Python modules (importing code):** * Use `import` statements * Python searches in multiple locations (sys.path) * Use dots instead of slashes: `folder.module` ```python theme={null} # Importing a module - Python searches for it import mymodule # Looks for mymodule.py from folder.utils import helper # Looks for folder/utils.py ``` ## How Python finds modules Python looks for modules (other .py files) in specific places. You can see these places: ```python theme={null} import sys print(sys.path) # List of folders Python checks ``` The list includes: 1. The folder containing your script 2. Python's built-in library folders 3. Installed packages ## Adding your own folders Sometimes you need Python to look in additional places: ```python theme={null} import sys # Add a folder to Python's search path sys.path.append("/path/to/my/folder") # Now you can import from that folder import mymodule ``` Common example - importing from a parent folder: ```python theme={null} import sys import os # Go up one level from current script parent = os.path.dirname(os.path.dirname(__file__)) sys.path.append(parent) ``` ## Common mistakes This happens when Python can't find your file. The file path is wrong or you're running from a different folder than expected. ```python theme={null} # Debug it: import os print("Looking in:", os.getcwd()) print("Files available:", os.listdir()) ``` Fix: Use the correct path from your current directory, or use absolute paths. Python can't find the module you're trying to import. It's not in any of the folders Python searches. ```python theme={null} # See where Python looks: import sys print("Python searches in:", sys.path) ``` Fix: Make sure the module is in one of those folders, or add its folder to sys.path. Remember: regular files use paths with slashes, Python modules use dots. ```python theme={null} # Wrong: import data/helpers # SyntaxError! # Right: import data.helpers # For data/helpers.py ``` Your script works in VS Code but not in terminal? You're probably in a different folder. ```python theme={null} # Always check first: import os print("Running from:", os.getcwd()) ``` Fix: Navigate to the right folder in terminal, or use the VS Code play button. Windows uses backslashes, but Mac/Linux use forward slashes. Use forward slashes - they work everywhere! ```python theme={null} # Works everywhere: "data/file.csv" # Only works on Windows: "data\\file.csv" ``` ## Keep it simple Remember, everyone struggles with paths at first. For now: * Keep related files in the same folder * Use the VS Code play button (it's predictable) * When confused, print `os.getcwd()` to see where you are * Come back to this page when you hit path errors The mental model: Know where you are, know where you want to go, then navigate with `/` for files. For imports, same folder needs no path, subfolders use `.`, parent folders need sys.path. Apply these concepts to read and write files # Working with files Source: https://python.datalumina.com/practical-python/working-with-files Read, process, and write data files ## Files in AI projects When working with Python for AI, you'll constantly work with data files. Your data might come as: * **CSV files** - Spreadsheet data from Excel or databases * **JSON files** - API responses and configuration data * **XML files** - Structured data from various systems * **Text files** - Raw text for processing * **Parquet files** - Efficient data storage format The good news? Python has excellent libraries for all of these. ## Common libraries for files Each file type has specialized libraries: **CSV files:** * `pandas` - Best for data analysis (recommended) * `csv` module - Built-in, for simple operations **JSON files:** * `json` module - Built-in, handles all JSON operations * `pandas` - Can read/write JSON with DataFrames **Other formats:** * `xml.etree` - Built-in XML parsing * `openpyxl` - Excel files (.xlsx) * `PyPDF2` - PDF files ## Working with our sales data Let's work with our CSV file and convert it to different formats. First, install pandas: ```bash theme={null} pip install pandas ``` If you get an error, try `pip3 install pandas` or install it through VS Code's terminal. Update your `analyzer.py`: ```python theme={null} import pandas as pd import json import os # Read the CSV file df = pd.read_csv('data/sales.csv') print("CSV Data:") print(df) print(f"\nShape: {df.shape[0]} rows, {df.shape[1]} columns") # Quick operation: calculate total for each row df['total'] = df['quantity'] * df['price'] print("\nWith totals:") print(df) # Create output directory os.makedirs('output', exist_ok=True) # Save as different formats # 1. JSON format (good for web APIs) df.to_json('output/sales_data.json', orient='records', indent=2) # 2. Excel format (good for sharing) df.to_excel('output/sales_data.xlsx', index=False) # 3. Updated CSV (with our new total column) df.to_csv('output/sales_with_totals.csv', index=False) print("\nFiles saved:") print("- output/sales_data.json") print("- output/sales_data.xlsx") print("- output/sales_with_totals.csv") ``` ## File format comparison Different formats have different uses: ```python theme={null} # JSON - Great for APIs and web applications { "date": "2024-01-01", "product": "Laptop", "quantity": 2, "price": 999.99 } # CSV - Simple, universal, good for data analysis date,product,quantity,price 2024-01-01,Laptop,2,999.99 # Excel - Feature-rich, good for business users # (Binary format with formatting, formulas, etc.) ``` ## Loading different file types Here's how to load various formats: ```python theme={null} # CSV df = pd.read_csv('data/file.csv') # JSON df = pd.read_json('data/file.json') # or for simple JSON: with open('data/config.json', 'r') as f: data = json.load(f) # Excel df = pd.read_excel('data/file.xlsx') # Text files with open('data/file.txt', 'r') as f: text = f.read() ``` ## Learn more To dive deeper into file handling: * [Pandas documentation](https://pandas.pydata.org/docs/) - Comprehensive data handling * [Python JSON module](https://docs.python.org/3/library/json.html) - Official JSON docs * [Real Python file I/O](https://realpython.com/working-with-files-in-python/) - Detailed tutorial * [CSV module docs](https://docs.python.org/3/library/csv.html) - Built-in CSV handling Split your code into reusable functions # Formatting with Ruff Source: https://python.datalumina.com/tools/code-quality/index Automatically format and lint your Python code ## What is Ruff? Ruff is a modern Python tool that's incredibly fast and combines multiple tools in one: * **Linting** - Finding issues and potential errors * **Formatting** - Fixing code style automatically * **Import sorting** - Organizing imports cleanly It's beginner-friendly with clear error messages and works seamlessly with VS Code. A **linter** checks your code for style issues and potential errors. A **formatter** automatically fixes these issues for you. ## Install Ruff in VS Code 1. Open VS Code 2. Press `Ctrl+Shift+X` (Windows/Linux) or `Cmd+Shift+X` (Mac) 3. Search for "Ruff" 4. Install the official Ruff extension by Astral The Ruff extension replaces older tools like Pylint, Black, and isort. You only need this one extension. ## Enable format on save Let's make VS Code automatically format your code when you save: 1. Press `Ctrl+,` (Windows/Linux) or `Cmd+,` (Mac) to open settings 2. Search for "format on save" 3. Check the box for "Editor: Format On Save" 4. Search for "default formatter" 5. Set "Python > Formatting: Provider" to "Ruff" ## See it in action Here's messy code before formatting: ```python theme={null} import os def calculate_total(items): total=0 for item in items: total+=item['price']*item['quantity'] return total shopping_cart=[{'name':'apple','price':0.5,'quantity':6},{'name':'banana','price':0.3,'quantity':8}] print(calculate_total(shopping_cart)) ``` After saving with Ruff (automatic): ```python theme={null} import os def calculate_total(items): total = 0 for item in items: total += item["price"] * item["quantity"] return total shopping_cart = [ {"name": "apple", "price": 0.5, "quantity": 6}, {"name": "banana", "price": 0.3, "quantity": 8}, ] print(calculate_total(shopping_cart)) ``` Ruff automatically: * Separated imports * Added proper spacing * Fixed indentation * Made quotes consistent * Formatted the list for readability If formatting doesn't work on save, right-click in your Python file and select "Format Document". This should trigger Ruff manually. ## Common formatting rules Ruff follows Python's style guide (PEP 8) automatically: * 4 spaces for indentation * Spaces around operators (`x = 1`, not `x=1`) * Two blank lines between functions * Maximum line length of 88 characters You don't need to memorize these - Ruff handles them for you! ## Understanding linting errors Ruff will underline code issues in your editor: ```python theme={null} # Unused imports (Ruff warns you) import os import sys # Only using one print("Hello") ``` Hover over underlined code to see: * What the issue is * Why it matters * How to fix it Don't ignore linting warnings! They help you write better code and catch bugs early. ## What's next? With Ruff set up, your code will always look professional and follow best practices automatically. # Complete workflow Source: https://python.datalumina.com/tools/dependencies/complete-setup Start to finish setup ## New project checklist Follow these steps every time you start a new Python project. ## Step 1: Open terminal Open your terminal: * **Mac**: Terminal app or iTerm * **Windows**: Terminal, Command Prompt, or PowerShell ## Step 2: Navigate to your projects folder ```bash theme={null} # Go to your projects directory cd ~/Documents/Projects # Mac cd C:\Users\YourName\Documents\Projects # Windows ``` Create a dedicated folder for all your Python projects. This keeps things organized! ## Step 3: Create the project Use uv to create your project: ```bash theme={null} uv init my-awesome-project ``` **What happens:** * Creates a new folder `my-awesome-project` * Creates `.gitignore` (Git will ignore `.venv`, `.env`, etc.) * Creates `.python-version` (specifies Python version) * Creates `pyproject.toml` (project configuration) * Creates `README.md` (project description) * Creates `main.py` (example file) **Initial structure:** ``` my-awesome-project/ ├── .gitignore # Git ignore rules ├── .python-version # Python version ├── pyproject.toml # Project config ├── README.md # Project description └── main.py # Example file ``` The `.venv` folder is created automatically when you run `uv add` to install your first package. Same with `uv.lock`. ## Step 4: Open in VS Code ```bash theme={null} # Enter the project folder cd my-awesome-project # Open in VS Code code . ``` **What happens:** * VS Code opens with your project * Python extension activates automatically * Virtual environment is detected If `code .` doesn't work, see the Git section for setup instructions. ## Step 5: Add packages Open terminal in VS Code (`` Ctrl+` ``): ```bash theme={null} # Add packages you need uv add requests uv add pandas numpy uv add python-dotenv # For interactive Python (optional) uv add ipykernel ``` **What happens:** * Packages download and install * `pyproject.toml` updates with dependencies * `uv.lock` locks exact versions ## Step 6: Test your setup Edit `main.py`: ```python theme={null} import requests from dotenv import load_dotenv import os # Load environment variables load_dotenv() # Test the setup print("✅ Packages imported successfully!") # Test environment variable api_key = os.environ.get("API_KEY", "not-set") print(f"✅ API_KEY: {api_key}") # Test requests response = requests.get("https://api.github.com") print(f"✅ GitHub API status: {response.status_code}") ``` Run it: ```bash theme={null} uv run python main.py ``` ## Step 7: Set up environment variables Create `.env` for secrets: ```bash theme={null} # .env API_KEY=your-secret-key-here DATABASE_URL=postgresql://localhost/mydb DEBUG=True ``` Create `.env.example` for others: ```bash theme={null} # .env.example API_KEY=your-api-key-here DATABASE_URL=your-database-url DEBUG=True ``` **Important**: `.env` is already in `.gitignore` - your secrets are safe! ## Step 8: Initialize Git ```bash theme={null} # Initialize Git repository git init # Add all files git add . # First commit git commit -m "Initial commit" ``` **What happens:** * Git starts tracking your files * All files except those in `.gitignore` are staged * Your first snapshot is saved ## Step 9: Create GitHub repository Create the repository directly from your terminal: ```bash theme={null} # Create private repository gh repo create my-awesome-project --private --source=. --remote=origin --push # Or create public repository gh repo create my-awesome-project --public --source=. --remote=origin --push ``` **What happens:** * Creates repository on GitHub * Sets up remote connection * Pushes your code automatically If you don't have GitHub CLI, install it: **Mac:** ```bash theme={null} brew install gh ``` **Windows:** ```bash theme={null} winget install --id GitHub.cli # Or download from cli.github.com ``` **Linux:** ```bash theme={null} # Debian/Ubuntu curl -fsSL https://cli.github.com/packages/githubcli-archive-keyring.gpg | sudo dd of=/usr/share/keyrings/githubcli-archive-keyring.gpg sudo chmod go+r /usr/share/keyrings/githubcli-archive-keyring.gpg echo "deb [arch=$(dpkg --print-architecture) signed-by=/usr/share/keyrings/githubcli-archive-keyring.gpg] https://cli.github.com/packages stable main" | sudo tee /etc/apt/sources.list.d/github-cli.list > /dev/null sudo apt update sudo apt install gh ``` After installing, authenticate with: ```bash theme={null} gh auth login ``` If you prefer the traditional way: 1. Go to [github.com](https://github.com) 2. Click **+** > **New repository** 3. Name it `my-awesome-project` 4. Choose Private or Public 5. **Don't** add any files 6. Click **Create repository** Then run: ```bash theme={null} git remote add origin https://github.com/YOUR-USERNAME/my-awesome-project.git git push -u origin main ``` **You're done!** Your project is now: * Set up locally with uv * Tracked by Git * Backed up on GitHub ## The daily workflow From here, your routine is: ```bash theme={null} # Make changes to your code... # Add packages as needed uv add some-package # Commit changes git add . git commit -m "Add new feature" # Push to GitHub git push ``` **Prefer clicking?** You can do all Git operations using VS Code's UI: * **Source Control panel** (Ctrl+Shift+G): Stage, commit, and push with clicks * **Status bar**: Shows branch and sync button * **Command Palette** (Ctrl+Shift+P): Type "Git" to see all commands See the Git & GitHub section for details! ## Quick reference ```bash theme={null} # Project setup (one time) uv init project-name cd project-name code . git init git add . git commit -m "Initial commit" gh repo create project-name --private --source=. --remote=origin --push # Daily development uv add package-name # Add packages uv run python script.py # Run code git add . # Stage changes git commit -m "message" # Commit git push # Push to GitHub ``` ## Pro tips 1. **Commit often** - Small commits are better than huge ones 2. **Write clear messages** - "Fix login bug" not "updates" 3. **Use .env** - Never hardcode secrets 4. **Keep it simple** - Don't over-engineer ## Commands summary Here's everything in one place: ```bash theme={null} # Setup (one time) uv init my-project cd my-project code . uv add requests pandas python-dotenv uv add --dev ipykernel echo "API_KEY=your-key" > .env git init git add . git commit -m "Initial commit" gh repo create my-project --private --source=. --remote=origin --push # Daily workflow uv add package-name # Add packages uv run python script.py # Run code git add . # Stage changes git commit -m "message" # Commit git push # Push to GitHub ``` ## What's next You've completed the Python fundamentals course. Continue your journey with these next steps: See what you've learned and continue with AI agents in Python # Modern Python Source: https://python.datalumina.com/tools/dependencies/index Next-level development with uv ## Why modern tools matter You've learned pip and virtual environments - that's great! But there's a better way. **Enter uv**: A modern Python package manager that's: * **10-100x faster** than pip * **Simpler** to use * **More reliable** * **All-in-one** tool ## The problem with pip Traditional Python development has pain points: * Slow package installation * Confusing virtual environment commands * Different tools for different tasks * Easy to mess up your environment ## What is uv? `uv` is a single tool that replaces: * pip (package installer) * venv (virtual environments) * pip-tools (dependency management) * pyenv (Python version management) Written in Rust, it's blazingly fast and just works. ## What you'll learn Speed comparison and benefits Create projects the modern way Start to finish project guide Once you try uv, you'll never go back to pip. It's that much better! # Why uv? Source: https://python.datalumina.com/tools/dependencies/uv-intro The future of Python packaging ## See the difference Let's install a package with pip vs uv: ### With pip (traditional) ```bash theme={null} pip install pandas # ⏱️ Takes 15-30 seconds ``` ### With uv (modern) ```bash theme={null} uv pip install pandas # ⚡ Takes 1-2 seconds ``` That's 10-30x faster! And it gets better. ## Real-world comparison Creating a new project: ```bash theme={null} # Create virtual environment python -m venv .venv # Activate it (different per OS!) # Windows: .venv\Scripts\activate # Mac/Linux: source .venv/bin/activate # Install packages pip install requests pandas numpy # Save dependencies pip freeze > requirements.txt ``` **Time**: \~45 seconds **Commands**: 4+ (varies by OS) ```bash theme={null} # Everything in one command uv init uv add requests pandas numpy ``` **Time**: \~3 seconds **Commands**: 2 ## Why is uv so fast? 1. **Written in Rust** - Compiled language, not interpreted Python 2. **Smart caching** - Reuses downloaded files intelligently 3. **Parallel downloads** - Gets multiple packages at once 4. **Better algorithms** - Optimized dependency resolution ## More than just speed ### One tool, not five Traditional Python: * `pip` for packages * `venv` for virtual environments * `pip-compile` for lock files * `pyenv` for Python versions * `pipx` for global tools With uv: * `uv` does it all ### It just works No more: * "Did I activate my venv?" * "Which Python am I using?" * "Why is this package conflicting?" uv handles it automatically. ### Modern features * **Lock files** - Exact reproducible installs * **Workspace support** - Multiple related projects * **Script running** - Built-in task runner * **Python management** - Install Python versions too ## Installing uv One command for any system: ```bash theme={null} curl -LsSf https://astral.sh/uv/install.sh | sh ``` ```powershell theme={null} powershell -c "irm https://astral.sh/uv/install.ps1 | iex" ``` After installation, restart your terminal. ## Quick commands Here's what you need to know: ```bash theme={null} # Create new project uv init my-project # Add packages uv add requests pandas # Install from existing project uv sync # Run Python uv run python script.py ``` ## Should you switch? **Yes, if you want:** * Faster development * Simpler commands * Less confusion * Modern tooling **Maybe wait if:** * You're in a team using pip * You have complex legacy setups * You're just starting (learn basics first) uv is backwards compatible - it can read requirements.txt and work with existing projects! ## What's next? Let's see uv in action by creating a real project. Create your first uv project # Using uv Source: https://python.datalumina.com/tools/dependencies/virtual-env Create projects the modern way ## Creating a new project Let's create a real project with uv: ```bash theme={null} # Create and enter project uv init ai-assistant cd ai-assistant ``` This creates: ``` ai-assistant/ ├── .gitignore # Git ignore file ├── .python-version # Python version for the project ├── pyproject.toml # Project configuration ├── README.md # Project readme └── main.py # Example script ``` The `.venv` folder and `uv.lock` file are created automatically when you first run `uv add` to install packages. ## Understanding pyproject.toml This is your project's configuration file: ```toml theme={null} [project] name = "ai-assistant" version = "0.1.0" description = "Add your description here" readme = "README.md" requires-python = ">=3.12" dependencies = [] ``` It replaces: * `requirements.txt` * `setup.py` * `setup.cfg` * Multiple config files One file to rule them all! ## Adding packages Add packages with `uv add`: ```bash theme={null} # Add a package uv add requests # Add multiple packages uv add pandas numpy matplotlib # Add development dependencies uv add --dev pytest black ``` Your `pyproject.toml` updates automatically: ```toml theme={null} [project] name = "ai-assistant" version = "0.1.0" description = "Add your description here" readme = "README.md" requires-python = ">=3.12" dependencies = [ "requests>=2.32.0", "pandas>=2.2.0", "numpy>=1.26.0", "matplotlib>=3.8.0", ] [tool.uv] dev-dependencies = [ "pytest>=8.0.0", "black>=24.0.0", ] ``` ## The lock file uv creates `uv.lock` - this locks exact versions: ``` # uv.lock (auto-generated) version = 1 requires-python = ">=3.12" [[package]] name = "requests" version = "2.32.3" dependencies = [ { name = "certifi" }, { name = "charset-normalizer" }, ... ] ``` This ensures everyone gets exactly the same packages. ## Running your code Three ways to run Python with uv: ```bash theme={null} # Method 1: uv run (recommended) uv run python main.py # Method 2: Activate venv (traditional) source .venv/bin/activate # Mac/Linux # or .venv\Scripts\activate # Windows # Method 3: Direct path .venv/bin/python main.py ``` `uv run` is recommended - it always uses the right Python! ## Common uv commands ```bash theme={null} # Create new project uv init project-name # Add packages uv add package-name # Remove packages uv remove package-name # Install all dependencies uv sync # Update packages uv add --upgrade package-name # Show installed packages uv pip list # Run Python scripts uv run python script.py ``` ## Working with existing projects Got a project with `requirements.txt`? No problem: ```bash theme={null} # Convert requirements.txt to pyproject.toml uv add -r requirements.txt # Or just install from requirements.txt uv pip install -r requirements.txt ``` ## Virtual environment details uv creates `.venv` automatically when you add packages: * Created on first `uv add` command * No activation needed with `uv run` * Always in project directory * Works with VS Code automatically * Already in `.gitignore` (uv adds it) ## Tips and tricks 1. **Global tools**: Install tools globally with uv ```bash theme={null} uv tool install black uv tool install mypy ``` 2. **Python versions**: uv can manage Python too ```bash theme={null} uv python install 3.12 uv python install 3.11 ``` 3. **Scripts**: Add custom commands ```toml theme={null} [project.scripts] start = "ai_assistant.main:run" test = "pytest tests/" ``` ## What's next? Ready to put it all together? Check out the complete project workflow! Start-to-finish project guide # Using .env files Source: https://python.datalumina.com/tools/environment/dotenv The easy way to manage secrets ## What is a .env file? A `.env` file is a simple text file that stores your environment variables. Instead of typing `export` commands, you write them once in a file. ## Basic setup ### 1. Install python-dotenv ```bash theme={null} pip install python-dotenv ``` ### 2. Create .env file Create a file named `.env` in your project: ``` # .env API_KEY=sk-1234567890abcdef DATABASE_URL=sqlite:///myapp.db DEBUG=True ``` ### 3. Load in Python ```python theme={null} from dotenv import load_dotenv import os # Load the .env file load_dotenv() # Now use your variables api_key = os.environ.get('API_KEY') debug = os.environ.get('DEBUG') print(f"API Key: {api_key}") print(f"Debug mode: {debug}") ``` That's it! Much easier than export commands. ## Critical: Add to .gitignore **Never commit .env files!** They contain secrets. Add to `.gitignore` immediately: ``` # .gitignore .env .venv/ __pycache__/ ``` ## Complete example Here's a real example with an API: ```python theme={null} # app.py from dotenv import load_dotenv import os import requests # Load environment variables load_dotenv() # Get API key API_KEY = os.environ.get('OPENAI_API_KEY') if not API_KEY: print("Please set OPENAI_API_KEY in .env file") exit(1) # Use the API headers = {"Authorization": f"Bearer {API_KEY}"} # Make your API calls... ``` Your `.env` file: ``` # .env OPENAI_API_KEY=sk-your-actual-key-here MODEL=gpt-3.5-turbo MAX_TOKENS=100 ``` ## Show others what they need Create `.env.example` (this one you DO commit): ``` # .env.example OPENAI_API_KEY=your-api-key-here MODEL=gpt-3.5-turbo MAX_TOKENS=100 ``` This shows other developers what variables they need without exposing your actual keys. ## Rules for .env files * One variable per line * No spaces around `=` * No quotes (unless part of the value) * Use `#` for comments * Always UPPERCASE names ## Common patterns ``` # API Keys OPENAI_API_KEY=sk-... GITHUB_TOKEN=ghp_... # Database DATABASE_URL=sqlite:///local.db # Settings DEBUG=True PORT=8000 LOG_LEVEL=INFO ``` ## Quick tips 1. **Load early**: Put `load_dotenv()` at the start of your program 2. **Use defaults**: `os.environ.get('PORT', '8000')` 3. **Check your .gitignore**: Make sure `.env` is listed 4. **Keep it simple**: Only put configuration that changes ## What's next? You now know how to manage secrets safely! Ready for modern Python tooling? Next-level Python development # Environment & secrets Source: https://python.datalumina.com/tools/environment/index Keep your API keys safe ## Never put secrets in your code When working with APIs or databases, you'll need: * API keys * Passwords * Connection strings Putting these directly in your code is dangerous - anyone can see them! ## The solution Environment variables let you keep secrets separate from your code. We'll learn two approaches: What they are and how they work The easy way with .env files Most Python projects use `.env` files - they're simple and work great for local development. # Environment variables Source: https://python.datalumina.com/tools/environment/variables Understanding environment config ## What are environment variables? Environment variables are settings stored outside your code. Think of them as configuration that your program can read. ## The problem they solve ```python theme={null} # BAD: Never hardcode sensitive data! api_key = "sk-1234567890abcdef" # Everyone can see this! database = "production_database" # Can't change without editing code ``` Problems: * Secrets visible in code * Can't share code safely * Different settings for different computers ## How environment variables work Environment variables live in your system, not your code: ```python theme={null} import os # Read from environment api_key = os.environ.get('API_KEY') database = os.environ.get('DATABASE_NAME', 'default.db') print(f"Using database: {database}") ``` ## Setting environment variables You can set them temporarily in your terminal: ```bash theme={null} # Mac/Linux export API_KEY=sk-1234567890abcdef python app.py # Windows set API_KEY=sk-1234567890abcdef python app.py ``` But they disappear when you close the terminal! ## Reading in Python ```python theme={null} import os # Method 1: Get with default api_key = os.environ.get('API_KEY', 'demo-key') # Method 2: Check if exists if 'API_KEY' in os.environ: api_key = os.environ['API_KEY'] else: print("No API key found") # Method 3: Will crash if not found api_key = os.environ['API_KEY'] # KeyError if missing! ``` ## Common uses * **API Keys**: `OPENAI_API_KEY`, `GITHUB_TOKEN` * **Database URLs**: `DATABASE_URL`, `REDIS_URL` * **App Settings**: `DEBUG=True`, `PORT=8000` * **File Paths**: `LOG_DIR`, `UPLOAD_FOLDER` ## Important notes * Environment variables are always strings * Names are UPPERCASE by convention * They're different on each computer * They don't persist between terminal sessions ## What's next? Setting variables manually is tedious. Let's use `.env` files for a better workflow. Easier way to manage variables # Clone and create Source: https://python.datalumina.com/tools/git/clone-create Working with repositories ## Two things you'll do often 1. **Clone** - Download existing projects from GitHub 2. **Create** - Start new projects and upload them Let's learn both. ## Cloning a repository Cloning means downloading a project from GitHub to your computer. ### Example: Clone an AI project Let's clone a real project to see how it works: **Pro tip**: Instead of using `cd` to navigate: **Mac**: Right-click a folder in Finder > Services > New Terminal at Folder (or hold Option and right-click > "Open in Terminal") **Windows**: Right-click a folder in File Explorer > "Open in Terminal" (or Shift + right-click > "Open PowerShell window here") This opens the terminal already in that folder! ```bash theme={null} # Open Terminal (Mac) or Command Prompt (Windows) # Navigate to where you want the project cd ~/Documents # Mac cd C:\Users\YourName\Documents # Windows # Clone using HTTPS URL git clone https://github.com/openai/openai-quickstart-python.git # Go into the project cd openai-quickstart-python # Open in VS Code (see note below if this doesn't work) code . ``` ```bash theme={null} # Open Terminal (Mac) or Command Prompt (Windows) # Navigate to where you want the project cd ~/Documents # Mac cd C:\Users\YourName\Documents # Windows # Clone using SSH URL git clone git@github.com:openai/openai-quickstart-python.git # Go into the project cd openai-quickstart-python # Open in VS Code (see note below if this doesn't work) code . ``` **If `code .` doesn't work**, you need to enable it first: **Mac:** 1. Open VS Code 2. Press `Cmd + Shift + P` 3. Type "Shell Command: Install 'code' command in PATH" 4. Press Enter 5. Restart your terminal **Windows:** 1. During VS Code installation, check "Add to PATH" 2. If you missed it, reinstall VS Code and check that option 3. Or manually: Right-click project folder > "Open with Code" That's it! You now have the entire project on your computer. ### What just happened? * Git downloaded all files * Git downloaded all history * You can now run, modify, and learn from this code Always clone into a sensible location. I recommend having a `projects` or `repos` folder in your Documents. ## Creating your own repository Let's put your `python-for-ai` project on GitHub. **Critical**: Before pushing to GitHub, create a `.gitignore` file! This prevents uploading your `.venv` folder, which can be gigabytes in size and cause push failures. ### Step 0: Create .gitignore file Before anything else, create a `.gitignore` file in your project: ``` # .gitignore - tells Git what NOT to track .venv/ .env __pycache__/ *.pyc .DS_Store ``` Save this file in your project root. Git will now ignore these files. ### Step 1: Create on GitHub 1. Go to [github.com](https://github.com) 2. Click the green "New" button (or + icon > "New repository") 3. Fill in: * **Repository name**: `python-for-ai` * **Description**: "Learning Python for AI development" * **Public/Private**: Choose Private for now * **Don't** add README, .gitignore, or license 4. Click "Create repository" ### Step 2: Connect your local project GitHub will show you commands. Choose based on your authentication method: ```bash theme={null} # Open Terminal (Mac) or Command Prompt (Windows) # Navigate to your python-for-ai folder cd ~/Documents/python-for-ai # Mac cd C:\Users\YourName\Documents\python-for-ai # Windows # Initialize Git in your project git init # Add all your files git add . # Create your first commit git commit -m "Initial commit" # Rename branch to main git branch -M main # Connect to GitHub with HTTPS (use YOUR username) git remote add origin https://github.com/YOUR-USERNAME/python-for-ai.git # Push your code git push -u origin main ``` ```bash theme={null} # Open Terminal (Mac) or Command Prompt (Windows) # Navigate to your python-for-ai folder cd ~/Documents/python-for-ai # Mac cd C:\Users\YourName\Documents\python-for-ai # Windows # Initialize Git in your project git init # Add all your files git add . # Create your first commit git commit -m "Initial commit" # Rename branch to main git branch -M main # Connect to GitHub with SSH (use YOUR username) git remote add origin git@github.com:YOUR-USERNAME/python-for-ai.git # Push your code git push -u origin main ``` When you push, GitHub will ask for your username and the personal access token (not your password!). VS Code will remember it. ## The daily workflow Once your project is on GitHub: ```bash theme={null} # Make changes to your code... # Save changes git add . git commit -m "Add new feature" # Upload to GitHub git push ``` That's 90% of what you'll do with Git! ## Common tasks 1. Press `Ctrl/Cmd + Shift + P` 2. Type "Git: Clone" 3. Paste the repository URL 4. Choose where to save it 5. VS Code opens the project automatically * **Private**: Only you can see it (good for learning) * **Public**: Anyone can see it (good for portfolio) * You can change this later in Settings ``` # .gitignore - tells Git what NOT to track .venv/ .env __pycache__/ *.pyc .DS_Store ``` Add this file to keep junk out of your repo. The `.venv/` folder can be several gigabytes! ## Practice exercise Try this: 1. Clone any Python project that interests you 2. Create a new repo for one of your practice scripts 3. Make a change, commit, and push ## What's next? VS Code makes Git even easier with visual tools. Let's explore those. Use Git without the terminal # GitHub setup Source: https://python.datalumina.com/tools/git/github-setup Create your account ## Create your GitHub account GitHub is free and takes 5 minutes to set up. You'll need it to: * Back up your code * Share your projects * Download AI tools and examples ## Step 1: Sign up 1. Go to [github.com](https://github.com) 2. Click "Sign up" 3. Enter: * **Username**: Pick something professional (employers will see this) * **Email**: Use one you check regularly * **Password**: Make it strong ## Step 2: Verify your account GitHub will send you an email. Click the link to verify. ## Step 3: Set up your profile Once logged in: 1. Click your profile picture (top right) > "Your profile" 2. Click "Edit profile" 3. Add: * **Name**: Your real name * **Image**: Add a profile picture * **Bio**: "Learning Python for AI development" (or similar) ## Step 4: Configure Git locally Tell Git who you are (one-time setup): ```bash theme={null} # Open terminal in VS Code (Terminal > New Terminal) git config --global user.name "Your Name" git config --global user.email "your.email@example.com" ``` Use the same email you used for GitHub. ## Step 5: Choose your authentication method There are three ways to authenticate with GitHub. Choose one: **Recommended**: We suggest using GitHub CLI for the easiest setup experience. It's modern, simple, and handles authentication automatically. ### GitHub CLI (gh) Modern approach using GitHub's official tool: 1. Install GitHub CLI: * **Windows**: Download from [cli.github.com](https://cli.github.com) * **macOS**: `brew install gh` * **Linux**: See [installation guide](https://github.com/cli/cli#installation) 2. Authenticate: ```bash theme={null} gh auth login ``` 3. Follow the prompts: * Choose GitHub.com * Choose SSH (recommended) or HTTPS * Authenticate with browser That's it! Git will automatically use your gh credentials. ### Personal Access Token Traditional method using tokens: 1. Go to GitHub Settings (click profile > Settings) 2. Scroll down to "Developer settings" (left sidebar) 3. Click "Personal access tokens" > "Tokens (classic)" 4. Click "Generate new token" > "Generate new token (classic)" 5. Give it a name like "My Laptop" or "VS Code" 6. Select scopes: check `repo` (full control of repositories) 7. Set expiration (or no expiration for convenience) 8. Click "Generate token" 9. **Copy the token immediately** (you won't see it again!) Save your token somewhere safe! You'll need it when pushing code. ### Using your token When you push code for the first time: ```bash theme={null} git push # GitHub will ask for: Username: your-github-username Password: paste-your-token-here (NOT your GitHub password!) ``` ### SSH Keys The most secure method - no passwords needed: 1. Generate SSH key: ```bash theme={null} ssh-keygen -t ed25519 -C "your_email@example.com" # Just press Enter for all prompts (accept defaults) ``` 2. Add to ssh-agent: ```bash theme={null} eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519 ``` ```bash theme={null} # In Git Bash (not Command Prompt): eval "$(ssh-agent -s)" ssh-add ~/.ssh/id_ed25519 ``` 3. Copy your public key: ```bash theme={null} # macOS pbcopy < ~/.ssh/id_ed25519.pub # Windows (Git Bash) cat ~/.ssh/id_ed25519.pub | clip # Linux cat ~/.ssh/id_ed25519.pub # Then manually copy the output ``` 4. Add to GitHub: * Go to [GitHub Settings > SSH Keys](https://github.com/settings/keys) * Click "New SSH key" * Give it a title (e.g., "My Laptop") * Paste your key * Click "Add SSH key" 5. Test the connection: ```bash theme={null} ssh -T git@github.com # You should see: "Hi username! You've successfully authenticated..." ``` **Important**: When cloning, use SSH URLs: ```bash theme={null} # SSH URL (what you want) git clone git@github.com:username/repo.git # Not HTTPS URL git clone https://github.com/username/repo.git ``` ## What's next? Now let's learn how to create your first repository and clone existing projects. Start using GitHub # Git & GitHub Source: https://python.datalumina.com/tools/git/index Version control basics ## What is Git? Git is like a save system for your code. It tracks every change you make, lets you go back to previous versions, and helps you collaborate with others. GitHub is where you store your Git projects online - think of it as Google Drive for code. ## Why you need Git As an AI engineer, you'll use Git to: * **Save your progress**: Never lose code again * **Try experiments**: Test ideas without breaking working code * **Share projects**: Show your work to employers or collaborators * **Use AI tools**: Many AI projects are shared on GitHub ## What we'll cover We'll focus on the essential Git commands you'll actually use: * Understanding version control (5 minutes) * Creating a GitHub account (5 minutes) * Cloning and creating projects (10 minutes) * Using Git in VS Code (10 minutes) We're keeping this simple. You only need about 5-6 Git commands to be productive. We'll skip the complex stuff you won't need yet. Understand the basics in 5 minutes Create your account Work with repositories Git without the terminal # Version control Source: https://python.datalumina.com/tools/git/version-control Understanding Git basics ## The problem Git solves Imagine working on a Python project. You've probably done this: * `my_script.py` * `my_script_v2.py` * `my_script_v2_final.py` * `my_script_v2_final_ACTUALLY_FINAL.py` * `my_script_backup_before_breaking_everything.py` Git solves this mess by tracking changes properly. ## How Git works Think of Git as taking snapshots of your code: 1. **You write code** - Make changes to your files 2. **You save a snapshot** - Called a "commit" in Git 3. **Git remembers everything** - Every snapshot, who made it, when, and why ```python theme={null} # Monday: Your code works def calculate_price(amount): return amount * 1.20 # 20% markup # Tuesday: Boss wants 25% markup def calculate_price(amount): return amount * 1.25 # Changed from 20% to 25% # Wednesday: "Actually, can we go back to 20%?" # With Git: Easy! Just go back to Monday's version # Without Git: Hope you still have that file somewhere... ``` ## Key concepts (all you need) **Repository (repo)**: A project tracked by Git * Your `python-for-ai` folder can be a repository **Staging**: Choosing which changes to save * Like selecting items to put in a box before shipping **Commit**: A saved snapshot of your code * Like saving in a video game - you can always go back **Push**: Upload your commits to GitHub * Backs up your code online **Pull**: Download changes from GitHub * Get updates when working with others **Clone**: Copy a project from GitHub * How you get AI projects to try ## First: Install Git Check if you have Git: ```bash theme={null} git --version ``` If you see a version number, you're good! If not, install Git: 1. Download from [git-scm.com](https://git-scm.com/download/win) 2. Run the installer 3. Keep all default settings 4. Restart VS Code after installation Visit [git-scm.com/downloads/mac](https://git-scm.com/downloads/mac) for installation options. **Easiest method (recommended):** ```bash theme={null} # If you have Homebrew installed brew install git ``` **Alternative:** Install Xcode Command Line Tools (includes Git): ```bash theme={null} git --version ``` macOS will prompt to install if Git is not found. Click "Install" and wait a few minutes. ```bash theme={null} # Ubuntu/Debian sudo apt update sudo apt install git # Fedora sudo dnf install git # Arch sudo pacman -S git ``` ## The simplest Git workflow Here's literally all you need to know for now: These are terminal commands, not Python code! Run them in VS Code's terminal. ```bash theme={null} # 0. First time only - initialize Git in your project git init # 1. Save your changes locally git add . git commit -m "Add price calculation function" # 2. Upload to GitHub (after connecting to GitHub - see next pages) git push # That's it! Your code is saved and backed up ``` If you see "fatal: not a git repository", you need to run `git init` first. This only needs to be done once per project. You can run these commands: * **One by one**: Type each command and press Enter * **All together**: Copy and paste all three lines - the terminal runs them in sequence ## Common questions No! VS Code has buttons for all Git operations. We'll show you both ways, but you can stick to clicking buttons if you prefer. Git is very forgiving. Every commit is saved forever, so you can always go back. It's actually harder to lose work with Git than without it. No. Git is the tool on your computer. GitHub is a website that stores Git projects. You can use Git without GitHub, but GitHub makes sharing easier. ## What's next? Let's create your GitHub account so you have somewhere to store your code. Create your account in 5 minutes # VS Code Git Source: https://python.datalumina.com/tools/git/vscode-git Git in your editor ## Git without the terminal VS Code has Git built in. You can do everything with clicks instead of commands. ## The Source Control panel Look at the left sidebar in VS Code. You'll see this icon: * **Source Control** icon (looks like a branch) * Shows all your changed files * One-click commits ## Basic workflow ### 1. See your changes Open the Source Control panel: * Changed files appear under "Changes" * Click any file to see what changed * Green lines = added * Red lines = removed ### 2. Stage changes Before committing, you "stage" files: * Hover over a file * Click the **+** icon * Or click **+** next to "Changes" to stage everything ### 3. Commit Once files are staged: 1. Type a message in the text box 2. Press `Ctrl/Cmd + Enter` (or click ✓) That's a commit! ### 4. Push to GitHub After committing: * Click the **...** menu in Source Control * Click "Push" * Or click the sync icon in the bottom status bar ## Visual features ### See changes inline * Modified files show a colored bar in the editor * Click the bar to see what changed * Blue = modified, Green = added, Red = deleted ## Common VS Code Git tasks 1. Open your project folder 2. Open Source Control panel 3. Click "Initialize Repository" 4. That's it! Your project now uses Git 1. Press `Ctrl/Cmd + Shift + P` 2. Type "Git: Clone" 3. Paste the GitHub URL 4. Choose where to save 5. VS Code opens it automatically 1. Create new file: `.gitignore` 2. VS Code suggests common patterns 3. Or use Python template: ``` .venv/ .env __pycache__/ *.pyc .vscode/ .DS_Store ``` Made a mistake? Undo changes: 1. In Source Control panel 2. Right-click the file 3. Select "Discard Changes" 4. Confirms before reverting ## Sync button magic The status bar shows a sync button: * **↓ 3** means "3 commits to pull" * **↑ 2** means "2 commits to push" * Click it to sync everything ## Tips for beginners 1. **Commit often**: Every small feature or fix 2. **Write clear messages**: "Fix login bug" not "changes" 3. **Pull before starting**: Get latest changes first 4. **Don't commit secrets**: Check your .gitignore Never commit `.env` files or API keys! Always add them to `.gitignore` first. ## Terminal vs UI Both work! Use what feels comfortable: | Task | Terminal | VS Code UI | | ----------- | ------------------------- | -------------------- | | Stage files | `git add .` | Click + icon | | Commit | `git commit -m "message"` | Type message + Enter | | Push | `git push` | Click sync | | Pull | `git pull` | Click sync | ## What's next? Now you know Git! Let's learn about environment variables and keeping secrets safe. Keep your API keys safe # Essential tools Source: https://python.datalumina.com/tools/index Tools every Python developer needs ## Tools for real Python development You've learned Python and built your first projects. Now let's add the essential tools that make Python development easier and more professional. ## What you'll learn Every Python developer needs these tools: * **Git & GitHub** - Save your work and collaborate with others * **Environment variables** - Keep secrets safe and manage configuration * **Code quality** - Automatically format and lint your code * **Modern Python tools** - Better ways to manage packages and dependencies These tools are especially important for AI development, where you'll share code, work with API keys, and manage complex dependencies. Version control basics Manage API keys safely Format and lint your code Dependency management