{ "cells": [ { "cell_type": "markdown", "id": "c4980ff8", "metadata": {}, "source": [ "# Week 1: Python Fundamentals and Environment Setup\n", "\n", "*Kmex Consult — Data Science Fundamentals Course*\n", "\n", "Work through each code cell in order. Edit and re-run to experiment." ] }, { "cell_type": "markdown", "id": "44e637eb", "metadata": {}, "source": [ "*Data Science Fundamentals Course*" ] }, { "cell_type": "markdown", "id": "1741f0e9", "metadata": {}, "source": [ "## Week 1 Overview\n", "This week is designed to get you started with Python programming from scratch. We will set up your development environment, learn the fundamental building blocks of Python, and begin writing your first programs. This week is crucial as it establishes the foundation for all the data science work ahead.\n", "\n", "By the end of Week 1, you will be able to:\n", "- Install and configure Python and your development environment\n", "- Understand Python syntax and basic concepts\n", "- Work with variables and data types\n", "- Use control flow statements (loops and conditionals)\n", "- Write and call functions\n", "- Push your work to GitHub\n", "\n", "Week 1 is divided into three 2-hour sessions:\n", "- Session 1: Python Installation & Setup, Variables & Data Types\n", "- Session 2: Operators & Control Flow\n", "- Session 3: Functions, Code Organization, and Introduction to Git" ] }, { "cell_type": "markdown", "id": "cbaabe93", "metadata": {}, "source": [ "## SESSION 1: Python Installation & Setup, Variables & Data Types" ] }, { "cell_type": "markdown", "id": "d66714f0", "metadata": {}, "source": [ "### Duration: 2 hours" ] }, { "cell_type": "markdown", "id": "199cf732", "metadata": {}, "source": [ "### 1.1 What is Python?\n", "Python is a high-level, interpreted programming language that is easy to read and learn. It was created by Guido van Rossum in 1991 and has become one of the most popular languages for data science, web development, and automation.\n", "\n", "Why Python for Data Science?\n", "- Simple and readable syntax: Python code looks like pseudocode, making it easier to learn\n", "- Powerful data science libraries: NumPy, pandas, scikit-learn, matplotlib, and many others\n", "- Large community: Extensive online resources, tutorials, and libraries\n", "- Versatility: Can be used for data analysis, machine learning, web scraping, and more\n", "- Industry adoption: Widely used in data science and tech companies globally\n", "- Open source: Free to use and modify\n", "- Interactive environments: Jupyter notebooks allow for interactive data analysis and exploration" ] }, { "cell_type": "markdown", "id": "bd3b3157", "metadata": {}, "source": [ "### 1.2 Installing Python" ] }, { "cell_type": "markdown", "id": "c226dbb9", "metadata": {}, "source": [ "#### Method 1: Installing Anaconda (Recommended)\n", "Anaconda is a distribution that includes Python and many commonly used libraries for data science. This is the easiest method for beginners.\n", "1. Visit https://www.anaconda.com/products/individual\n", "1. Download the Python 3.9 or later version for your operating system (Windows, macOS, or Linux)\n", "1. Run the installer and follow the prompts\n", "1. During installation, check "Add Anaconda to my PATH environment variable" (Windows only)\n", "1. After installation, verify by opening a terminal/command prompt and typing: python --version" ] }, { "cell_type": "markdown", "id": "66d8cbfc", "metadata": {}, "source": [ "#### Method 2: Direct Python Installation\n", "If you prefer a minimal installation:\n", "1. Visit https://www.python.org/downloads/\n", "1. Download Python 3.9 or later\n", "1. Run the installer\n", "1. On Windows, check "Add Python 3.x to PATH"\n", "1. After installation, verify: python --version\n", "1. Install pip (Python package manager): pip install --upgrade pip" ] }, { "cell_type": "markdown", "id": "be3ebdf2", "metadata": {}, "source": [ "### 1.3 Verifying Your Installation\n", "Open a terminal (macOS/Linux) or Command Prompt (Windows) and run:\n", "python --version\n", "You should see output like: Python 3.9.x (or your installed version)" ] }, { "cell_type": "markdown", "id": "e2e45529", "metadata": {}, "source": [ "### 1.4 Your First Python Program\n", "Python can be run in two ways:" ] }, { "cell_type": "markdown", "id": "5586a52c", "metadata": {}, "source": [ "#### Interactive Mode (Python Shell)\n", "Open your terminal/command prompt and type:\n", "python\n", "You will see the Python prompt (>>>). Now you can type Python commands:\n", ">>> print(\"Hello, Data Science World!\")\n", "Hello, Data Science World!\n", ">>> 2 + 2\n", "4\n", ">>> exit()" ] }, { "cell_type": "markdown", "id": "30607998", "metadata": {}, "source": [ "#### Script Mode (Writing Python Files)\n", "It is more practical to write Python code in files (.py files) that can be saved and reused.\n", "Step 1: Create a new file called hello.py\n", "Step 2: Write your code in the file" ] }, { "cell_type": "code", "execution_count": null, "id": "ddd7c23d", "metadata": {}, "outputs": [], "source": [ "print(\"Hello, Data Science World!\")\n", "x = 2 + 2\n", "print(x)" ] }, { "cell_type": "markdown", "id": "f47906ec", "metadata": {}, "source": [ "Step 3: Run the script from your terminal:\n", "python hello.py" ] }, { "cell_type": "markdown", "id": "39823183", "metadata": {}, "source": [ "### 1.5 Setting Up Jupyter Notebook\n", "Jupyter Notebook is an interactive environment ideal for data analysis and learning. It allows you to write and execute code, see results immediately, and include explanations.\n", "If you installed Anaconda, Jupyter is already included. Start it by typing:\n", "jupyter notebook\n", "This opens a web browser with Jupyter. You can create a new notebook and start writing code in cells." ] }, { "cell_type": "markdown", "id": "4ffa5fb8", "metadata": {}, "source": [ "### 1.6 Setting Up an IDE (VS Code or PyCharm)" ] }, { "cell_type": "markdown", "id": "78c3503d", "metadata": {}, "source": [ "#### Visual Studio Code (VS Code)\n", "A lightweight, free code editor:\n", "- Download VS Code from https://code.visualstudio.com/\n", "- Install the Python extension by Microsoft\n", "- Create a new folder for your project\n", "- Open it in VS Code and create a .py file\n", "- Write your code and run it by right-clicking and selecting "Run Python File"" ] }, { "cell_type": "markdown", "id": "0e54d6c6", "metadata": {}, "source": [ "### 1.7 Understanding Variables\n", "A variable is a container that holds a value. Think of it as a labeled box where you store information. In Python, variables are created when you assign a value to them.\n", "Variable Naming Rules:\n", "- Must start with a letter (a-z, A-Z) or underscore (_)\n", "- Can contain letters, numbers (0-9), and underscores\n", "- Are case-sensitive (Name and name are different)\n", "- Should be descriptive and lowercase with underscores (snake_case)\n", "- Cannot use Python keywords (e.g., if, for, class)\n", "Examples of variable assignment:" ] }, { "cell_type": "code", "execution_count": null, "id": "2e0dc12b", "metadata": {}, "outputs": [], "source": [ "# Variable assignment\n", "student_name = \"Alice\"\n", "student_age = 25\n", "height_cm = 170.5\n", "is_enrolled = True\n", "\n", "# Printing variables\n", "print(student_name)\n", "print(student_age)\n", "print(height_cm)\n", "print(is_enrolled)\n", "\n", "# Using variables in calculations\n", "average_age = student_age\n", "new_age = student_age + 1\n", "print(new_age)" ] }, { "cell_type": "markdown", "id": "3010b8a7", "metadata": {}, "source": [ "### 1.8 Basic Data Types\n", "Python has several basic data types. Understanding them is crucial for working with data." ] }, { "cell_type": "markdown", "id": "1c24b374", "metadata": {}, "source": [ "#### 1. Integers (int)\n", "Whole numbers without decimal points." ] }, { "cell_type": "code", "execution_count": null, "id": "8793edcc", "metadata": {}, "outputs": [], "source": [ "age = 25\n", "count = 100\n", "negative = -50\n", "zero = 0\n", "\n", "# Checking type\n", "print(type(age)) # Output: " ] }, { "cell_type": "markdown", "id": "ab904f84", "metadata": {}, "source": [ "#### 2. Floats (float)\n", "Numbers with decimal points." ] }, { "cell_type": "code", "execution_count": null, "id": "0e3853ff", "metadata": {}, "outputs": [], "source": [ "height = 5.9\n", "temperature = 36.5\n", "pi = 3.14159\n", "negative_float = -2.5\n", "\n", "# Checking type\n", "print(type(height)) # Output: " ] }, { "cell_type": "markdown", "id": "9cface26", "metadata": {}, "source": [ "#### 3. Strings (str)\n", "Text enclosed in single quotes, double quotes, or triple quotes." ] }, { "cell_type": "code", "execution_count": null, "id": "330c7f63", "metadata": {}, "outputs": [], "source": [ "name = \"Alice\"\n", "city = 'Lagos'\n", "message = \"\"\"This is a\n", "multiline string\"\"\"\n", "\n", "# String operations\n", "greeting = \"Hello, \" + name\n", "print(greeting) # Output: Hello, Alice\n", "\n", "# String length\n", "print(len(name)) # Output: 5\n", "\n", "# Accessing characters\n", "print(name[0]) # Output: A (first character)" ] }, { "cell_type": "markdown", "id": "07148932", "metadata": {}, "source": [ "#### 4. Booleans (bool)\n", "True or False values. Used for logical operations." ] }, { "cell_type": "code", "execution_count": null, "id": "501ab801", "metadata": {}, "outputs": [], "source": [ "is_student = True\n", "has_job = False\n", "\n", "# Boolean comparisons\n", "x = 5\n", "y = 10\n", "\n", "print(x > y) # Output: False\n", "print(x < y) # Output: True\n", "print(x == y) # Output: False\n", "\n", "# Type checking\n", "print(type(is_student)) # Output: " ] }, { "cell_type": "markdown", "id": "c65350d1", "metadata": {}, "source": [ "#### Type Conversion\n", "You can convert between data types:" ] }, { "cell_type": "code", "execution_count": null, "id": "491ab8e4", "metadata": {}, "outputs": [], "source": [ "# String to integer\n", "age_str = \"25\"\n", "age_int = int(age_str)\n", "print(age_int) # Output: 25\n", "\n", "# Integer to string\n", "count = 100\n", "count_str = str(count)\n", "print(count_str) # Output: \"100\"\n", "\n", "# String to float\n", "height_str = \"5.9\"\n", "height_float = float(height_str)\n", "print(height_float) # Output: 5.9\n", "\n", "# Integer to float\n", "age_int = 25\n", "age_float = float(age_int)\n", "print(age_float) # Output: 25.0\n", "\n", "# Float to integer (truncates decimal)\n", "height = 5.9\n", "height_int = int(height)\n", "print(height_int) # Output: 5" ] }, { "cell_type": "markdown", "id": "962e3dbf", "metadata": {}, "source": [ "## SESSION 2: Operators & Control Flow" ] }, { "cell_type": "markdown", "id": "c1d554ee", "metadata": {}, "source": [ "### Duration: 2 hours" ] }, { "cell_type": "markdown", "id": "2b5cf54f", "metadata": {}, "source": [ "### 2.1 Arithmetic Operators\n", "Arithmetic operators are used to perform mathematical operations.\n", "Examples:" ] }, { "cell_type": "code", "execution_count": null, "id": "d1429918", "metadata": {}, "outputs": [], "source": [ "x = 10\n", "y = 3\n", "\n", "print(x + y) # Output: 13\n", "print(x - y) # Output: 7\n", "print(x * y) # Output: 30\n", "print(x / y) # Output: 3.3333...\n", "print(x // y) # Output: 3\n", "print(x % y) # Output: 1\n", "print(x ** y) # Output: 1000\n", "\n", "# Real-world example: Calculate area of rectangle\n", "length = 10\n", "width = 5\n", "area = length * width\n", "print(f\"Area: {area} square units\") # Output: Area: 50 square units" ] }, { "cell_type": "markdown", "id": "788be053", "metadata": {}, "source": [ "### 2.2 Comparison Operators\n", "Comparison operators compare values and return True or False.\n", "Examples:" ] }, { "cell_type": "code", "execution_count": null, "id": "683544da", "metadata": {}, "outputs": [], "source": [ "x = 10\n", "y = 5\n", "\n", "print(x == y) # Output: False\n", "print(x != y) # Output: True\n", "print(x > y) # Output: True\n", "print(x < y) # Output: False\n", "print(x >= y) # Output: True\n", "print(x <= y) # Output: False\n", "\n", "# Comparing strings\n", "name1 = \"Alice\"\n", "name2 = \"Bob\"\n", "print(name1 == name2) # Output: False" ] }, { "cell_type": "markdown", "id": "776cb3fa", "metadata": {}, "source": [ "### 2.3 Logical Operators\n", "Logical operators combine conditional statements.\n", "Examples:" ] }, { "cell_type": "code", "execution_count": null, "id": "9c63d39c", "metadata": {}, "outputs": [], "source": [ "age = 25\n", "is_student = True\n", "\n", "# Using 'and'\n", "print(age > 18 and age < 65) # Output: True\n", "print(age > 30 and is_student) # Output: False\n", "\n", "# Using 'or'\n", "print(age < 18 or is_student) # Output: True\n", "\n", "# Using 'not'\n", "print(not(age < 18)) # Output: True\n", "\n", "# Real-world example: Check if someone can work\n", "working_age = age > 18 and age < 65\n", "print(f\"Can work: {working_age}\") # Output: Can work: True" ] }, { "cell_type": "markdown", "id": "5241a221", "metadata": {}, "source": [ "### 2.4 Assignment Operators\n", "Assignment operators are used to assign values to variables." ] }, { "cell_type": "code", "execution_count": null, "id": "5737e2db", "metadata": {}, "outputs": [], "source": [ "x = 10\n", "print(x) # Output: 10\n", "\n", "x += 5 # x = x + 5\n", "print(x) # Output: 15\n", "\n", "x -= 3 # x = x - 3\n", "print(x) # Output: 12\n", "\n", "x *= 2 # x = x * 2\n", "print(x) # Output: 24\n", "\n", "# Real-world: Update test score\n", "score = 80\n", "score += 5 # Bonus points\n", "print(f\"Final score: {score}\") # Output: Final score: 85" ] }, { "cell_type": "markdown", "id": "5235d377", "metadata": {}, "source": [ "### 2.5 Control Flow: If-Else Statements\n", "Control flow statements allow your program to make decisions and execute different code based on conditions. The most fundamental control structure is the if-else statement." ] }, { "cell_type": "markdown", "id": "e1fcf04c", "metadata": {}, "source": [ "#### Basic If Statement\n", "Execute code only if a condition is True." ] }, { "cell_type": "code", "execution_count": null, "id": "88ad955a", "metadata": {}, "outputs": [], "source": [ "age = 25\n", "\n", "if age >= 18:\n", "print(\"You are an adult\")\n", "\n", "# Output: You are an adult\n", "\n", "# Another example\n", "score = 45\n", "if score >= 50:\n", "print(\"You passed\")\n", "# This won't execute because score is not >= 50" ] }, { "cell_type": "markdown", "id": "bd61d286", "metadata": {}, "source": [ "Important: Note the colon (:) and indentation. Python uses indentation to show which code belongs to the if block." ] }, { "cell_type": "markdown", "id": "87ebe9f4", "metadata": {}, "source": [ "#### If-Else Statement\n", "Execute one block if condition is True, another if False." ] }, { "cell_type": "code", "execution_count": null, "id": "d787b613", "metadata": {}, "outputs": [], "source": [ "age = 15\n", "\n", "if age >= 18:\n", "print(\"You are an adult\")\n", "else:\n", "print(\"You are a minor\")\n", "\n", "# Output: You are a minor\n", "\n", "# Real-world example: Grading\n", "score = 75\n", "\n", "if score >= 80:\n", "grade = \"A\"\n", "else:\n", "grade = \"Not A\"\n", "\n", "print(f\"Your grade: {grade}\") # Output: Your grade: Not A" ] }, { "cell_type": "markdown", "id": "d7db1a13", "metadata": {}, "source": [ "#### If-Elif-Else Statement\n", "Check multiple conditions in sequence." ] }, { "cell_type": "code", "execution_count": null, "id": "e8300c4c", "metadata": {}, "outputs": [], "source": [ "score = 75\n", "\n", "if score >= 90:\n", "grade = \"A\"\n", "elif score >= 80:\n", "grade = \"B\"\n", "elif score >= 70:\n", "grade = \"C\"\n", "elif score >= 60:\n", "grade = \"D\"\n", "else:\n", "grade = \"F\"\n", "\n", "print(f\"Your grade: {grade}\") # Output: Your grade: C\n", "\n", "# Real-world: Discount based on purchase amount\n", "purchase = 150\n", "\n", "if purchase >= 200:\n", "discount = 0.20 # 20% discount\n", "elif purchase >= 100:\n", "discount = 0.10 # 10% discount\n", "else:\n", "discount = 0.0 # No discount\n", "\n", "final_price = purchase * (1 - discount)\n", "print(f\"Final price: {final_price}\") # Output: Final price: 135.0" ] }, { "cell_type": "markdown", "id": "0c07775d", "metadata": {}, "source": [ "### 2.6 Loops: For and While\n", "Loops allow you to repeat code multiple times. They are essential for automating repetitive tasks." ] }, { "cell_type": "markdown", "id": "4c8931bb", "metadata": {}, "source": [ "#### The For Loop\n", "Repeats a block of code a specific number of times." ] }, { "cell_type": "code", "execution_count": null, "id": "023bc3c4", "metadata": {}, "outputs": [], "source": [ "# Loop through numbers 0 to 4\n", "for i in range(5):\n", "print(i)\n", "\n", "# Output:\n", "# 0\n", "# 1\n", "# 2\n", "# 3\n", "# 4\n", "\n", "# Loop through a list\n", "fruits = [\"apple\", \"banana\", \"cherry\"]\n", "for fruit in fruits:\n", "print(fruit)\n", "\n", "# Output:\n", "# apple\n", "# banana\n", "# cherry\n", "\n", "# Loop with index\n", "for index, fruit in enumerate(fruits):\n", "print(f\"Index {index}: {fruit}\")\n", "\n", "# Output:\n", "# Index 0: apple\n", "# Index 1: banana\n", "# Index 2: cherry\n", "\n", "# Real-world: Calculate sum of numbers\n", "numbers = [10, 20, 30, 40, 50]\n", "total = 0\n", "for num in numbers:\n", "total += num\n", "print(f\"Sum: {total}\") # Output: Sum: 150" ] }, { "cell_type": "markdown", "id": "685ae6c8", "metadata": {}, "source": [ "#### The While Loop\n", "Repeats code while a condition is True." ] }, { "cell_type": "code", "execution_count": null, "id": "265276ff", "metadata": {}, "outputs": [], "source": [ "# Count down\n", "count = 5\n", "while count > 0:\n", "print(count)\n", "count -= 1\n", "print(\"Blastoff!\")\n", "\n", "# Output:\n", "# 5\n", "# 4\n", "# 3\n", "# 2\n", "# 1\n", "# Blastoff!\n", "\n", "# Real-world: Continue asking until valid input\n", "password = \"\"\n", "while password != \"secret\":\n", "password = input(\"Enter password: \")\n", "if password == \"secret\":\n", "print(\"Access granted!\")\n", "else:\n", "print(\"Wrong password, try again\")" ] }, { "cell_type": "markdown", "id": "0d801207", "metadata": {}, "source": [ "#### Break and Continue Statements\n", "Control loop execution with break and continue." ] }, { "cell_type": "code", "execution_count": null, "id": "e9cc974d", "metadata": {}, "outputs": [], "source": [ "# Break: Exit the loop early\n", "for i in range(10):\n", "if i == 5:\n", "break # Exit loop when i equals 5\n", "print(i)\n", "\n", "# Output: 0, 1, 2, 3, 4\n", "\n", "# Continue: Skip to next iteration\n", "for i in range(5):\n", "if i == 2:\n", "continue # Skip when i equals 2\n", "print(i)\n", "\n", "# Output: 0, 1, 3, 4\n", "\n", "# Real-world: Find first number divisible by 7\n", "for i in range(20, 50):\n", "if i % 7 == 0:\n", "print(f\"Found: {i}\")\n", "break" ] }, { "cell_type": "markdown", "id": "d92f5425", "metadata": {}, "source": [ "## SESSION 3: Functions, Code Organization & Git Introduction" ] }, { "cell_type": "markdown", "id": "37999e94", "metadata": {}, "source": [ "### Duration: 2 hours" ] }, { "cell_type": "markdown", "id": "b0f3d94e", "metadata": {}, "source": [ "### 3.1 Understanding Functions\n", "A function is a reusable block of code that performs a specific task. Functions help you organize code, avoid repetition, and make programs more maintainable.\n", "\n", "Key benefits of functions:\n", "- Reusability: Write once, use many times\n", "- Organization: Break complex problems into smaller pieces\n", "- Readability: Clear names describe what code does\n", "- Maintenance: Easier to fix or update code\n", "- Testing: Test individual functions in isolation" ] }, { "cell_type": "markdown", "id": "41a10db2", "metadata": {}, "source": [ "### Defining Functions" ] }, { "cell_type": "code", "execution_count": null, "id": "22ae64c1", "metadata": {}, "outputs": [], "source": [ "def function_name(parameters):\n", "\"\"\"Docstring explaining what function does\"\"\"\n", "# Function body - code to execute\n", "return result\n", "\n", "# Simple function with no parameters\n", "def say_hello():\n", "\"\"\"Greets the user\"\"\"\n", "print(\"Hello, World!\")\n", "\n", "say_hello() # Call the function\n", "# Output: Hello, World!\n", "\n", "# Function with parameters\n", "def greet(name):\n", "\"\"\"Greets a person by name\"\"\"\n", "print(f\"Hello, {name}!\")\n", "\n", "greet(\"Alice\") # Output: Hello, Alice!\n", "greet(\"Bob\") # Output: Hello, Bob!\n", "\n", "# Function with return value\n", "def add(a, b):\n", "\"\"\"Adds two numbers and returns the result\"\"\"\n", "result = a + b\n", "return result\n", "\n", "sum_result = add(5, 3)\n", "print(sum_result) # Output: 8\n", "\n", "# Function with multiple parameters and return\n", "def calculate_area(length, width):\n", "\"\"\"Calculates area of a rectangle\"\"\"\n", "area = length * width\n", "return area\n", "\n", "rect_area = calculate_area(10, 5)\n", "print(f\"Area: {rect_area}\") # Output: Area: 50" ] }, { "cell_type": "markdown", "id": "6806945e", "metadata": {}, "source": [ "#### Default Parameters and Keyword Arguments" ] }, { "cell_type": "code", "execution_count": null, "id": "738529ee", "metadata": {}, "outputs": [], "source": [ "# Function with default parameters\n", "def power(base, exponent=2):\n", "\"\"\"Raises base to exponent (default 2)\"\"\"\n", "return base ** exponent\n", "\n", "print(power(5)) # Output: 25 (uses default exponent=2)\n", "print(power(5, 3)) # Output: 125 (exponent=3)\n", "\n", "# Function with keyword arguments\n", "def create_profile(name, age, city=\"Unknown\"):\n", "\"\"\"Creates a user profile\"\"\"\n", "profile = f\"Name: {name}, Age: {age}, City: {city}\"\n", "return profile\n", "\n", "# Positional arguments\n", "print(create_profile(\"Alice\", 25))\n", "# Output: Name: Alice, Age: 25, City: Unknown\n", "\n", "# Keyword arguments\n", "print(create_profile(name=\"Bob\", age=30, city=\"Lagos\"))\n", "# Output: Name: Bob, Age: 30, City: Lagos\n", "\n", "# Mixed\n", "print(create_profile(\"Charlie\", 28, city=\"London\"))\n", "# Output: Name: Charlie, Age: 28, City: London" ] }, { "cell_type": "markdown", "id": "3aa8f732", "metadata": {}, "source": [ "#### Returning Multiple Values" ] }, { "cell_type": "code", "execution_count": null, "id": "63a779e6", "metadata": {}, "outputs": [], "source": [ "# Function returning multiple values\n", "def get_min_max(numbers):\n", "\"\"\"Returns minimum and maximum from a list\"\"\"\n", "return min(numbers), max(numbers)\n", "\n", "numbers = [10, 5, 20, 15, 8]\n", "min_val, max_val = get_min_max(numbers)\n", "print(f\"Min: {min_val}, Max: {max_val}\")\n", "# Output: Min: 5, Max: 20\n", "\n", "# Function returning results and status\n", "def divide(a, b):\n", "\"\"\"Divides a by b, returns result and success status\"\"\"\n", "if b == 0:\n", "return None, False # Division by zero\n", "return a / b, True\n", "\n", "result, success = divide(10, 2)\n", "if success:\n", "print(f\"Result: {result}\") # Output: Result: 5.0\n", "else:\n", "print(\"Error: Cannot divide by zero\")" ] }, { "cell_type": "markdown", "id": "516ffd4b", "metadata": {}, "source": [ "### 3.2 Variable Scope\n", "Scope determines where a variable can be accessed in your code. Python has two main scopes:\n", "- Global scope: Variables accessible anywhere in the program\n", "- Local scope: Variables accessible only within the function" ] }, { "cell_type": "code", "execution_count": null, "id": "5fe098c2", "metadata": {}, "outputs": [], "source": [ "# Global variable\n", "global_var = \"I am global\"\n", "\n", "def my_function():\n", "# Local variable\n", "local_var = \"I am local\"\n", "print(global_var) # Can access global\n", "print(local_var) # Can access local\n", "\n", "my_function()\n", "# Output:\n", "# I am global\n", "# I am local\n", "\n", "# print(local_var) # This would cause an error\n", "# local_var is not defined outside the function\n", "\n", "# Real-world example\n", "PI = 3.14159 # Global constant\n", "\n", "def circle_area(radius):\n", "\"\"\"Calculate circle area (local scope for radius and area)\"\"\"\n", "area = PI * radius ** 2\n", "return area\n", "\n", "print(circle_area(5)) # Output: 78.53975" ] }, { "cell_type": "markdown", "id": "4b70c1ad", "metadata": {}, "source": [ "### 3.3 Code Organization Best Practices\n", "Writing organized code is crucial for data science work. Here are best practices:\n", "- Use descriptive names: Use clear, meaningful names for variables and functions\n", "- Add comments: Explain why code does something, not just what it does\n", "- Write docstrings: Document what each function does\n", "- Keep functions focused: Each function should do one thing well\n", "- Use consistent formatting: Follow PEP 8 style guidelines\n", "- Avoid global state: Minimize use of global variables\n", "- Test your code: Verify functions work as expected\n", "Example of well-organized code:" ] }, { "cell_type": "code", "execution_count": null, "id": "135991d6", "metadata": {}, "outputs": [], "source": [ "# Calculate student grades\n", "def calculate_grade(score):\n", "\"\"\"\n", "Converts numeric score to letter grade\n", "\n", "Parameters:\n", "score (int/float): Student's test score\n", "\n", "Returns:\n", "str: Letter grade (A, B, C, D, or F)\n", "\"\"\"\n", "if score >= 90:\n", "return \"A\"\n", "elif score >= 80:\n", "return \"B\"\n", "elif score >= 70:\n", "return \"C\"\n", "elif score >= 60:\n", "return \"D\"\n", "else:\n", "return \"F\"\n", "\n", "def process_grades(scores):\n", "\"\"\"\n", "Processes a list of scores and returns grades\n", "\n", "Parameters:\n", "scores (list): List of student scores\n", "\n", "Returns:\n", "list: Corresponding letter grades\n", "\"\"\"\n", "grades = []\n", "for score in scores:\n", "grade = calculate_grade(score)\n", "grades.append(grade)\n", "return grades\n", "\n", "# Usage\n", "student_scores = [85, 92, 78, 88, 95]\n", "student_grades = process_grades(student_scores)\n", "\n", "for score, grade in zip(student_scores, student_grades):\n", "print(f\"Score: {score} -> Grade: {grade}\")\n", "\n", "# Output:\n", "# Score: 85 -> Grade: B\n", "# Score: 92 -> Grade: A\n", "# Score: 78 -> Grade: C\n", "# Score: 88 -> Grade: B\n", "# Score: 95 -> Grade: A" ] }, { "cell_type": "markdown", "id": "5cdb8918", "metadata": {}, "source": [ "### 3.4 PEP 8: Python Style Guide\n", "PEP 8 is the official style guide for Python code. Following it makes code readable and professional.\n", "- Use lowercase with underscores for variables: my_variable = 5 (not myVariable or MyVariable)\n", "- Function names also lowercase with underscores: def my_function(): (not myFunction)\n", "- Class names use CamelCase: class MyClass:\n", "- Use 4 spaces for indentation: Never mix tabs and spaces\n", "- Line length max 79 characters: Makes code readable on all screens\n", "- Use meaningful names: name = "Alice" (not n or x)\n", "- Add spaces around operators: x = y + 2 (not x=y+2)\n", "- No spaces before colons in arguments: def func(a, b): (not def func(a , b):)" ] }, { "cell_type": "markdown", "id": "0ab5b350", "metadata": {}, "source": [ "### 3.5 Introduction to Git and GitHub\n", "Git is a version control system that tracks changes to your code. GitHub is a platform for hosting Git repositories. For a data scientist, Git is essential for:\n", "- Backing up your code\n", "- Tracking changes over time\n", "- Collaborating with others\n", "- Building a portfolio to showcase your work" ] }, { "cell_type": "markdown", "id": "983f2205", "metadata": {}, "source": [ "#### Installing Git\n", "Download and install from https://git-scm.com/" ] }, { "cell_type": "markdown", "id": "716a6d3b", "metadata": {}, "source": [ "#### Basic Git Concepts\n", "- Repository: A folder containing your project and its history\n", "- Commit: A saved version of your code with a message describing changes\n", "- Branch: A parallel version of your code for developing features\n", "- Pull Request: A request to merge changes from one branch to another" ] }, { "cell_type": "markdown", "id": "08e88b55", "metadata": {}, "source": [ "#### Setting Up Your First Repository\n", "1. Create a folder for your project\n", "1. Navigate into the folder: cd my_project\n", "1. Initialize Git: git init\n", "1. Add files: git add hello.py\n", "1. Commit changes: git commit -m "Initial commit"\n", "1. Check status: git status" ] }, { "cell_type": "code", "execution_count": null, "id": "62e8ee73", "metadata": {}, "outputs": [], "source": [ "# Initialize a new repository\n", "git init\n", "\n", "# Check status\n", "git status\n", "\n", "# Add a file to staging area\n", "git add hello.py\n", "\n", "# Commit with a message\n", "git commit -m \"Add hello.py script\"\n", "\n", "# View commit history\n", "git log\n", "\n", "# Create a new branch\n", "git branch feature/new-function\n", "\n", "# Switch to new branch\n", "git checkout feature/new-function\n", "\n", "# Make changes and commit\n", "git add .\n", "git commit -m \"Add new function\"\n", "\n", "# Switch back to main\n", "git checkout main\n", "\n", "# Merge branch into main\n", "git merge feature/new-function" ] }, { "cell_type": "markdown", "id": "f22169b9", "metadata": {}, "source": [ "#### Creating a GitHub Repository\n", "1. Create a GitHub account at https://github.com if you don't have one\n", "1. Click "New" to create a new repository\n", "1. Name your repository (e.g., data-science-learning)\n", "1. Add a description\n", "1. Initialize with a README (recommended)\n", "1. Click "Create repository"\n", "1. Follow instructions to push your local code to GitHub" ] }, { "cell_type": "code", "execution_count": null, "id": "2d97088a", "metadata": {}, "outputs": [], "source": [ "# Add GitHub repository as remote\n", "git remote add origin https://github.com/yourusername/repository-name.git\n", "\n", "# Push local commits to GitHub\n", "git push -u origin main\n", "\n", "# Clone a repository\n", "git clone https://github.com/username/repository.git\n", "\n", "# Pull latest changes from GitHub\n", "git pull origin main" ] }, { "cell_type": "markdown", "id": "37fcb4aa", "metadata": {}, "source": [ "## Week 1 Summary\n", "By completing Week 1, you have learned:\n", "- How to install and configure Python and Jupyter Notebook\n", "- Basic data types: int, float, str, bool\n", "- Variables and how to use them\n", "- Arithmetic, comparison, and logical operators\n", "- Control flow with if-elif-else statements\n", "- Loops with for and while statements\n", "- Functions and how to organize code\n", "- Variable scope and best practices\n", "- Introduction to Git and GitHub\n", "- PEP 8 style guidelines" ] }, { "cell_type": "markdown", "id": "1a1b452a", "metadata": {}, "source": [ "## Week 1 Assignments" ] }, { "cell_type": "markdown", "id": "71ccf49c", "metadata": {}, "source": [ "### Assignment 1: Python Setup and First Script\n", "Create a Python script that:\n", "- Defines variables for a person (name, age, city, height)\n", "- Uses arithmetic operations to calculate BMI (weight in kg / (height in m)^2)\n", "- Uses if-elif-else to classify BMI (underweight < 18.5, normal 18.5-24.9, overweight 25-29.9, obese >= 30)\n", "- Prints the results with proper formatting" ] }, { "cell_type": "markdown", "id": "6b1d2b99", "metadata": {}, "source": [ "### Assignment 2: Functions and Control Flow\n", "Write functions that:\n", "- Convert temperature from Celsius to Fahrenheit: F = (C × 9/5) + 32\n", "- Check if a number is even or odd\n", "- Calculate factorial of a number (use loops or recursion)\n", "- Find the maximum number in a list without using max()\n", "Test each function with different inputs" ] }, { "cell_type": "markdown", "id": "e79759a3", "metadata": {}, "source": [ "### Assignment 3: GitHub Repository\n", "Create a GitHub repository for your learning:\n", "- Initialize a local Git repository\n", "- Create a README.md file describing your learning goals\n", "- Add your scripts from Assignments 1 and 2\n", "- Commit your changes with meaningful messages\n", "- Push to GitHub\n", "- Share the link to your repository" ] }, { "cell_type": "markdown", "id": "bbe87d5e", "metadata": {}, "source": [ "## Recommended Practice Problems\n", "- Write a function that converts hours, minutes, and seconds to total seconds\n", "- Write a function that checks if a number is prime\n", "- Create a function that generates the Fibonacci sequence up to n\n", "- Write a calculator that takes two numbers and an operator (+, -, *, /)\n", "- Create a program that plays a guessing game (user guesses a random number)\n", "- Write a function that converts currency between different units" ] }, { "cell_type": "markdown", "id": "2b229643", "metadata": {}, "source": [ "## Additional Resources" ] }, { "cell_type": "markdown", "id": "82089f6f", "metadata": {}, "source": [ "### Books\n", "- Python Crash Course by Eric Matthes - Beginner-friendly introduction\n", "- Think Python by Allen Downey - Great for understanding programming concepts\n", "- Chapters 2-3 from "Python for Data Analysis" by Wes McKinney" ] }, { "cell_type": "markdown", "id": "ed7b2662", "metadata": {}, "source": [ "### Online Resources\n", "- Python Official Documentation: https://docs.python.org/3/\n", "- Real Python: https://realpython.com/ - Excellent tutorials\n", "- GeeksforGeeks: https://www.geeksforgeeks.org/python-programming-language/\n", "- Codecademy: Interactive Python courses" ] }, { "cell_type": "markdown", "id": "0cbf3508", "metadata": {}, "source": [ "### Practice Platforms\n", "- LeetCode: https://leetcode.com/ - Coding challenges\n", "- HackerRank: https://www.hackerrank.com/ - Practice problems\n", "- Codewars: https://www.codewars.com/ - Gamified coding" ] } ], "metadata": { "kernelspec": { "display_name": "Python 3", "language": "python", "name": "python3" }, "language_info": { "name": "python", "version": "3.11" } }, "nbformat": 4, "nbformat_minor": 5 }