Saturday, 21 December 2024

Day 50 : Python Program to Find Gravitational Force Between the Two Object


import math

def calculate_gravitational_force(m1, m2, r):

    """Calculates the gravitational force between two objects."""

    G = 6.67430e-11  

    force = G * (m1 * m2) / (r ** 2)

    return force

def main():

    print("Gravitational Force Calculator")

    try:

        mass1 = float(input("Enter the mass of the first object (kg): "))

        mass2 = float(input("Enter the mass of the second object (kg): "))

        distance = float(input("Enter the distance between the objects (m): "))


        if mass1 <= 0 or mass2 <= 0 or distance <= 0:

            print("Masses and distance must be positive values.")

            return


        force = calculate_gravitational_force(mass1, mass2, distance)

        print(f"The gravitational force between the objects is {force:.2e} N.")

    except ValueError:

        print("Invalid input. Please enter numeric values.")

if __name__ == "__main__":

    main()

#source code --> clcoding.com 

Code Explanation:

Function Definition
1. import math
Imports the math module. While not directly used in the current code, it might be added for future computations or extensions.

2. def calculate_gravitational_force(m1, m2, r):
Defines a function named calculate_gravitational_force that calculates the gravitational force between two objects.
Parameters:
m1: Mass of the first object (in kilograms).
m2: Mass of the second object (in kilograms).
r: Distance between the centers of the two objects (in meters).
3. G = 6.67430e-11
Declares the gravitational constant, G, which has a value of 
6.67430×10−11m3kg−1s−2.

4. force = G * (m1 * m2) / (r ** 2)
Calculates the gravitational force using the formula:
๐น=๐บ*๐‘š1⋅๐‘š2/๐‘Ÿ2
​The masses are multiplied, and the result is divided by the square of the distance.

5. return force
Returns the computed gravitational force to the caller.
Main Program Logic

6. def main():
Defines the main function to interact with the user.

7. print("Gravitational Force Calculator")
Displays a title message to introduce the program.

8. try:
Starts a try block to handle user input and potential errors.

9. mass1 = float(input("Enter the mass of the first object (kg): "))
Prompts the user to input the mass of the first object in kilograms and converts the input to a float.

10. mass2 = float(input("Enter the mass of the second object (kg): "))
Prompts the user to input the mass of the second object in kilograms and converts the input to a float.

11. distance = float(input("Enter the distance between the objects (m): "))
Prompts the user to input the distance between the objects in meters and converts the input to a float.
Validation

12. if mass1 <= 0 or mass2 <= 0 or distance <= 0:
Checks if any of the inputs (mass1, mass2, or distance) are less than or equal to zero.
Gravitational force requires positive values for mass and distance.

13. print("Masses and distance must be positive values.")
If validation fails, prints an error message.

14. return
Exits the function to prevent further computation.
Force Calculation

15. force = calculate_gravitational_force(mass1, mass2, distance)
Calls the calculate_gravitational_force function with the user-provided inputs and stores the result in the variable force.

16. print(f"The gravitational force between the objects is {force:.2e} N.")
Prints the calculated gravitational force in scientific notation with two decimal places, followed by the unit N (Newtons).

Error Handling
17. except ValueError:
Catches any ValueError that occurs if the user inputs invalid (non-numeric) data.

18. print("Invalid input. Please enter numeric values.")
Displays an error message when a ValueError is caught.
Program Entry Point

19. if __name__ == "__main__":
Ensures that the main() function is only executed when the script is run directly, not when imported as a module.

20. main()
Calls the main function to start the program.

 

0 Comments:

Post a Comment

Popular Posts

Categories

100 Python Programs for Beginner (53) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (173) C (77) C# (12) C++ (82) Course (67) Coursera (226) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (20) Django (14) Downloads (3) edx (2) Engineering (14) Excel (13) Factorial (1) Finance (6) flask (3) flutter (1) FPL (17) Google (34) Hadoop (3) HTML&CSS (47) IBM (25) IoT (1) IS (25) Java (93) Leet Code (4) Machine Learning (59) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (932) Python Coding Challenge (358) Python Quiz (23) Python Tips (2) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (3) Software (17) SQL (42) UX Research (1) web application (8) Web development (2) web scraping (2)

Followers

Person climbing a staircase. Learn Data Science from Scratch: online program with 21 courses