Python Common Standard Libraries

PythonPythonBeginner
Practice Now

Introduction

In an enchanted maritime world filled with mystery and magic, a world where seafarers navigate not just the treacherous waters but also the arcane flows of magic, there exists a legend known for his formidable skills in both sailing and spell-craft—the notorious Pirate Captain Magellan the Bewitched. Magellan's ability to harness the powers of Python's Common Standard Libraries has been the cornerstone of his success in outsmarting rival pirates and discovering hidden treasures.

As a member of Magellan's crew, your quest is to master the same set of powerful Python libraries to help navigate your ship through a series of challenges. The fate of The Enchanted Marauder, the most feared ship on the high seas, lies in your hands. Will you embrace the code of Python and become an invaluable asset to Captain Magellan? The adventure ahead will test your skills and cunning in equal measure!


Skills Graph

%%%%{init: {'theme':'neutral'}}%%%% flowchart RL python(("`Python`")) -.-> python/ModulesandPackagesGroup(["`Modules and Packages`"]) python/ModulesandPackagesGroup -.-> python/standard_libraries("`Common Standard Libraries`") subgraph Lab Skills python/standard_libraries -.-> lab-271593{{"`Python Common Standard Libraries`"}} end

In this step, you are tasked with charting the course for your forthcoming journey. Calculate the best route using the math module and estimate the time of arrival with the help of the datetime module.

First, open a script named chart_course.py in the ~/project directory. This script will calculate the distance to your next destination based on latitude and longitude coordinates.

import math

## Coordinates of your current location and the destination (in degrees)
current_location = (0, 0)
destination = (10, 10)

def calculate_distance(loc1, loc2):
    ## Convert degrees to radians
    lat1, lon1 = map(math.radians, loc1)
    lat2, lon2 = map(math.radians, loc2)

    ## Haversine formula
    dlon = lon2 - lon1
    dlat = lat2 - lat1
    a = math.sin(dlat/2)**2 + math.cos(lat1) * math.cos(lat2) * math.sin(dlon/2)**2
    c = 2 * math.asin(math.sqrt(a))
    r = 6371  ## Radius of Earth in kilometers
    return c * r

## Estimate the distance
distance = calculate_distance(current_location, destination)
print(f"The distance to the destination is {distance:.2f} kilometers.")

Now, estimate the time of arrival using datetime:

from datetime import datetime, timedelta

## Assume an average ship speed of 10 km/h
average_speed = 10

## Calculate the time of arrival
time_to_destination = timedelta(hours=distance / average_speed)
arrival_time = datetime.now() + time_to_destination

print(f"Estimated time of arrival: {arrival_time.strftime('%Y-%m-%d %H:%M:%S')}")

Execute your script by running the following command in your terminal:

python ~/project/chart_course.py

The information below should be displayed on your terminal:

The distance to the destination is 1568.52 kilometers.
Estimated time of arrival: 2024-01-04 09:40:36

Managing Inventory with Collections

Captain Magellan keeps his inventory sorted and accessible with the help of Python's collections module. Your mission is to organize the ship's supply data using a Counter from the collections module.

Open a script named manage_inventory.py in the ~/project directory:

from collections import Counter

## Inventory list
inventory = ['potion', 'dagger', 'potion', 'gold coin', 'gold coin', 'ruby']

inventory_counter = Counter(inventory)

## Display inventory count
for item, count in inventory_counter.items():
    print(f"{item.title()}: {count}")

## Add items to your inventory
loot = ['gold coin', 'emerald', 'potion']
inventory_counter.update(loot)

print("\nUpdated inventory:")
for item, count in inventory_counter.items():
    print(f"{item.title()}: {count}")

To manage the inventory, run:

python ~/project/manage_inventory.py

The information below should be displayed on your terminal:

Potion: 2
Dagger: 1
Gold Coin: 2
Ruby: 1

Updated inventory:
Potion: 3
Dagger: 1
Gold Coin: 3
Ruby: 1
Emerald: 1

Summary

In this lab, you were transported into the world of enchantments and maritime adventures. We designed engaging scenarios that leveraged Python's Common Standard Libraries as tools for navigating challenges, similar to how Captain Magellan would on his voyages. You've learned how to perform geographical calculations with math and datetime, managed an inventory of magical items with collections, and would go on to work with file systems and other common tasks with additional standard libraries.

As you completed each task, you not only gained proficiency in using these libraries but also contributed to the successful journey of The Enchanted Marauder. These exercises set the foundations for being an effective Python programmer — able to tackle practical problems with creativity and efficiency. May the winds of knowledge continue to fill your sails!

Other Python Tutorials you may like