W1
Beginner 3 sessions • 6 hours Python

Week 1: Python Fundamentals and Environment Setup

.ipynb
Follow along in JupyterDownload the complete Week 1 notebook — every code example ready to run.
Download Notebook

Data Science Fundamentals Course

Week 1 Overview

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. By the end of Week 1, you will be able to:

  • Install and configure Python and your development environment
  • Understand Python syntax and basic concepts
  • Work with variables and data types
  • Use control flow statements (loops and conditionals)
  • Write and call functions
  • Push your work to GitHub

Week 1 is divided into three 2-hour sessions:

  • Session 1: Python Installation & Setup, Variables & Data Types
  • Session 2: Operators & Control Flow
  • Session 3: Functions, Code Organization, and Introduction to Git

SESSION 1: Python Installation & Setup, Variables & Data Types

Duration: 2 hours

1.1 What is Python?

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. Why Python for Data Science?

  • Simple and readable syntax: Python code looks like pseudocode, making it easier to learn
  • Powerful data science libraries: NumPy, pandas, scikit-learn, matplotlib, and many others
  • Large community: Extensive online resources, tutorials, and libraries
  • Versatility: Can be used for data analysis, machine learning, web scraping, and more
  • Industry adoption: Widely used in data science and tech companies globally
  • Open source: Free to use and modify
  • Interactive environments: Jupyter notebooks allow for interactive data analysis and exploration

1.2 Installing Python

Method 1: Installing Anaconda (Recommended)

Anaconda is a distribution that includes Python and many commonly used libraries for data science. This is the easiest method for beginners.

  1. Visit https://www.anaconda.com/products/individual
  2. Download the Python 3.9 or later version for your operating system (Windows, macOS, or Linux)
  3. Run the installer and follow the prompts
  4. During installation, check "Add Anaconda to my PATH environment variable" (Windows only)
  5. After installation, verify by opening a terminal/command prompt and typing: python --version

Method 2: Direct Python Installation

If you prefer a minimal installation:

  1. Visit https://www.python.org/downloads/
  2. Download Python 3.9 or later
  3. Run the installer
  4. On Windows, check "Add Python 3.x to PATH"
  5. After installation, verify: python --version
  6. Install pip (Python package manager): pip install --upgrade pip

1.3 Verifying Your Installation

Open a terminal (macOS/Linux) or Command Prompt (Windows) and run:

python --version

You should see output like: Python 3.9.x (or your installed version)

1.4 Your First Python Program

Python can be run in two ways:

Interactive Mode (Python Shell)

Open your terminal/command prompt and type:

python

You will see the Python prompt (>>>). Now you can type Python commands:

>>> print("Hello, Data Science World!") Hello, Data Science World! >>> 2 + 2 4 >>> exit()

Script Mode (Writing Python Files)

It is more practical to write Python code in files (.py files) that can be saved and reused.

Step 1: Create a new file called hello.py

Step 2: Write your code in the file

print("Hello, Data Science World!")
x = 2 + 2
print(x)

Step 3: Run the script from your terminal:

python hello.py

1.5 Setting Up Jupyter Notebook

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.

If you installed Anaconda, Jupyter is already included. Start it by typing:

jupyter notebook

This opens a web browser with Jupyter. You can create a new notebook and start writing code in cells.

1.6 Setting Up an IDE (VS Code or PyCharm)

Visual Studio Code (VS Code)

A lightweight, free code editor:

  • Download VS Code from https://code.visualstudio.com/
  • Install the Python extension by Microsoft
  • Create a new folder for your project
  • Open it in VS Code and create a .py file
  • Write your code and run it by right-clicking and selecting "Run Python File"

1.7 Understanding Variables

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.

Variable Naming Rules:

  • Must start with a letter (a-z, A-Z) or underscore (_)
  • Can contain letters, numbers (0-9), and underscores
  • Are case-sensitive (Name and name are different)
  • Should be descriptive and lowercase with underscores (snake_case)
  • Cannot use Python keywords (e.g., if, for, class)

Examples of variable assignment:

# Variable assignment
student_name = "Alice"
student_age = 25
height_cm = 170.5
is_enrolled = True

# Printing variables
print(student_name)
print(student_age)
print(height_cm)
print(is_enrolled)

# Using variables in calculations
average_age = student_age
new_age = student_age + 1
print(new_age)

1.8 Basic Data Types

Python has several basic data types. Understanding them is crucial for working with data.

1. Integers (int)

Whole numbers without decimal points.

age = 25
count = 100
negative = -50
zero = 0

# Checking type
print(type(age)) # Output: <class 'int'>

2. Floats (float)

Numbers with decimal points.

height = 5.9
temperature = 36.5
pi = 3.14159
negative_float = -2.5

# Checking type
print(type(height)) # Output: <class 'float'>

3. Strings (str)

Text enclosed in single quotes, double quotes, or triple quotes.

name = "Alice"
city = 'Lagos'
message = """This is a
multiline string"""

# String operations
greeting = "Hello, " + name
print(greeting) # Output: Hello, Alice

# String length
print(len(name)) # Output: 5

# Accessing characters
print(name[0]) # Output: A (first character)

4. Booleans (bool)

True or False values. Used for logical operations.

is_student = True
has_job = False

# Boolean comparisons
x = 5
y = 10

print(x > y) # Output: False
print(x < y) # Output: True
print(x == y) # Output: False

# Type checking
print(type(is_student)) # Output: <class 'bool'>

Type Conversion

You can convert between data types:

# String to integer
age_str = "25"
age_int = int(age_str)
print(age_int) # Output: 25

# Integer to string
count = 100
count_str = str(count)
print(count_str) # Output: "100"

# String to float
height_str = "5.9"
height_float = float(height_str)
print(height_float) # Output: 5.9

# Integer to float
age_int = 25
age_float = float(age_int)
print(age_float) # Output: 25.0

# Float to integer (truncates decimal)
height = 5.9
height_int = int(height)
print(height_int) # Output: 5

SESSION 2: Operators & Control Flow

Duration: 2 hours

2.1 Arithmetic Operators

Arithmetic operators are used to perform mathematical operations.

Examples:

x = 10
y = 3

print(x + y) # Output: 13
print(x - y) # Output: 7
print(x * y) # Output: 30
print(x / y) # Output: 3.3333...
print(x // y) # Output: 3
print(x % y) # Output: 1
print(x ** y) # Output: 1000

# Real-world example: Calculate area of rectangle
length = 10
width = 5
area = length * width
print(f"Area: {area} square units") # Output: Area: 50 square units

2.2 Comparison Operators

Comparison operators compare values and return True or False.

Examples:

x = 10
y = 5

print(x == y) # Output: False
print(x != y) # Output: True
print(x > y) # Output: True
print(x < y) # Output: False
print(x >= y) # Output: True
print(x <= y) # Output: False

# Comparing strings
name1 = "Alice"
name2 = "Bob"
print(name1 == name2) # Output: False

2.3 Logical Operators

Logical operators combine conditional statements.

Examples:

age = 25
is_student = True

# Using 'and'
print(age > 18 and age < 65) # Output: True
print(age > 30 and is_student) # Output: False

# Using 'or'
print(age < 18 or is_student) # Output: True

# Using 'not'
print(not(age < 18)) # Output: True

# Real-world example: Check if someone can work
working_age = age > 18 and age < 65
print(f"Can work: {working_age}") # Output: Can work: True

2.4 Assignment Operators

Assignment operators are used to assign values to variables.

x = 10
print(x) # Output: 10

x += 5 # x = x + 5
print(x) # Output: 15

x -= 3 # x = x - 3
print(x) # Output: 12

x *= 2 # x = x * 2
print(x) # Output: 24

# Real-world: Update test score
score = 80
score += 5 # Bonus points
print(f"Final score: {score}") # Output: Final score: 85

2.5 Control Flow: If-Else Statements

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.

Basic If Statement

Execute code only if a condition is True.

age = 25

if age >= 18:
print("You are an adult")

# Output: You are an adult

# Another example
score = 45
if score >= 50:
print("You passed")
# This won't execute because score is not >= 50

Important: Note the colon (:) and indentation. Python uses indentation to show which code belongs to the if block.

If-Else Statement

Execute one block if condition is True, another if False.

age = 15

if age >= 18:
print("You are an adult")
else:
print("You are a minor")

# Output: You are a minor

# Real-world example: Grading
score = 75

if score >= 80:
grade = "A"
else:
grade = "Not A"

print(f"Your grade: {grade}") # Output: Your grade: Not A

If-Elif-Else Statement

Check multiple conditions in sequence.

score = 75

if score >= 90:
grade = "A"
elif score >= 80:
grade = "B"
elif score >= 70:
grade = "C"
elif score >= 60:
grade = "D"
else:
grade = "F"

print(f"Your grade: {grade}") # Output: Your grade: C

# Real-world: Discount based on purchase amount
purchase = 150

if purchase >= 200:
discount = 0.20 # 20% discount
elif purchase >= 100:
discount = 0.10 # 10% discount
else:
discount = 0.0 # No discount

final_price = purchase * (1 - discount)
print(f"Final price: {final_price}") # Output: Final price: 135.0

2.6 Loops: For and While

Loops allow you to repeat code multiple times. They are essential for automating repetitive tasks.

The For Loop

Repeats a block of code a specific number of times.

# Loop through numbers 0 to 4
for i in range(5):
print(i)

# Output:
# 0
# 1
# 2
# 3
# 4

# Loop through a list
fruits = ["apple", "banana", "cherry"]
for fruit in fruits:
print(fruit)

# Output:
# apple
# banana
# cherry

# Loop with index
for index, fruit in enumerate(fruits):
print(f"Index {index}: {fruit}")

# Output:
# Index 0: apple
# Index 1: banana
# Index 2: cherry

# Real-world: Calculate sum of numbers
numbers = [10, 20, 30, 40, 50]
total = 0
for num in numbers:
total += num
print(f"Sum: {total}") # Output: Sum: 150

The While Loop

Repeats code while a condition is True.

# Count down
count = 5
while count > 0:
print(count)
count -= 1
print("Blastoff!")

# Output:
# 5
# 4
# 3
# 2
# 1
# Blastoff!

# Real-world: Continue asking until valid input
password = ""
while password != "secret":
password = input("Enter password: ")
if password == "secret":
print("Access granted!")
else:
print("Wrong password, try again")

Break and Continue Statements

Control loop execution with break and continue.

# Break: Exit the loop early
for i in range(10):
if i == 5:
break # Exit loop when i equals 5
print(i)

# Output: 0, 1, 2, 3, 4

# Continue: Skip to next iteration
for i in range(5):
if i == 2:
continue # Skip when i equals 2
print(i)

# Output: 0, 1, 3, 4

# Real-world: Find first number divisible by 7
for i in range(20, 50):
if i % 7 == 0:
print(f"Found: {i}")
break

SESSION 3: Functions, Code Organization & Git Introduction

Duration: 2 hours

3.1 Understanding Functions

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. Key benefits of functions:

  • Reusability: Write once, use many times
  • Organization: Break complex problems into smaller pieces
  • Readability: Clear names describe what code does
  • Maintenance: Easier to fix or update code
  • Testing: Test individual functions in isolation

Defining Functions

def function_name(parameters):
"""Docstring explaining what function does"""
# Function body - code to execute
return result

# Simple function with no parameters
def say_hello():
"""Greets the user"""
print("Hello, World!")

say_hello() # Call the function
# Output: Hello, World!

# Function with parameters
def greet(name):
"""Greets a person by name"""
print(f"Hello, {name}!")

greet("Alice") # Output: Hello, Alice!
greet("Bob") # Output: Hello, Bob!

# Function with return value
def add(a, b):
"""Adds two numbers and returns the result"""
result = a + b
return result

sum_result = add(5, 3)
print(sum_result) # Output: 8

# Function with multiple parameters and return
def calculate_area(length, width):
"""Calculates area of a rectangle"""
area = length * width
return area

rect_area = calculate_area(10, 5)
print(f"Area: {rect_area}") # Output: Area: 50

Default Parameters and Keyword Arguments

# Function with default parameters
def power(base, exponent=2):
"""Raises base to exponent (default 2)"""
return base ** exponent

print(power(5)) # Output: 25 (uses default exponent=2)
print(power(5, 3)) # Output: 125 (exponent=3)

# Function with keyword arguments
def create_profile(name, age, city="Unknown"):
"""Creates a user profile"""
profile = f"Name: {name}, Age: {age}, City: {city}"
return profile

# Positional arguments
print(create_profile("Alice", 25))
# Output: Name: Alice, Age: 25, City: Unknown

# Keyword arguments
print(create_profile(name="Bob", age=30, city="Lagos"))
# Output: Name: Bob, Age: 30, City: Lagos

# Mixed
print(create_profile("Charlie", 28, city="London"))
# Output: Name: Charlie, Age: 28, City: London

Returning Multiple Values

# Function returning multiple values
def get_min_max(numbers):
"""Returns minimum and maximum from a list"""
return min(numbers), max(numbers)

numbers = [10, 5, 20, 15, 8]
min_val, max_val = get_min_max(numbers)
print(f"Min: {min_val}, Max: {max_val}")
# Output: Min: 5, Max: 20

# Function returning results and status
def divide(a, b):
"""Divides a by b, returns result and success status"""
if b == 0:
return None, False # Division by zero
return a / b, True

result, success = divide(10, 2)
if success:
print(f"Result: {result}") # Output: Result: 5.0
else:
print("Error: Cannot divide by zero")

3.2 Variable Scope

Scope determines where a variable can be accessed in your code. Python has two main scopes:

  • Global scope: Variables accessible anywhere in the program
  • Local scope: Variables accessible only within the function
# Global variable
global_var = "I am global"

def my_function():
# Local variable
local_var = "I am local"
print(global_var) # Can access global
print(local_var) # Can access local

my_function()
# Output:
# I am global
# I am local

# print(local_var) # This would cause an error
# local_var is not defined outside the function

# Real-world example
PI = 3.14159 # Global constant

def circle_area(radius):
"""Calculate circle area (local scope for radius and area)"""
area = PI * radius ** 2
return area

print(circle_area(5)) # Output: 78.53975

3.3 Code Organization Best Practices

Writing organized code is crucial for data science work. Here are best practices:

  • Use descriptive names: Use clear, meaningful names for variables and functions
  • Add comments: Explain why code does something, not just what it does
  • Write docstrings: Document what each function does
  • Keep functions focused: Each function should do one thing well
  • Use consistent formatting: Follow PEP 8 style guidelines
  • Avoid global state: Minimize use of global variables
  • Test your code: Verify functions work as expected

Example of well-organized code:

# Calculate student grades
def calculate_grade(score):
"""
Converts numeric score to letter grade

Parameters:
score (int/float): Student's test score

Returns:
str: Letter grade (A, B, C, D, or F)
"""
if score >= 90:
return "A"
elif score >= 80:
return "B"
elif score >= 70:
return "C"
elif score >= 60:
return "D"
else:
return "F"

def process_grades(scores):
"""
Processes a list of scores and returns grades

Parameters:
scores (list): List of student scores

Returns:
list: Corresponding letter grades
"""
grades = []
for score in scores:
grade = calculate_grade(score)
grades.append(grade)
return grades

# Usage
student_scores = [85, 92, 78, 88, 95]
student_grades = process_grades(student_scores)

for score, grade in zip(student_scores, student_grades):
print(f"Score: {score} -> Grade: {grade}")

# Output:
# Score: 85 -> Grade: B
# Score: 92 -> Grade: A
# Score: 78 -> Grade: C
# Score: 88 -> Grade: B
# Score: 95 -> Grade: A

3.4 PEP 8: Python Style Guide

PEP 8 is the official style guide for Python code. Following it makes code readable and professional.

  • Use lowercase with underscores for variables: my_variable = 5 (not myVariable or MyVariable)
  • Function names also lowercase with underscores: def my_function(): (not myFunction)
  • Class names use CamelCase: class MyClass:
  • Use 4 spaces for indentation: Never mix tabs and spaces
  • Line length max 79 characters: Makes code readable on all screens
  • Use meaningful names: name = "Alice" (not n or x)
  • Add spaces around operators: x = y + 2 (not x=y+2)
  • No spaces before colons in arguments: def func(a, b): (not def func(a , b):)

3.5 Introduction to Git and GitHub

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:

  • Backing up your code
  • Tracking changes over time
  • Collaborating with others
  • Building a portfolio to showcase your work

Installing Git

Download and install from https://git-scm.com/

Basic Git Concepts

  • Repository: A folder containing your project and its history
  • Commit: A saved version of your code with a message describing changes
  • Branch: A parallel version of your code for developing features
  • Pull Request: A request to merge changes from one branch to another

Setting Up Your First Repository

  1. Create a folder for your project
  2. Navigate into the folder: cd my_project
  3. Initialize Git: git init
  4. Add files: git add hello.py
  5. Commit changes: git commit -m "Initial commit"
  6. Check status: git status
# Initialize a new repository
git init

# Check status
git status

# Add a file to staging area
git add hello.py

# Commit with a message
git commit -m "Add hello.py script"

# View commit history
git log

# Create a new branch
git branch feature/new-function

# Switch to new branch
git checkout feature/new-function

# Make changes and commit
git add .
git commit -m "Add new function"

# Switch back to main
git checkout main

# Merge branch into main
git merge feature/new-function

Creating a GitHub Repository

  1. Create a GitHub account at https://github.com if you don't have one
  2. Click "New" to create a new repository
  3. Name your repository (e.g., data-science-learning)
  4. Add a description
  5. Initialize with a README (recommended)
  6. Click "Create repository"
  7. Follow instructions to push your local code to GitHub
# Add GitHub repository as remote
git remote add origin https://github.com/yourusername/repository-name.git

# Push local commits to GitHub
git push -u origin main

# Clone a repository
git clone https://github.com/username/repository.git

# Pull latest changes from GitHub
git pull origin main

Week 1 Summary

By completing Week 1, you have learned:

  • How to install and configure Python and Jupyter Notebook
  • Basic data types: int, float, str, bool
  • Variables and how to use them
  • Arithmetic, comparison, and logical operators
  • Control flow with if-elif-else statements
  • Loops with for and while statements
  • Functions and how to organize code
  • Variable scope and best practices
  • Introduction to Git and GitHub
  • PEP 8 style guidelines

Week 1 Assignments

Assignment 1: Python Setup and First Script

Create a Python script that:

  • Defines variables for a person (name, age, city, height)
  • Uses arithmetic operations to calculate BMI (weight in kg / (height in m)^2)
  • Uses if-elif-else to classify BMI (underweight < 18.5, normal 18.5-24.9, overweight 25-29.9, obese >= 30)
  • Prints the results with proper formatting

Assignment 2: Functions and Control Flow

Write functions that:

  • Convert temperature from Celsius to Fahrenheit: F = (C × 9/5) + 32
  • Check if a number is even or odd
  • Calculate factorial of a number (use loops or recursion)
  • Find the maximum number in a list without using max()

Test each function with different inputs

Assignment 3: GitHub Repository

Create a GitHub repository for your learning:

  • Initialize a local Git repository
  • Create a README.md file describing your learning goals
  • Add your scripts from Assignments 1 and 2
  • Commit your changes with meaningful messages
  • Push to GitHub
  • Share the link to your repository
  • Write a function that converts hours, minutes, and seconds to total seconds
  • Write a function that checks if a number is prime
  • Create a function that generates the Fibonacci sequence up to n
  • Write a calculator that takes two numbers and an operator (+, -, *, /)
  • Create a program that plays a guessing game (user guesses a random number)
  • Write a function that converts currency between different units

Additional Resources

Books

  • Python Crash Course by Eric Matthes - Beginner-friendly introduction
  • Think Python by Allen Downey - Great for understanding programming concepts
  • Chapters 2-3 from "Python for Data Analysis" by Wes McKinney

Online Resources

  • Python Official Documentation: https://docs.python.org/3/
  • Real Python: https://realpython.com/ - Excellent tutorials
  • GeeksforGeeks: https://www.geeksforgeeks.org/python-programming-language/
  • Codecademy: Interactive Python courses

Practice Platforms

  • LeetCode: https://leetcode.com/ - Coding challenges
  • HackerRank: https://www.hackerrank.com/ - Practice problems
  • Codewars: https://www.codewars.com/ - Gamified coding