Imports

 Imports:

Way to use files with codes to modulate your whole code by importing modules from other packages or code files.

Sample code without import in it.
homework_assignment_grades = {
    "homework1" : 85,
    "homework2" : 100,
    "homework3" : 81
}

def calculate_homework_grade(homework_assignment_grades_arg):
    """
    This function takes a dictionary of homework assignment grades and calculates the average grade.
    """
    total = 0
    for grade in homework_assignment_grades_arg.values():
        total += grade
    average = round(total / len(homework_assignment_grades_arg),2)
    print(f"Average homework grade: {average}")
    return average

calculate_homework_grade(homework_assignment_grades_arg=homework_assignment_grades)


As you can see having all code in one file make readability and maintainability issue. So to modulate it we can create code in different files and then can use it in another file according to our need.

Code segregation into multiple files and it's usage:
folder structure with file - grade_service/grade_average_service.py

grade_average_service.py file content:
def calculate_homework_grade(homework_assignment_grades_arg):
    """
    This function takes a dictionary of homework assignment grades and calculates the average grade.
    """
    total = 0
    for grade in homework_assignment_grades_arg.values():
        total += grade
    average = round(total / len(homework_assignment_grades_arg),2)
    print(f"Average homework grade: {average}")
    return average

imports.py file content which is going to use this file:
import grade_service.grade_average_service as grade_service

homework_assignment_grades = {
    "homework1" : 85,
    "homework2" : 100,
    "homework3" : 81
}

grade_service.calculate_homework_grade(homework_assignment_grades_arg=homework_assignment_grades)

As you can see now main file is import and you can read the task performed in it without bothering about readability issue and you can easily maintain file as well with respect to process through imports.py and through logic building by modifying grade_service/grade_average_service.py.


So it will help you in maintaining your project in right and appropriate manner.

Standard Library comes with python and how to use them?

"""
Standard Library Methods

Useful Methods sample and usage mechanism explanation
"""

#  importing random module from standard library
import random

tyoesOfDrinks = ["water", "juice", "soda", "milk", "coffee", "tea"]

print("Randomly selected drink from list: ", random.choice(tyoesOfDrinks))

print("Random numbers between 0 to 100: ", random.randint(0, 100))

# importing math module from standard library
import math

squareRoot = math.sqrt(16)
print("Square root of 16 is: ", squareRoot)
print("Square root of 25 is: ", math.sqrt(25))


Comments

Popular posts from this blog

Post Request with Pydantic usage (input validator)

Code Scalability and Routing

CRUD Assignment