Data Science Fundamentals Course
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:
Week 1 is divided into three 2-hour sessions:
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?
Anaconda is a distribution that includes Python and many commonly used libraries for data science. This is the easiest method for beginners.
If you prefer a minimal 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)
Python can be run in two ways:
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()
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
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.
A lightweight, free code editor:
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:
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)
Python has several basic data types. Understanding them is crucial for working with data.
Whole numbers without decimal points.
age = 25 count = 100 negative = -50 zero = 0 # Checking type print(type(age)) # Output: <class 'int'>
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'>
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)
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'>
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
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
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
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
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
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.
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.
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
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
Loops allow you to repeat code multiple times. They are essential for automating repetitive tasks.
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
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")
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
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:
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
# 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
# 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")
Scope determines where a variable can be accessed in your code. Python has two main scopes:
# 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
Writing organized code is crucial for data science work. Here are best practices:
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
PEP 8 is the official style guide for Python code. Following it makes code readable and professional.
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:
Download and install from https://git-scm.com/
# 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
# 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
By completing Week 1, you have learned:
Create a Python script that:
Write functions that:
Test each function with different inputs
Create a GitHub repository for your learning: