Creating Python Modules for Geometrical Shapes

Aim: How do you make a module? Give an example of construction of a module using different geometrical shapes and operations on them as its functions.

Making of Module Steps

Creating a Module

A module allows you to logically organize your Python code. Grouping related code into a module makes the code easier to understand and use. A module is a Python object with arbitrarily named attributes that you can bind and reference.

Simply, a module is a file consisting of Python code. A module can define functions, classes, and variables. A module can also include runnable code.

Example: The Python code for a module named aname normally resides in a file named aname.py. Here’s an example of a simple module, support.py:

def print_func(par):
print("Hello:", par)
return

The Import Statement

You can use any Python source file as a module by executing an import statement in some other Python source file. The import has the following syntax:

import module

When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module.

Example: To import the module support.py, you need to put the following command at the top of the script:

1[, module2[,... moduleN]

When the interpreter encounters an import statement, it imports the module if the module is present in the search path. A search path is a list of directories that the interpreter searches before importing a module.

Example: To import the module support.py, you need to put the following command at the top of the script:

#!/usr/bin/python
# Import module support
import support
# Now you can call defined function from the module as follows
support.print_func("Zara")

Output:

1 Hello: Zara

A module is loaded only once, regardless of the number of times it is imported. This prevents the module execution from happening over and over again if multiple imports occur.

The from…import Statement

Python’s from statement lets you import specific attributes from a module into the current namespace. The from...import has the following syntax:

1from modname import name1[, name2[, ... nameN]]

Example: To import the function fibonacci from the module fib, use the following statement:

1 from fib import fibonacci

This statement does not import the entire module fib into the current namespace; it just introduces the item fibonacci from the module fib into the global symbol table of the importing module.

The from…import * Statement

It is also possible to import all names from a module into the current namespace by using the following import statement:

1 from modname import *

This provides an easy way to import all the items from a module into the current namespace; however, this statement should be used sparingly.

Aim: Give an example of construction of a module using different geometrical shapes and operations on them as its functions

Program:

import numpy as np
import cv2
my_img = np.zeros((400, 400, 3), dtype = "uint8")
# creating a rectangle
cv2.rectangle(my_img, (30, 30), (300, 200), (0, 20, 200), 10)
cv2.imshow('Window', my_img)
# allows us to see image
# until closed forcefully
cv2.waitKey(0)
cv2.destroyAllWindows()

CreaƟng Python Modules for Geometrical Shapes

Sample Viva Questions and Answers

  1. What is a module in Python?
    A module is a file containing Python code that can define functions, classes, and variables, allowing for code organization and reuse.

  2. How do you create a module in Python?
    A module is created by writing Python code in a .py file. The file name becomes the module name when imported.

  3. What are some common geometrical shapes you can define in a module?
    Common geometrical shapes include circles, rectangles, triangles, and squares.

  4. What operations can be performed on geometrical shapes in a module?
    Operations can include calculating area, perimeter, and volume, as well as transformations like scaling and rotation.

  5. How can you define a class for a geometrical shape in a module?
    A class can be defined within the module to represent a shape, with methods to perform operations related to that shape.

  6. What is the significance of using functions in a module?
    Functions encapsulate specific tasks, making the code reusable and easier to maintain, as well as improving readability.

  7. Can you import a module into another Python file?
    Yes, a module can be imported into another Python file using the import statement, allowing access to its functions and classes.

  8. What is an example of a function you might include in a geometrical shapes module?
    An example function could be calculate_area() that computes the area of a shape based on its dimensions.

  9. How can you handle different shapes in a single module?
    You can define multiple classes within the module, each representing a different shape, and provide specific methods for each shape.

  10. What are some practical applications of geometrical shape modules?
    Such modules can be used in computer graphics, game development, engineering simulations, and educational tools for teaching geometry.

📌 Python Programming Lab – Complete Guide

Welcome to the Python Programming Lab! This comprehensive lab series is designed to provide a solid foundation in Python programming through practical exercises and hands-on learning. From basic calculations to advanced concepts like file handling, modules, and GUI programming, this lab covers it all. Let’s dive into what you’ll be learning throughout this lab course.


🔍 Week 1: Introduction to Python Basics

In the first week, you will explore fundamental Python concepts aimed at building a strong foundation for your programming journey.

  • Getting Started with Python: Visit the Python Official Website to explore documentation and use the help() function in the interpreter.
  • Python as a Calculator: Learn how to perform basic arithmetic operations like addition, subtraction, multiplication, and division.
  • Calculating Compound Interest: Write a program to calculate compound interest using the formula with given principal, rate, and time.
  • Distance Calculation: Compute the distance between two points using the distance formula.
  • Reading User Details: Write a program to collect and print user details like name, address, email, and phone number.

🔍 Week 2: Python Loops and Conditional Statements

This week focuses on using loops and conditional statements effectively.

  • Pattern Generation: Print a triangle pattern using nested loops.
  • Character Identification: Write a program to identify whether the input is a digit, lowercase, uppercase, or special character.
  • Fibonacci Sequence Generation: Use a while loop to generate the Fibonacci series.
  • Prime Numbers Identification: Find all prime numbers within a specified range using the break statement.

🔍 Week 3: Data Structures and Functions

Dive into data structures and creating functions to enhance your programming skills.

  • Converting Lists and Tuples to Arrays: Understand how to convert different data structures.
  • Finding Common Values: Compare two arrays to find common values.
  • Calculating GCD: Create a function to calculate the greatest common divisor (GCD) of two numbers.
  • Palindrome Checker: Write a function that checks if a given string is a palindrome.

🔍 Week 4: Advanced Functions and String Manipulation

This week emphasizes sorting, handling duplicate elements, and manipulating strings effectively.

  • Checking Sorted Lists: Write a function to check if a list is sorted.
  • Handling Duplicates: Create functions to detect and remove duplicates from lists.
  • Dictionary Inversion: Write a program to swap keys and values in a dictionary.
  • String Manipulation: Add commas between characters, remove words from strings, and convert sentences to title case without using built-in functions.
  • Binary String Generation: Use recursion to generate all binary strings of a specified length.

🔍 Week 5: Working with Matrices and Modules

Learn to work with matrices and create custom modules for various applications.

  • Matrix Operations: Define, print, add, and multiply square matrices using Python.
  • Creating Modules: Build modules using geometrical shapes and their operations.
  • Exception Handling: Implement exception handling for robust error management.

🔍 Week 6: Object-Oriented Programming and Validation

This week focuses on using classes, inheritance, and validation techniques.

  • Drawing Shapes with Classes:
    • Create classes for rectangles, points, and circles, and draw them on a canvas.
    • Add colors and attributes to these shapes to enhance visualization.
  • Method Resolution Order (MRO): Demonstrate MRO in multiple inheritance scenarios.
  • Data Validation: Write programs to validate phone numbers and email addresses.

🔍 Week 7: File Handling and Text Processing

Master file handling techniques and analyzing text data.

  • File Merging: Combine the contents of two files into a new file.
  • Word Search: Create a function to find specific words in a file.
  • Word Frequency Analysis: Identify the most frequent words in a text file.
  • Text Statistics: Count words, vowels, blank spaces, lowercase, and uppercase letters in a file.

🔍 Week 8: Python Libraries and GUI Programming

Explore advanced Python libraries and build simple graphical user interfaces.

  • NumPy, Plotly, and Scipy: Learn how to install and use these powerful libraries for data analysis and visualization.
  • Digital Logic Gates: Implement logic gate operations such as AND, OR, NOT, and EX-OR.
  • Adder Circuits: Create programs for Half Adders, Full Adders, and Parallel Adders.
  • GUI Programming: Build a simple window wizard with text labels, input fields, and buttons using Python’s GUI tools.

🌟 Conclusion:

The Python Programming Lab R23 provides you with a strong foundation in Python programming through a wide range of exercises, from basic concepts to advanced topics. By the end of this lab, you will have gained valuable skills in data processing, file handling, OOP, modules, and GUI development. Start coding and enhance your Python skills! 🚀


;