Working with Mulitple Files in Python

Moderator: ramajayam

Post Reply
admin
Site Admin
Posts: 67
Joined: Wed Feb 07, 2024 8:24 am

Working with Mulitple Files in Python

Post by admin »

Code for File no 1 Titled Maincode.py

Code: Select all

# Maincode.py



def multiply(a, b):
    return a * b

def divide(a, b):
    if b == 0:
        raise ValueError("Cannot divide by zero!")
    return a / b

if __name__ == '__main__':
    # Test cases
    print("Testing multiply and divide functions")
    print("2 * 3 =", multiply(2, 3))  # Should print 6
    print("10 / 2 =", divide(10, 2))  # Should print 5.0
    try:
        print("10 / 0 =", divide(10, 0))  # Should raise an exception
    except ValueError as e:
        print("Caught an exception:", e)

Code for File no 2 Titled Maincode.py

Code: Select all

import Maincode

print(Maincode.multiply(5, 6))


def d():
    print("Code Executed Successfully")	  

if __name__ == '__main__':
    d()

Usage of if __name__ == '__main__': in a code


if __name__ == '__main__': construct is a powerful tool in Python that allows you to:

Run code only when a script is executed directly.
Prevent certain code from running when the script is imported as a module.
Include test code or example usage that doesn't interfere with the module's functionality when imported.
This construct helps in creating clean and modular code, making it easier to test and reuse across different projects.

To Download the files register
You do not have the required permissions to view the files attached to this post.
Post Reply