Chapter 1: Python Basics

📖 Reading Time: 20-25 min 💻 Code Examples: 10 📝 Exercises: 5 📊 Difficulty: Beginner

Master the fundamentals of Python programming

Introduction

The first step in learning machine learning is to build a solid foundation in Python programming. Python is the most widely used programming language for machine learning, characterized by its simple and readable syntax.

In this chapter, you will learn the following:

1. Variables and Data Types

1.1 Basic Data Types

Python primarily has the following data types:

Data Type Description Examples
int Integer 42, -10, 0
float Floating-point number 3.14, -0.5, 2.0
str String "Hello", 'Python'
bool Boolean True, False
list List (array) [1, 2, 3], ["a", "b"]
dict Dictionary (key-value pairs) {"name": "Alice", "age": 25}

Example 1: Variables and Data Types

# Integer
age = 25
print(f"Age: {age}, Type: {type(age)}")  # Output: Age: 25, Type: <class 'int'>

# Floating-point number
height = 170.5
print(f"Height: {height}cm, Type: {type(height)}")  # Output: Height: 170.5cm, Type: <class 'float'>

# String
name = "Taro"
print(f"Name: {name}, Type: {type(name)}")  # Output: Name: Taro, Type: <class 'str'>

# Boolean
is_student = True
print(f"Student: {is_student}, Type: {type(is_student)}")  # Output: Student: True, Type: <class 'bool'>

# List
scores = [85, 90, 78, 92]
print(f"Scores: {scores}, Type: {type(scores)}")  # Output: Scores: [85, 90, 78, 92], Type: <class 'list'>

# Dictionary
person = {"name": "Taro", "age": 25, "city": "Tokyo"}
print(f"Person: {person}, Type: {type(person)}")  # Output: Person: {'name': 'Taro', 'age': 25, 'city': 'Tokyo'}, Type: <class 'dict'>

1.2 Working with Lists and Dictionaries

Example 2: Basic List Operations

# Creating a list
numbers = [1, 2, 3, 4, 5]

# Accessing elements (zero-based index)
print(numbers[0])    # Output: 1
print(numbers[-1])   # Output: 5 (the last element)

# Slicing
print(numbers[1:4])  # Output: [2, 3, 4] (from index 1 to 3)
print(numbers[:3])   # Output: [1, 2, 3] (the first three)
print(numbers[2:])   # Output: [3, 4, 5] (from index 2 to the end)

# Adding an element
numbers.append(6)
print(numbers)       # Output: [1, 2, 3, 4, 5, 6]

# Removing an element
numbers.remove(3)
print(numbers)       # Output: [1, 2, 4, 5, 6]

# Length of the list
print(len(numbers))  # Output: 5

Example 3: Basic Dictionary Operations

# Creating a dictionary
student = {
    "name": "Hanako",
    "age": 20,
    "major": "Information Science"
}

# Accessing values
print(student["name"])        # Output: Hanako
print(student.get("age"))     # Output: 20

# Adding and updating values
student["gpa"] = 3.8
student["age"] = 21
print(student)  # Output: {'name': 'Hanako', 'age': 21, 'major': 'Information Science', 'gpa': 3.8}

# Checking for keys
print("name" in student)      # Output: True
print("email" in student)     # Output: False

# All keys and values
print(student.keys())         # Output: dict_keys(['name', 'age', 'major', 'gpa'])
print(student.values())       # Output: dict_values(['Hanako', 21, 'Information Science', 3.8])

2. Defining and Using Functions

A function is a reusable block of code. You define it using the def keyword.

Example 4: Function Basics

# Function without arguments
def greet():
    print("Hello!")

greet()  # Output: Hello!

# Function with an argument
def greet_person(name):
    print(f"Hello, {name}!")

greet_person("Taro")  # Output: Hello, Taro!

# Function with a return value
def add(a, b):
    return a + b

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

# Default arguments
def power(base, exponent=2):
    return base ** exponent

print(power(3))      # Output: 9 (3 squared)
print(power(3, 3))   # Output: 27 (3 cubed)

# Multiple return values
def calculate(a, b):
    return a + b, a - b, a * b, a / b

sum_val, diff, prod, quot = calculate(10, 2)
print(f"Sum: {sum_val}, Difference: {diff}, Product: {prod}, Quotient: {quot}")
# Output: Sum: 12, Difference: 8, Product: 20, Quotient: 5.0
graph LR A[Function call] --> B[Pass arguments] B --> C[Process inside function] C --> D[Return value] D --> E[Use at call site] style A fill:#e3f2fd style C fill:#fff3e0 style E fill:#e8f5e9

3. Control Flow

3.1 Conditionals (if statements)

Example 5: if Statement Basics

# Basic if statement
score = 85

if score >= 90:
    print("Excellent!")
elif score >= 70:
    print("Good.")
elif score >= 60:
    print("Pass.")
else:
    print("Fail.")
# Output: Good.

# Multiple conditions
age = 25
has_license = True

if age >= 18 and has_license:
    print("You can drive.")
else:
    print("You cannot drive.")
# Output: You can drive.

# Ternary operator
temperature = 25
weather = "hot" if temperature > 30 else "cool"
print(weather)  # Output: cool

3.2 Loops (for and while statements)

Example 6: for and while Statements

# for statement (iterating over list elements)
fruits = ["apple", "banana", "orange"]
for fruit in fruits:
    print(f"Favorite fruit: {fruit}")
# Output:
# Favorite fruit: apple
# Favorite fruit: banana
# Favorite fruit: orange

# Looping with the range function
for i in range(5):
    print(i)
# Output: 0, 1, 2, 3, 4

# while statement
count = 0
while count < 5:
    print(f"Count: {count}")
    count += 1
# Output: Count: 0, Count: 1, ..., Count: 4

# enumerate (iterating with an index)
for index, fruit in enumerate(fruits):
    print(f"{index}: {fruit}")
# Output:
# 0: apple
# 1: banana
# 2: orange

# Iterating over a dictionary
student = {"name": "Taro", "age": 20, "major": "CS"}
for key, value in student.items():
    print(f"{key}: {value}")
# Output:
# name: Taro
# age: 20
# major: CS
graph TD A[Start] --> B{Check condition} B -->|True| C[Execute body] C --> D[Update] D --> B B -->|False| E[End] style A fill:#e3f2fd style C fill:#fff3e0 style E fill:#e8f5e9

4. List Comprehensions

List comprehensions are a powerful feature for creating lists concisely.

Example 7: List Comprehensions

# The conventional way
squares = []
for i in range(10):
    squares.append(i ** 2)
print(squares)  # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# List comprehension (written on a single line)
squares = [i ** 2 for i in range(10)]
print(squares)  # Output: [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

# Conditional list comprehension
even_squares = [i ** 2 for i in range(10) if i % 2 == 0]
print(even_squares)  # Output: [0, 4, 16, 36, 64]

# Transforming strings
words = ["hello", "world", "python"]
upper_words = [word.upper() for word in words]
print(upper_words)  # Output: ['HELLO', 'WORLD', 'PYTHON']

# Nested list comprehension
matrix = [[i * j for j in range(1, 4)] for i in range(1, 4)]
print(matrix)
# Output: [[1, 2, 3], [2, 4, 6], [3, 6, 9]]

# Dictionary comprehension
numbers = [1, 2, 3, 4, 5]
squares_dict = {n: n ** 2 for n in numbers}
print(squares_dict)  # Output: {1: 1, 2: 4, 3: 9, 4: 16, 5: 25}

5. File Input/Output

Example 8: Reading and Writing Files

# Writing to a file
with open("sample.txt", "w", encoding="utf-8") as f:
    f.write("Hello, Python!\n")
    f.write("Let's learn machine learning.\n")

# Reading a file (entire contents)
with open("sample.txt", "r", encoding="utf-8") as f:
    content = f.read()
    print(content)

# Reading a file (line by line)
with open("sample.txt", "r", encoding="utf-8") as f:
    for line in f:
        print(line.strip())  # strip() removes the newline

# Appending to a file
with open("sample.txt", "a", encoding="utf-8") as f:
    f.write("Adding a new line\n")

# Reading and writing CSV files
import csv

# Writing to a CSV
data = [
    ["Name", "Age", "City"],
    ["Taro", "25", "Tokyo"],
    ["Hanako", "30", "Osaka"]
]

with open("data.csv", "w", newline="", encoding="utf-8") as f:
    writer = csv.writer(f)
    writer.writerows(data)

# Reading a CSV
with open("data.csv", "r", encoding="utf-8") as f:
    reader = csv.reader(f)
    for row in reader:
        print(row)

6. Error Handling (try-except)

Example 9: Exception Handling

# Basic exception handling
try:
    result = 10 / 0  # ZeroDivisionError
except ZeroDivisionError:
    print("Cannot divide by zero!")
# Output: Cannot divide by zero!

# Handling multiple exceptions
def safe_divide(a, b):
    try:
        return a / b
    except ZeroDivisionError:
        print("Error: cannot divide by zero")
        return None
    except TypeError:
        print("Error: please enter a number")
        return None

print(safe_divide(10, 2))     # Output: 5.0
print(safe_divide(10, 0))     # Output: Error: cannot divide by zero, None
print(safe_divide(10, "a"))   # Output: Error: please enter a number, None

# else and finally
try:
    number = int(input("Enter a number: "))
    result = 100 / number
except ValueError:
    print("Error: please enter a number")
except ZeroDivisionError:
    print("Error: please enter a non-zero value")
else:
    print(f"Result: {result}")  # Runs only when there is no error
finally:
    print("Processing complete")  # Always runs

# Custom exception
class NegativeNumberError(Exception):
    pass

def sqrt(x):
    if x < 0:
        raise NegativeNumberError("Cannot compute the square root of a negative number")
    return x ** 0.5

try:
    print(sqrt(16))   # Output: 4.0
    print(sqrt(-4))   # Raises NegativeNumberError
except NegativeNumberError as e:
    print(f"Error: {e}")

7. Practical Example: Simple Data Processing

Example 10: Student Grade Processing Program

# Student data
students = [
    {"name": "Taro", "scores": [85, 90, 78]},
    {"name": "Hanako", "scores": [92, 88, 95]},
    {"name": "Jiro", "scores": [70, 75, 80]},
    {"name": "Momoko", "scores": [88, 91, 87]}
]

# Function to calculate the average score
def calculate_average(scores):
    return sum(scores) / len(scores)

# Function to return a letter grade
def get_grade(average):
    if average >= 90:
        return "A"
    elif average >= 80:
        return "B"
    elif average >= 70:
        return "C"
    elif average >= 60:
        return "D"
    else:
        return "F"

# Process each student's grades
results = []
for student in students:
    avg = calculate_average(student["scores"])
    grade = get_grade(avg)
    results.append({
        "name": student["name"],
        "average": avg,
        "grade": grade
    })

# Display the results
print("=" * 50)
print("Grade Report")
print("=" * 50)
for result in results:
    print(f"{result['name']}: Average {result['average']:.2f} (Grade: {result['grade']})")

# Find the top-scoring student
best_student = max(results, key=lambda x: x["average"])
print("=" * 50)
print(f"Top student: {best_student['name']} ({best_student['average']:.2f})")

# Extract excellent students with a list comprehension
excellent_students = [r["name"] for r in results if r["average"] >= 85]
print(f"Excellent students (average 85 or above): {', '.join(excellent_students)}")
graph TD A[Data input] --> B[Compute average] B --> C[Assign grade] C --> D[Store results] D --> E[Output report] E --> F[Display statistics] style A fill:#e3f2fd style C fill:#fff3e0 style F fill:#e8f5e9

Summary

In this chapter, you learned the fundamentals of Python programming:

Next step: Using these fundamentals, Chapter 2 covers numerical computing with NumPy.

Exercises

Exercise 1: FizzBuzz Problem

Problem: Write a program that prints the numbers from 1 to 100. However, for multiples of 3 print "Fizz" instead of the number, for multiples of 5 print "Buzz", and for numbers that are multiples of both 3 and 5 print "FizzBuzz".

# Example solution
for i in range(1, 101):
    if i % 15 == 0:  # Multiple of both 3 and 5 (multiple of 15)
        print("FizzBuzz")
    elif i % 3 == 0:
        print("Fizz")
    elif i % 5 == 0:
        print("Buzz")
    else:
        print(i)
Exercise 2: Prime Number Check Function

Problem: Create a function is_prime(n) that determines whether a given number is prime.

# Example solution
def is_prime(n):
    """Prime number check function"""
    if n < 2:
        return False
    for i in range(2, int(n ** 0.5) + 1):
        if n % i == 0:
            return False
    return True

# Test
test_numbers = [2, 3, 4, 17, 20, 29, 100]
for num in test_numbers:
    result = "prime" if is_prime(num) else "not prime"
    print(f"{num}: {result}")
Exercise 3: List Comprehension

Problem: Using a list comprehension, create a list of the numbers from 1 to 100 that are multiples of 3 or 5 (or both).

# Example solution
multiples = [i for i in range(1, 101) if i % 3 == 0 or i % 5 == 0]
print(multiples)
print(f"Count: {len(multiples)}")
print(f"Sum: {sum(multiples)}")

# Output: [3, 5, 6, 9, 10, 12, 15, ..., 100]
# Count: 47
# Sum: 2418
Exercise 4: Dictionary Aggregation

Problem: Create a function count_chars(text) that returns a dictionary mapping each character to the number of times it appears in the string.

# Example solution
def count_chars(text):
    """Count the occurrences of each character"""
    char_count = {}
    for char in text:
        if char in char_count:
            char_count[char] += 1
        else:
            char_count[char] = 1
    return char_count

# Alternatively, using the dictionary's get() method
def count_chars_v2(text):
    char_count = {}
    for char in text:
        char_count[char] = char_count.get(char, 0) + 1
    return char_count

# Test
text = "hello world"
result = count_chars(text)
print(result)
# Output: {'h': 1, 'e': 1, 'l': 3, 'o': 2, ' ': 1, 'w': 1, 'r': 1, 'd': 1}
Exercise 5: File Processing

Problem: Create a program that reads a text file, counts the number of words in each line, and writes the results to a new file.

# Example solution
def count_words_in_file(input_file, output_file):
    """Count the number of words in each line of a file"""
    try:
        with open(input_file, "r", encoding="utf-8") as f:
            lines = f.readlines()

        with open(output_file, "w", encoding="utf-8") as f:
            f.write("line_number,word_count,content\n")
            for i, line in enumerate(lines, 1):
                word_count = len(line.split())
                f.write(f"{i},{word_count},{line.strip()}\n")

        print(f"Results saved to {output_file}.")

    except FileNotFoundError:
        print(f"Error: {input_file} not found")
    except Exception as e:
        print(f"An error occurred: {e}")

# Create a test file
with open("test.txt", "w", encoding="utf-8") as f:
    f.write("Python is great\n")
    f.write("Machine learning is fun\n")
    f.write("Let's learn together\n")

# Run the function
count_words_in_file("test.txt", "result.txt")

Disclaimer