DEV Community

Cover image for Day 14 of #100daysofMiva || Mastering Python Modules, JSON, Math, and Dates
TD!
TD!

Posted on

Day 14 of #100daysofMiva || Mastering Python Modules, JSON, Math, and Dates

It's Day #14 and I'm back to where I left my simple python projects before running off to flask. Lol! Coding can be exciting, and frustrating too sometimes (or is it most times...). Anyway, you know better via your experiences. That's why I'm excited documenting mine. So today, I learnt Python modules, polymorphism, JSON, Math, Datetime, Scope and iterators. Let's dive in.

1. Python Modules: Building Reusable Code Libraries

Modules in Python are files containing Python code (functions, variables, or classes) that can be reused across different scripts or projects. Creating modules promotes code reuse, making your projects cleaner and more modular.

Creating and Importing Modules:

A module is simply a Python file saved with the .py extension. You can define functions, variables, and classes in one module and import them into another.

Example: Creating and Using a Module

  1. Create a file called mymodule.py with the following content:
# mymodule.py
def greeting(name):
    print(f"Hello, {name}")
Enter fullscreen mode Exit fullscreen mode
  1. Now, import the module in another Python script:
import mymodule

mymodule.greeting("Jonathan")  # Output: Hello, Jonathan
Enter fullscreen mode Exit fullscreen mode

You can also give an alias to a module when importing:

import mymodule as mx

mx.greeting("Jane")  # Output: Hello, Jane
Enter fullscreen mode Exit fullscreen mode

Using Built-in Modules:

Python comes with many built-in modules. For instance, you can use the platform module to retrieve system information:

import platform

print(platform.system())  # Output: The OS you're running (e.g., Windows, Linux, etc.)
Enter fullscreen mode Exit fullscreen mode

2. Working with JSON in Python: Parsing and Generating JSON Data

JSON (JavaScript Object Notation) is widely used for transmitting data in web applications. Python provides the json module to parse and generate JSON.

Parsing JSON:

You can convert a JSON string into a Python dictionary using json.loads().

import json

json_data = '{ "name": "John", "age": 30, "city": "New York" }'
parsed_data = json.loads(json_data)

print(parsed_data['age'])  # Output: 30
Enter fullscreen mode Exit fullscreen mode

Converting Python Objects to JSON:

You can also convert Python objects (e.g., dict, list, tuple) into a JSON string using json.dumps().

Example:

import json

python_obj = {"name": "John", "age": 30, "city": "New York"}
json_string = json.dumps(python_obj)

print(json_string)  # Output: {"name": "John", "age": 30, "city": "New York"}
Enter fullscreen mode Exit fullscreen mode

Formatting and Customizing JSON Output:

You can make the JSON string more readable by using the indent parameter:

json_string = json.dumps(python_obj, indent=4)
print(json_string)
Enter fullscreen mode Exit fullscreen mode

This outputs a well-formatted JSON string:

{
    "name": "John",
    "age": 30,
    "city": "New York"
}
Enter fullscreen mode Exit fullscreen mode

3. Python Math: Performing Mathematical Operations

Python provides both built-in functions and the math module for performing a variety of mathematical tasks.

Basic Math Functions:

min() and max(): To find the minimum and maximum values in an iterable:

print(min(5, 10, 25))  # Output: 5
print(max(5, 10, 25))  # Output: 25
Enter fullscreen mode Exit fullscreen mode

abs(): Returns the absolute value of a number:

print(abs(-7.25))  # Output: 7.25
Enter fullscreen mode Exit fullscreen mode

pow(): Calculates the power of a number:

print(pow(4, 3))  # Output: 64 (4 to the power of 3)
Enter fullscreen mode Exit fullscreen mode

The Math Module:

For advanced mathematical operations, the math module offers an extensive set of functions.

  • Square Root: Using math.sqrt():
import math

print(math.sqrt(64))  # Output: 8.0
Enter fullscreen mode Exit fullscreen mode
  • Ceiling and Floor: Rounds a number up or down:
print(math.ceil(1.4))  # Output: 2
print(math.floor(1.4))  # Output: 1
Enter fullscreen mode Exit fullscreen mode
  • PI Constant: Accessing the value of π:
print(math.pi)  # Output: 3.141592653589793
Enter fullscreen mode Exit fullscreen mode

4. Working with Dates: Managing Time in Python

Python’s datetime module helps manage dates and times. You can generate the current date, extract specific components (like year, month, day), or manipulate date objects.

Getting the Current Date and Time:

The datetime.now() function returns the current date and time.

import datetime

current_time = datetime.datetime.now()
print(current_time)
# Output: 2024-09-06 05:15:51.590708 (example)
Enter fullscreen mode Exit fullscreen mode

Creating a Specific Date:

You can create a custom date using the datetime() constructor.

custom_date = datetime.datetime(2020, 5, 17)
print(custom_date)  # Output: 2020-05-17 00:00:00
Enter fullscreen mode Exit fullscreen mode

Formatting Dates with strftime():

You can format date objects into strings using strftime().

Example:

formatted_date = custom_date.strftime("%B %d, %Y")
print(formatted_date)  # Output: May 17, 2020
Enter fullscreen mode Exit fullscreen mode

Here's a table of some common format codes used in strftime():

Directive Description Example
%a Short weekday Wed
%A Full weekday Wednesday
%b Short month name Dec
%B Full month name December
%Y Year (full) 2024
%H Hour (24-hour format) 17
%I Hour (12-hour format) 05

Polymorphism in Python

Polymorphism refers to the ability of different objects to be treated as instances of the same class through a common interface. It allows methods to do different things based on the object it is acting upon.

Method Overriding
In Python, polymorphism is often achieved through method overriding. A subclass can provide a specific implementation of a method that is already defined in its superclass.

Example:


class Animal:
    def make_sound(self):
        pass

class Dog(Animal):
    def make_sound(self):
        return "Woof!"

class Cat(Animal):
    def make_sound(self):
        return "Meow!"

# Using polymorphism
def animal_sound(animal):
    print(animal.make_sound())

dog = Dog()
cat = Cat()

animal_sound(dog)  # Output: Woof!
animal_sound(cat)  # Output: Meow!
Enter fullscreen mode Exit fullscreen mode

In the above example, animal_sound() can handle both Dog and Cat objects because they both implement the make_sound() method, demonstrating polymorphism.

Operator Overloading

Polymorphism also allows you to define how operators behave with user-defined classes by overloading them.

Example:


class Vector:
    def __init__(self, x, y):
        self.x = x
        self.y = y

    def __add__(self, other):
        return Vector(self.x + other.x, self.y + other.y)

    def __repr__(self):
        return f"Vector({self.x}, {self.y})"

v1 = Vector(2, 3)
v2 = Vector(4, 1)
v3 = v1 + v2

print(v3)  # Output: Vector(6, 4)
Here, the + operator is overloaded to handle Vector objects, allowing us to add vectors using the + operator.

2. Iterators in Python
An iterator is an object that allows you to traverse through a container, such as a list or tuple, and retrieve elements one by one. Python iterators implement two main methods: __iter__() and __next__().

Creating an Iterator
You can create your own iterator by defining a class with __iter__() and __next__() methods.

Example:

python
Copy code
class CountDown:
    def __init__(self, start):
        self.start = start

    def __iter__(self):
        return self

    def __next__(self):
        if self.start <= 0:
            raise StopIteration
        current = self.start
        self.start -= 1
        return current

# Using the iterator

cd = CountDown(5)
for number in cd:
    print(number)
# Output: 5, 4, 3, 2, 1
Enter fullscreen mode Exit fullscreen mode

In this example, CountDown is an iterator that counts down from a starting number to 1.

Using Built-in Iterators
Python provides built-in iterators such as enumerate(), map(), and filter().

Example:


numbers = [1, 2, 3, 4, 5]
squared = map(lambda x: x ** 2, numbers)

for num in squared:
    print(num)
# Output: 1, 4, 9, 16, 25
Enter fullscreen mode Exit fullscreen mode

Here, map() applies a function to all items in the list and returns an iterator.

Scope in Python

Scope determines the visibility of variables in different parts of the code. Python uses the LEGB rule to resolve names: Local, Enclosing, Global, and Built-in.

Local Scope

Variables created inside a function are local to that function.

Example:


def my_func():
    x = 10  # Local variable
    print(x)

my_func()
# Output: 10
Enter fullscreen mode Exit fullscreen mode

Here, x is accessible only within my_func().

Global Scope

Variables created outside any function are global and accessible from anywhere in the code.

Example:

Copy code
x = 20  # Global variable

def my_func():
    print(x)

my_func()
print(x)
# Output: 20, 20
Enter fullscreen mode Exit fullscreen mode

Enclosing Scope

In nested functions, an inner function can access variables from its enclosing (outer) function.

Example:


def outer_func():
    x = 30

    def inner_func():
        print(x)  # Accessing variable from outer function

    inner_func()

outer_func()
# Output: 30
Enter fullscreen mode Exit fullscreen mode

Global Keyword

To modify a global variable inside a function, use the global keyword.

Example:


x = 50

def my_func():
    global x
    x = 60

my_func()
print(x)
# Output: 60
Enter fullscreen mode Exit fullscreen mode

Nonlocal Keyword

The nonlocal keyword allows you to modify a variable in the nearest enclosing scope that is not global.

Example:


def outer_func():
    x = 70

    def inner_func():
        nonlocal x
        x = 80

    inner_func()
    print(x)

outer_func()
# Output: 80
Enter fullscreen mode Exit fullscreen mode

In this example, nonlocal allows inner_func() to modify the x variable in outer_func().

Check out my #100daysofMiva repo on GitHub. Follow, Star and Share.

Top comments (0)