Understanding Basic Python Concepts

This module covers the fundamental concepts of Python programming, including data types, data structures, functions, and error handling. By the end of this module, you should have a solid understanding of the basics of Python and be able to write simple programs.

Data Types

Python has several built-in data types that are essential for handling different kinds of information:

Numeric Types
int (integers), float (decimals), complex
Sequence Types
list, tuple, range
Mapping Type
dict (Key-Value pairs)
Boolean Type
bool (True/False)

Data Structures

Effectively using data structures is key to writing efficient Python code.

Lists

Ordered, mutable collections. Great for storing sequences of items.

my_list = [1, 2, 3, "apple"]
my_list.append("banana")
print(my_list[0])  # Output: 1

Dictionaries

Unordered collections of key-value pairs. Ideal for lookups.

my_dict = {'name': 'Alice', 'role': 'Developer'}
print(my_dict['name'])  # Output: Alice

NumPy Arrays

Foundation for ML. Homogeneous collections enabling fast mathematical operations.

import numpy as np
my_array = np.array([1, 2, 3])
print(my_array * 2)  # Output: [2 4 6]

Functions

Functions allow you to encapsulate logic and reuse code.

def calculate_area(radius):
    """Calculates the area of a circle."""
    pi = 3.14159
    return pi * (radius ** 2)

result = calculate_area(5)
print(f"Area: {result}")

Example: Basic Programs

Here are some standard algorithms implemented in Python.

Fibonacci Series

def fibonnaci_series(n):
    """Prints n terms of the Fibonacci series."""
    a, b = 0, 1
    print(a, b, end=' ')
    for i in range(n - 2):
        c = a + b
        print(c, end=' ')
        a, b = b, c
    print()

# Run it
fibonnaci_series(10)

Matrix Addition

def add_matrices(mat1, mat2):
    # Create result matrix
    final = [[0 for _ in range(len(mat1[0]))] for _ in range(len(mat1))]
            
    for i in range(len(mat1)):
        for j in range(len(mat1[i])):
            final[i][j] = mat1[i][j] + mat2[i][j]
            
    return final

m1 = [[1, 2], [3, 4]]
m2 = [[5, 6], [7, 8]]
print(add_matrices(m1, m2))