Showing posts with label 100 Python Programs for Beginner. Show all posts
Showing posts with label 100 Python Programs for Beginner. Show all posts

Friday, 27 December 2024

Day 62: Create Audiobook Using Python


from gtts import gTTS

import os

def create_audiobook(text_file, output_file):

    with open(text_file, 'r', encoding='utf-8') as file:

        text = file.read()

     tts = gTTS(text=text, lang='en')

    tts.save(output_file)

    print(f"Audiobook saved as {output_file}")


text_file = "clcoding_hindi.txt"  

output_file = "clcoding_hindi.mp3"

create_audiobook(text_file, output_file)

os.system(f"start {output_file}")  

#source code --> clcoding.com

Code Explanation:

1. Importing Required Libraries:
from gtts import gTTS
import os

from gtts import gTTS:
Imports the gTTS class from the gtts library, which is used to convert text to speech.
gTTS allows you to specify the text, language, and other options for generating the speech.

import os:
Imports the os module, which provides functions to interact with the operating system, such as running commands (os.system) to play the generated MP3 file.

2. Defining the create_audiobook Function:
def create_audiobook(text_file, output_file):
What It Does:
Defines a function named create_audiobook that takes two arguments:
text_file: Path to the input text file containing the content to be converted into speech.
output_file: Name of the MP3 file to save the audiobook.

3. Reading the Text File:
    with open(text_file, 'r', encoding='utf-8') as file:
        text = file.read()
open(text_file, 'r', encoding='utf-8'):

Opens the specified text_file in read mode ('r') with UTF-8 encoding to handle special characters if present.
with Statement:
Ensures the file is properly closed after it is read.
text = file.read():
Reads the entire content of the file and stores it in the variable text.

4. Converting Text to Speech:
    tts = gTTS(text=text, lang='en')
gTTS(text=text, lang='en'):
Converts the text to speech using the gTTS library.
Arguments:
text: The text content to convert.
lang='en': Specifies the language for the speech (English in this case).
tts:
A gTTS object that contains the generated speech.

5. Saving the Audiobook:
    tts.save(output_file)
tts.save(output_file):
Saves the generated speech to an MP3 file specified by output_file.

6. Confirmation Message:
    print(f"Audiobook saved as {output_file}")
print(...):
Prints a confirmation message to inform the user that the audiobook has been saved successfully.

7. Specifying the Input and Output Files:
text_file = "clcoding_hindi.txt"  
output_file = "clcoding_hindi.mp3"
text_file:
Specifies the name of the input text file that contains the content to be converted to speech.
output_file:
Specifies the name of the output MP3 file to save the audiobook.

8. Calling the Function:
create_audiobook(text_file, output_file)
create_audiobook(...):
Calls the create_audiobook function with the text_file and output_file arguments to generate the audiobook.

9. Playing the Audiobook:
os.system(f"start {output_file}")  
os.system(f"start {output_file}"):
Executes an operating system command to play the generated MP3 file.
Platform-Specific:
On Windows: start opens the file in the default media player.
On Linux or macOS, you might use commands like xdg-open or open instead.


 

Day 61: Python Program to Find GCD of Two Numbers Using Recursion

 


def gcd(a, b):

    """

   Function to calculate GCD of two numbers using recursion

    """

    if b == 0:

        return a

    else:

        return gcd(b, a % b)

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

result = gcd(num1, num2)

print(f"The GCD of {num1} and {num2} is {result}")

#source code --> clcoding.com 

Code Explanation:

1. Function Definition:
def gcd(a, b):
    """
    Function to calculate GCD of two numbers using recursion
    """
def gcd(a, b):

This defines a function named gcd that takes two arguments, a and b.
a and b represent the two numbers for which we want to calculate the Greatest Common Divisor (GCD).
""" ... """

This is a docstring that describes what the function does. It mentions that the function calculates the GCD of two numbers using recursion.

2. Base Case:
    if b == 0:
        return a
if b == 0:

Checks whether b (the second number) is 0.
This is the base case of recursion. When b is 0, the recursion stops.
return a

If b is 0, the function returns the value of a, as the GCD of any number and 0 is the number itself.
Example: GCD(8, 0) → 8.

3. Recursive Case:
    else:
        return gcd(b, a % b)
else:

Executes if b is not 0.
return gcd(b, a % b)

This is the recursive call. The function calls itself with:
b as the new first argument.
a % b (the remainder when a is divided by b) as the new second argument.
This step reduces the size of the problem with each recursive call, eventually reaching the base case where b is 0.

4. Taking User Input:
num1 = int(input("Enter the first number: "))
num1 = int(input("Enter the first number: "))
Prompts the user to input the first number with the message "Enter the first number: ".
input() captures the user’s input as a string.
int() converts the string input to an integer so it can be used in calculations.
The integer value is stored in the variable num1.
num2 = int(input("Enter the second number: "))
num2 = int(input("Enter the second number: "))
Similar to the above, prompts the user to input the second number.
Converts the input string to an integer and stores it in the variable num2.

5. Calling the Function and Storing the Result:
result = gcd(num1, num2)
result = gcd(num1, num2)
Calls the gcd function with num1 and num2 as arguments.
The function computes the GCD of num1 and num2 and returns the result.
The returned GCD is stored in the variable result.

6. Printing the Result:
print(f"The GCD of {num1} and {num2} is {result}")
print(f"...")
Prints the GCD of the two numbers in a formatted message.
F-String (f"..."): Dynamically inserts the values of num1, num2, and result into the string.
Example Output: The GCD of 48 and 18 is 6.


Thursday, 26 December 2024

Day 60: Python Program to Find Lcm of Two Number Using Recursion

 


def find_lcm(a, b):

    def find_gcd(a, b):

        if b == 0:

            return a

        else:

            return find_gcd(b, a % b)

    return abs(a * b) // find_gcd(a, b)

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

lcm = find_lcm(num1, num2)

print(f"The LCM of {num1} and {num2} is {lcm}.")

#source code --> clcoding.com 

Code Explanation:

1. def find_lcm(a, b):
This defines a function find_lcm that takes two parameters, a and b, representing the two numbers for which we want to calculate the LCM.

2. def find_gcd(a, b):
Inside the find_lcm function, there is a nested helper function find_gcd to calculate the GCD of two numbers.
The function uses recursion:
Base Case: If b == 0, return a as the GCD.
Recursive Case: Call find_gcd(b, a % b) until b becomes 0.
This is an implementation of the Euclidean Algorithm to compute the GCD.

3. return abs(a * b) // find_gcd(a, b)
Once the GCD is determined, the formula for calculating LCM is used:
LCM
(𝑎,𝑏)=∣𝑎×𝑏∣/GCD(𝑎,𝑏)
​abs(a * b) ensures the product is non-negative (handles potential negative input).
// is used for integer division to compute the LCM.

4. num1 = int(input("Enter the first number: "))
Takes input from the user for the first number, converts it to an integer, and stores it in num1.

5. num2 = int(input("Enter the second number: "))
Takes input from the user for the second number, converts it to an integer, and stores it in num2.

6. lcm = find_lcm(num1, num2)
Calls the find_lcm function with num1 and num2 as arguments.
The LCM of the two numbers is stored in the variable lcm.

7. print(f"The LCM of {num1} and {num2} is {lcm}.")
Outputs the calculated LCM using an f-string for formatted output.

Day 59: Python Program to Find GCD of Two Number

def find_gcd(a, b):

    while b:

        a, b = b, a % b

    return a

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

gcd = find_gcd(num1, num2)

print(f"The GCD of {num1} and {num2} is {gcd}.")

 #source code --> clcoding.com 

Code Explanation:

1. def find_gcd(a, b):
This defines a function named find_gcd that takes two parameters, a and b, representing the two numbers whose GCD you want to find.

2. while b:
This while loop runs as long as b is not zero. The loop keeps iterating until b becomes zero.
The condition while b is equivalent to while b != 0.

3. a, b = b, a % b
Inside the loop, this line uses Python's tuple unpacking to simultaneously update the values of a and b.
a becomes the current value of b, and b becomes the remainder of the division a % b.

This step implements the Euclidean Algorithm, which states that the GCD of two numbers does not change if the larger number is replaced by its remainder when divided by the smaller number.
The process continues until b becomes zero, at which point a holds the GCD.

4. return a
When the loop ends, the function returns the value of a, which is the GCD of the two numbers.

5. num1 = int(input("Enter the first number: "))
This line takes input from the user, converts it to an integer, and stores it in the variable num1.

6. num2 = int(input("Enter the second number: "))
Similarly, this line takes the second input from the user, converts it to an integer, and stores it in the variable num2.

7. gcd = find_gcd(num1, num2)
The find_gcd function is called with num1 and num2 as arguments, and the result is stored in the variable gcd.

8. print(f"The GCD of {num1} and {num2} is {gcd}.")
This line prints the GCD using an f-string to format the output.


Wednesday, 25 December 2024

Day 58: Python Program to Find LCM of Two Numbers

 

import math

def find_lcm(num1, num2):

    """

    Function to find the LCM of two numbers.

    :param num1: First number

    :param num2: Second number

    :return: LCM of num1 and num2

    """

    gcd = math.gcd(num1, num2)

    lcm = (num1 * num2) 

    return lcm

num1 = int(input("Enter the first number: "))

num2 = int(input("Enter the second number: "))

result = find_lcm(num1, num2)

print(f"The LCM of {num1} and {num2} is: {result}")

#source code --> clcoding.com 

Code Explanation:

Importing the math Module
import math
The math module is imported to use its built-in math.gcd() function for calculating the Greatest Common Divisor (GCD) of two numbers.

Defining the Function: find_lcm
def find_lcm(num1, num2):
    """
    Function to find the LCM of two numbers.
    
    :param num1: First number
    :param num2: Second number
    :return: LCM of num1 and num2
    """
Purpose: Calculates the LCM of two numbers.
Parameters:
num1: First input number.
num2: Second input number.
Return Value: The LCM of num1 and num2.

Calculating the GCD
    gcd = math.gcd(num1, num2)
math.gcd(num1, num2):
Finds the Greatest Common Divisor (GCD) of num1 and num2.
The GCD is the largest integer that evenly divides both numbers.

Calculating the LCM
    lcm = (num1 * num2) 
​ 
The product of the two numbers is divided by their GCD to compute the LCM efficiently.
Why it works: This relationship between GCD and LCM ensures that the LCM is the smallest positive integer that is divisible by both numbers.

Returning the LCM
    return lcm
Returns the computed LCM to the caller.

User Input
num1 = int(input("Enter the first number: "))
num2 = int(input("Enter the second number: "))

Prompts the user to input two integers:
num1: The first number.
num2: The second number.
Converts the input strings to integers using int().

Calling the Function
result = find_lcm(num1, num2)
Calls the find_lcm() function with num1 and num2 as arguments.
Stores the result (the LCM) in the variable result.

Displaying the Result
print(f"The LCM of {num1} and {num2} is: {result}")
Uses an f-string to display the computed LCM in a user-friendly format.

Day 56: Python Program to Find Sum of Sine Series

 


import math

def factorial(n):

    """Calculate the factorial of a number."""

    if n == 0 or n == 1:

        return 1

    return n * factorial(n - 1)

def sine_series(x, terms):

    """Calculate the sum of the sine series."""

    sine_sum = 0

    for i in range(terms):

        power = 2 * i + 1

        sign = (-1) ** i 

        term = sign * (x ** power) / factorial(power)

        sine_sum += term

    return sine_sum

angle_degrees = float(input("Enter the angle in degrees: "))

terms = int(input("Enter the number of terms: "))

angle_radians = math.radians(angle_degrees)

sine_sum = sine_series(angle_radians, terms)

print(f"The sum of the sine series for {angle_degrees}° is: {sine_sum}")

#source code --> clcoding.com 

Code Explanation:

Import Statement
import math
Imports the math module to use its built-in functions, like math.radians for converting degrees to radians.
Factorial Function
def factorial(n):
    """Calculate the factorial of a number."""
    if n == 0 or n == 1:
        return 1
    return n * factorial(n - 1)
Purpose: Computes the factorial of n recursively.
Logic:
If 𝑛=0 or 𝑛=1, return 1 (base case).
Otherwise, return 𝑛×factorial(𝑛−1)(recursive step).
Example:
factorial(3)=3×2×1=6.

Sine Series Function
def sine_series(x, terms):
    """Calculate the sum of the sine series."""
    sine_sum = 0
    for i in range(terms):
        power = 2 * i + 1
        sign = (-1) ** i
        term = sign * (x ** power) / factorial(power)
        sine_sum += term
    return sine_sum
Logic:
power: Calculates the power 
2i+1 (odd powers only).sign: Alternates between 
1 and −1 for successive terms, determined by 
(−1)𝑖 .
sine_sum: Accumulates the sum of all terms up to the specified number of terms.

Input Angle in Degrees
angle_degrees = float(input("Enter the angle in degrees: "))
Prompts the user to enter the angle in degrees.
Converts the input to a float for precise calculations.

Input Number of Terms
terms = int(input("Enter the number of terms: "))
Prompts the user to specify the number of terms in the series.

Converts the input to an integer.
Convert Degrees to Radians
angle_radians = math.radians(angle_degrees)
Converts the angle from degrees to radians using the math.radians() function.
This step is necessary because the Taylor series for sine requires the angle in radians.

Calculate the Sine Series
sine_sum = sine_series(angle_radians, terms)
Calls the sine_series() function with:
angle_radians: The angle in radians.
terms: The number of terms in the series.
Stores the computed sum in sine_sum.

Output the Result
print(f"The sum of the sine series for {angle_degrees}° is: {sine_sum}")
Uses an f-string to display the result of the sine series for the input angle in degrees.

Day 55: Python Program to Read a Number n and Print the Series “1+2+… +n= “


 n = int(input("Enter a number: "))

series = " + ".join(str(i) for i in range(1, n + 1))

total_sum = sum(range(1, n + 1))

print(f"{series} = {total_sum}")

#source code --> clcoding.com 

Code Explanation:

Input
n = int(input("Enter a number: "))
Prompts the user to enter an integer.
Converts the input to an integer using int() and stores it in the variable n.
Generate the Series
series = " + ".join(str(i) for i in range(1, n + 1))
Generates a string representation of the series 
1+2+3+…+n:
range(1, n + 1): Creates a range of integers from 1 to 𝑛
n (inclusive).
str(i) for i in range(1, n + 1): 
Converts each number in the range to a string.
" + ".join(...): Joins these strings with " + " as the separator, forming the series.
For example:
If 
n=5, the result is: "1 + 2 + 3 + 4 + 5".

Calculate the Total Sum
total_sum = sum(range(1, n + 1))
Computes the sum of all integers from 1 to n:
range(1, n + 1): Creates a range of integers from 1 to 𝑛
n (inclusive).
sum(...):
 Adds all the numbers in the range.
For example:
If 𝑛=5, the result is: 1+2+3+4+5=15

Output the Result
print(f"{series} = {total_sum}")
Uses an f-string to format the output.
Prints the series and the total sum in the format:
series=total_sum
For example:
If 𝑛=5, the output is:
1 + 2 + 3 + 4 + 5 = 15

Monday, 23 December 2024

Day 54: Python Program to Find Sum of Series 1/1!+1/2!+1/3!....1/N!


import math


def sum_of_series(n):

    """

    Calculates the sum of the series 1/1! + 1/2! + 1/3! + ... + 1/N!

    :param n: The number of terms in the series

    :return: The sum of the series

    """

    if n <= 0:

        return "N should be a positive integer."

    

    total_sum = 0

    for i in range(1, n + 1):

        total_sum += 1 / math.factorial(i)  

    return total_sum

try:

    N = int(input("Enter a positive integer N: "))

    if N <= 0:

        print("Please enter a positive integer.")

    else:

        result = sum_of_series(N)

        print(f"The sum of the series for N={N} is: {result:.6f}")

except ValueError:

    print("Invalid input! Please enter a positive integer.")

#source code --> clcoding.com 

Code Explanation:

1. Importing the math module:

import math

The math module provides access to mathematical functions, including math.factorial() used in this program.

2. Function Definition:

def sum_of_series(n):

    """

    Calculates the sum of the series 1/1! + 1/2! + 1/3! + ... + 1/N!

    :param n: The number of terms in the series

    :return: The sum of the series

    """

This function calculates the sum of the series up to 𝑁 terms.

3. Input Validation:

if n <= 0:

    return "N should be a positive integer."

Ensures that N is a positive integer. If  N≤0, an error message is returned.

4. Series Calculation:

total_sum = 0

for i in range(1, n + 1):

    total_sum += 1 / math.factorial(i)

total_sum: Accumulates the sum of the series. Initially set to 0.

for i in range(1, n + 1): Loops through integers from 1 to 𝑁

math.factorial(i): Computes i!, the factorial of 𝑖

1 / math.factorial(i): Adds the term 1/𝑖! to the total sum.

5. Returning the Result:

return total_sum

Returns the computed sum of the series.

6. User Input Handling:

try:

    N = int(input("Enter a positive integer N: "))

    if N <= 0:

        print("Please enter a positive integer.")

    else:

        result = sum_of_series(N)

        print(f"The sum of the series for N={N} is: {result:.6f}")

except ValueError:

    print("Invalid input! Please enter a positive integer.")

try block:

Prompts the user for an integer input for 𝑁.

If the user enters a valid positive integer:

Checks if 

N>0. If not, prints an error message.

Otherwise, calls sum_of_series(N) to compute the sum and prints the result with six decimal places.

except block:

Handles invalid inputs (e.g., entering a string or decimal) and displays an error message.

 

Sunday, 22 December 2024

Day 53: Python Program to Find Sum of Series 1+1/2+1/3...+1/N


 def sum_of_series(n):

    if n <= 0:

        return "N should be a positive integer."

    

    total_sum = 0

    for i in range(1, n + 1):

        total_sum += 1 / i

    return total_sum

try:

    N = int(input("Enter a positive integer N: "))

    if N <= 0:

        print("Please enter a positive integer.")

    else:

        result = sum_of_series(N)

        print(f"The sum of the series for N={N} is: {result:.6f}")

except ValueError:

    print("Invalid input! Please enter a positive integer.")

    

#source code --> clcoding.com 

Code Explanation:

1. Function Definition:

def sum_of_series(n):
    if n <= 0:
        return "N should be a positive integer."
sum_of_series(n):
This function takes an integer n as input, which represents the number of terms in the series.
If n is not a positive integer, it returns a message prompting the user to provide a valid input.

2. Series Calculation:
    total_sum = 0
    for i in range(1, n + 1):
        total_sum += 1 / i
total_sum = 0:
Initializes a variable to store the cumulative sum of the series.
for i in range(1, n + 1):
Iterates over the range from 1 to n (inclusive) to compute each term of the series.
total_sum += 1 / i:
Adds the reciprocal of the current number i (1+𝑖) to the cumulative sum.

3. Return Statement:
    return total_sum
Returns the calculated sum of the series as a floating-point number.

4. Main Block (User Interaction):
try:
    N = int(input("Enter a positive integer N: "))
    if N <= 0:
        print("Please enter a positive integer.")
try-except Block:
Handles invalid input to ensure the program doesn't crash if the user enters non-integer values.
N = int(input(...)):
Prompts the user for input and converts it to an integer.
if N <= 0:
Checks if the user entered a positive integer. If not, a message is displayed.

5. Function Call and Output:
    else:
        result = sum_of_series(N)
        print(f"The sum of the series for N={N} is: {result:.6f}")
except ValueError:
    print("Invalid input! Please enter a positive integer.")
sum_of_series(N):
Calls the function with the user-provided value of N to compute the series sum.
Formatted Output ({result:.6f}):
Displays the result rounded to 6 decimal places for better readability.
except ValueError:
Catches non-integer inputs and prompts the user to enter a valid positive integer.

6. Example Execution:
Input:
Enter a positive integer N: 5
Execution:
The program calls sum_of_series(5).
The function calculates:
𝑆=1+1/2+1/3+1/4+1/5=2.283333

The result is returned and printed.
Output:

The sum of the series for N=5 is: 2.283333


Day 52: Python Program to Print an Identity Matrix


 def print_identity_matrix(n):

    """

    Prints an identity matrix of size n x n.

    :param n: Size of the identity matrix

    """

    if n <= 0:

        print("Please enter a positive integer for the size of the matrix.")

        return

for i in range(n):

        for j in range(n):

            if i == j:

                print(1, end=" ")

            else:

                print(0, end=" ")

        print()  

try:

    size = int(input("Enter the size of the identity matrix: "))

    print_identity_matrix(size)

except ValueError:

    print("Invalid input! Please enter a valid integer.")

#source code --> clcoding.com

Code Explanation:

1. Function Definition:
def print_identity_matrix(n):
    """
    Prints an identity matrix of size n x n.
    :param n: Size of the identity matrix
    """
print_identity_matrix(n): This function takes one argument, n, which represents the size of the identity matrix.
The identity matrix is a square matrix where all diagonal elements are 1, and all other elements are 0.

2. Input Validation:
if n <= 0:
    print("Please enter a positive integer for the size of the matrix.")
    return
If the user provides a non-positive integer (n <= 0), the function outputs a warning message and stops further execution using return.

3. Nested Loop to Generate the Matrix:
for i in range(n):
    for j in range(n):
        if i == j:
            print(1, end=" ")
        else:
            print(0, end=" ")
    print()
Outer Loop (for i in range(n)):
Iterates over the rows of the matrix.
Inner Loop (for j in range(n)):
Iterates over the columns of the matrix.
Condition (if i == j):
Checks if the current position (i, j) is a diagonal element. If true, it prints 1; otherwise, it prints 0.
print(..., end=" "):
Ensures that elements in the same row are printed on the same line with a space in between.
print() (outside inner loop):
Moves to the next line after completing each row.

4. User Input and Error Handling:
try:
    size = int(input("Enter the size of the identity matrix: "))
    print_identity_matrix(size)
except ValueError:
    print("Invalid input! Please enter a valid integer.")
input(): Prompts the user to enter the size of the identity matrix.
int(input(...)): Converts the user's input to an integer.
try-except Block: Catches invalid inputs (e.g., non-integer values) and displays an error message.

5. Example Execution:
Input:
Enter the size of the identity matrix: 3

Output:
1 0 0 
0 1 0 
0 0 1 

Saturday, 21 December 2024

Day 51: Python Program to Form an Integer that has Number of Digits at 10’s LSD at 1’s Place


 def form_integer(number):

    if number < 0:

        print("Please provide a non-negative integer.")

        return None

    num_str = str(number)

    num_digits = len(num_str)

    last_digit = int(num_str[-1])

    result = num_digits * 10 + last_digit

     return result

number = int(input("Enter a positive integer: "))

new_integer = form_integer(number)

if new_integer is not None:

    print(f"The newly formed integer is: {new_integer}")

#source code --> clcoding.com 

Code Explanation:

1. Function Definition
def form_integer(number):
Defines a function named form_integer that accepts one parameter, number. This function processes the given number to generate a new integer.

2. Input Validation
if number < 0:
    print("Please provide a non-negative integer.")
    return None
Checks if the input number is negative. If it is, the function:
Prints a message: "Please provide a non-negative integer."
Returns None to terminate the function early and avoid further processing.

3. Convert Number to String
num_str = str(number)
Converts the input number to a string (num_str) so that its digits can be easily accessed and processed.

4. Count Digits
num_digits = len(num_str)
Calculates the total number of digits in the input number using the len() function. The result is stored in num_digits.

5. Extract the Last Digit
last_digit = int(num_str[-1])
Extracts the last digit of the number by accessing the last character of the string (num_str[-1]) and converting it back to an integer.

6. Form New Integer
result = num_digits * 10 + last_digit
Forms a new integer using the formula:
new integer=(number of digits×10)+(last digit)

7. Return Result
return result
Returns the newly formed integer (result) to the caller.

8. Input and Function Call
number = int(input("Enter a positive integer: "))
Prompts the user to input a positive integer.
Converts the input to an integer and stores it in the variable number.
new_integer = form_integer(number)
Calls the form_integer function with number as the argument.
Stores the returned value in the variable new_integer.

9. Output the Result
if new_integer is not None:
    print(f"The newly formed integer is: {new_integer}")
Checks if the returned value (new_integer) is not None. If valid:
Prints the newly formed integer.

10. Error Handling
If the user enters a negative number, the program handles it gracefully by displaying a message and skipping further processing.

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.

 

Day 48: Python Program To Clear Rightmost Set Bit of a Number

 



def clear_rightmost_set_bit(n):
    """
    Clears the rightmost set bit of the given number.
    :param n: The input number
    :return: The number with the rightmost set bit cleared
    """
    return n & (n - 1)
num = int(input("Enter a non-negative integer: "))  
result = clear_rightmost_set_bit(num)

print(f"Original number: {num} (Binary: {bin(num)})")
print(f"Number after clearing rightmost set bit: {result} (Binary: {bin(result)})")

#source code --> clcoding.com 


Code Explanation:

1. Function Definition
def clear_rightmost_set_bit(n):
    """
    Clears the rightmost set bit of the given number.
    :param n: The input number
    :return: The number with the rightmost set bit cleared
    """
    return n & (n - 1)

Key Points:
Rightmost Set Bit:
The rightmost set bit is the first 1 from the right in the binary representation of the number.
For example:
10 (binary: 1010) → The rightmost set bit is the second position from the right (2^1).
18 (binary: 10010) → The rightmost set bit is the fifth position from the right (2^4).

Clearing the Rightmost Set Bit:
The operation n & (n - 1) clears the rightmost set bit. Here's how:
Subtracting 1 from n flips all bits to the right of the rightmost set bit and flips the rightmost set bit to 0.
The & operation (bitwise AND) keeps all other bits unchanged but ensures the rightmost set bit is cleared.

Example:
For n = 10 (binary: 1010):
n - 1 = 9 (binary: 1001)
n & (n - 1) = 1010 & 1001 = 1000 (decimal: 8)

2. Input Handling
num = int(input("Enter a non-negative integer: "))  
Prompts the user to input a non-negative integer and stores it in num.

3. Call the Function
result = clear_rightmost_set_bit(num)
Calls the function clear_rightmost_set_bit with the input number num.
Stores the result (the number after clearing the rightmost set bit) in result.

4. Display the Results
print(f"Original number: {num} (Binary: {bin(num)})")
print(f"Number after clearing rightmost set bit: {result} (Binary: {bin(result)})")
bin():
Converts the integer into its binary representation (as a string prefixed with 0b).

For example:
bin(10) → '0b1010'
bin(8) → '0b1000'

Displays:
The original number and its binary representation.
The result after clearing the rightmost set bit and its binary representation.

Output:
Original number: 18 (Binary: 0b10010)
Number after clearing rightmost set bit: 16 (Binary: 0b10000)
Source

Day 49 : Python Program to Test Collatz Conjecture for a Given Number


def collatz_conjecture(n):

    if n <= 0:

        print("Please enter a positive integer.")

        return

     print(f"Starting number: {n}")

    while n != 1:

        if n % 2 == 0:

            n = n // 2

        else:

            n = 3 * n + 1

        print(n, end=" ")

    print("\nReached 1!")

try:

    number = int(input("Enter a positive integer to test the Collatz conjecture: "))

    collatz_conjecture(number)

except ValueError:

    print("Invalid input! Please enter a valid integer.")

#source code --> clcoding.com 

Code Explanation:

1. Function Definition
def collatz_conjecture(n):
This function implements the Collatz sequence starting from the number n.

2. Input Validation
if n <= 0:
    print("Please enter a positive integer.")
    return
The Collatz Conjecture only applies to positive integers.
If the input n is not a positive number (e.g., 0 or a negative number), the function prints an error message and exits using return.

3. Start the Sequence
print(f"Starting number: {n}")
Prints the starting number to indicate the beginning of the Collatz sequence.

4. Collatz Algorithm
while n != 1:
    if n % 2 == 0:
        n = n // 2
    else:
        n = 3 * n + 1
    print(n, end=" ")
while n != 1:

The loop runs until the number n becomes 1.
if n % 2 == 0:

Checks if n is even. If true, divide n by 2 (n = n // 2).
else:

If n is odd, apply the formula 3 * n + 1.
print(n, end=" "):

Prints the value of n after each step.
end=" " ensures all numbers are printed on the same line, separated by spaces.

5. Reached the End
print("\nReached 1!")
Once the loop ends (i.e., n == 1), this message is printed.

Error Handling
try:
    number = int(input("Enter a positive integer to test the Collatz conjecture: "))
    collatz_conjecture(number)
except ValueError:
    print("Invalid input! Please enter a valid integer.")

try-except Block:
Handles errors if the user enters invalid input (e.g., letters or symbols instead of numbers).
int(input()):
Prompts the user to enter a number and converts it to an integer.

ValueError:
If the user enters non-numeric input, Python raises a ValueError.
The program catches this error and prints an error message.

Thursday, 19 December 2024

Day 47: Python Program to Set Bit of an Integer




def count_set_bits(n):

    count=0

    while n > 0:

        count += n & 1

        n >>= 1

        return count

num=int(input("Enter an integer"))

print(f"The number of set bits in {num}is{count_set_bits(num)}.")

#source code --> clcoding.com 

 Code Explanation:

Function: count_set_bits
def count_set_bits(n):
    count = 0
    while n > 0:
        count += n & 1
        n >>= 1
        return count

Initialization:
count = 0: Initializes a variable count to store the number of set bits.

Logic:
n & 1: This operation checks if the least significant bit (LSB) of n is 1.
& is a bitwise AND operator. It returns 1 only if both corresponding bits are 1.
For example:
5 (binary: 101) & 1 (binary: 001) = 1 (LSB is 1).
4 (binary: 100) & 1 (binary: 001) = 0 (LSB is 0).
count += n & 1: Adds 1 to count if the LSB of n is 1.
n >>= 1: Right-shifts n by 1 bit to examine the next bit.
For example:
If n = 5 (binary: 101), n >> 1 = 2 (binary: 10).
If n = 2 (binary: 10), n >> 1 = 1 (binary: 1).

Loop Condition:
The loop continues as long as n > 0, meaning there are more bits to check.
Return Value:
The function returns count, which is the total number of set bits in the binary representation of n.
num = int(input("Enter an integer"))
Prompts the user to input an integer (num).
Converts the input string to an integer using int().
print(f"The number of set bits in {num} is {count_set_bits(num)}.")
Calls the count_set_bits function with num as input.
Prints the number of set bits.

Input:
Enter an integer: 5
Execution of count_set_bits(5)
Initial value: n = 5 (binary: 101), count = 0.

First iteration:
n & 1: 101 & 001 = 1 (LSB is 1).
count += 1: count = 1.
n >>= 1: n = 2 (binary: 10).

Second iteration:
n & 1: 10 & 01 = 0 (LSB is 0).
count = 1 (no increment).
n >>= 1: n = 1 (binary: 1).

Third iteration:
n & 1: 1 & 1 = 1 (LSB is 1).
count += 1: count = 2.
n >>= 1: n = 0 (loop exits).
Return count = 2.

Output:
The number of set bits in 5 is 2.

Day 46: Python Program to Swap Two Numbers Without Using The Third Variable

 

def swap_numbers(a, b):

    a = a + b

    b = a - b

    a = a - b

    return a, b

a = int(input("Enter the first number: "))

b = int(input("Enter the second number: "))

a, b = swap_numbers(a, b)

print(f"After swapping: First number = {a} and Second number = {b}")

#source code --> clcoding.com 

Code Explanation:

Function: swap_numbers
def swap_numbers(a, b):
    a = a + b
    b = a - b
    a = a - b
    return a, b
Purpose: This function swaps the values of a and b using arithmetic operations.
Process:
a = a + b: The sum of a and b is stored in a.
b = a - b: The new value of b becomes the original value of a.
a = a - b: The new value of a becomes the original value of b.

Return Value: The function returns the swapped values of a and b.

a = int(input("Enter the first number: "))
b = int(input("Enter the second number: "))
Input:
Prompts the user to enter two integers (a and b).
Converts the inputs into integers using int().
a, b = swap_numbers(a, b)

Function Call: Passes the user-provided values of a and b to the swap_numbers function.
Result: After the function executes, the values of a and b are swapped.

print(f"After swapping: First number = {a} and Second number = {b}")

Output: 
Prints the swapped values of a and b.

Wednesday, 18 December 2024

Day 45: Python Program to Compute a Polynomial Equation

 


def compute_polynomial(coefficients, x):

    result = 0

    n = len(coefficients)

    for i in range(n):

        result += coefficients[i] * (x ** (n - 1 - i))

    return result

coefficients = [1, -3, 2]  

x_value = 5  

result = compute_polynomial(coefficients, x_value)

print(f"The value of the polynomial at x = {x_value} is: {result}")

#source code --> clcoding.com 

Code Explanation:

Function Definition:
def compute_polynomial(coefficients, x):
This defines a function named compute_polynomial which takes two parameters:
coefficients: A list of coefficients for the polynomial.
x: The value at which the polynomial will be evaluated.

Initialize the result:
    result = 0
Here, the variable result is initialized to 0. This will store the final computed value of the polynomial as the function evaluates it.
Get the length of the coefficients list:

    n = len(coefficients)
n holds the number of coefficients in the list coefficients. This helps in determining the degree of the polynomial.

Loop through the coefficients:
    for i in range(n):
        result += coefficients[i] * (x ** (n - 1 - i))
This loop iterates over each coefficient in the coefficients list. For each coefficient:
i is the loop index (ranging from 0 to n-1).
The term coefficients[i] * (x ** (n - 1 - i)) computes the contribution of the current term in the polynomial.
The polynomial is evaluated using the following formula:

result=i=0n1coefficients[i]×xn1i

coefficients[i] is the coefficient of the 𝑖
i-th term.
x ** (n - 1 - i) raises x to the power of 

n-1-i, which represents the degree of each term in the polynomial (starting from the highest degree).
The result is updated with each term's value as the loop proceeds.

Return the result:
    return result
After the loop has completed, the function returns the value stored in result, which is the final value of the polynomial evaluated at x.

Call the function and print the result:
result = compute_polynomial(coefficients, x_value)
print(f"The value of the polynomial at x = {x_value} is: {result}")
The function compute_polynomial is called with coefficients = [1, -3, 2] and x_value = 5. The result is stored in the result variable, and then the value is printed.

Output:

The value of the polynomial at x = 5 is: 12

Day 44: Python Program To Print Pascal Triangle

 


def print_pascals_triangle(n):

    triangle = [[1]]

    for i in range(1, n):

        previous_row = triangle[-1]

        current_row = [1]  

        for j in range(1, len(previous_row)):

            current_row.append(previous_row[j - 1] + previous_row[j])

        current_row.append(1)  

        triangle.append(current_row)

        for row in triangle:

        print(" " * (n - len(row)), " ".join(map(str, row)))

rows = int(input("Enter the number of rows: "))

print_pascals_triangle(rows)

#source code --> clcoding.com

Code Explanation:

1. Function Definition

def print_pascals_triangle(n):
A function print_pascals_triangle is defined, which takes one argument n (the number of rows to generate).

2. Initializing the Triangle

    triangle = [[1]]
The triangle is initialized with a single row containing the number 1.

3. Building the Triangle

    for i in range(1, n):
        previous_row = triangle[-1]
        current_row = [1]  
A loop runs from 1 to n - 1, generating rows of the triangle:
previous_row: Refers to the last row of the triangle.
current_row: Starts with a 1, as every row in Pascal's Triangle begins with 1.

        for j in range(1, len(previous_row)):
            current_row.append(previous_row[j - 1] + previous_row[j])
For each position in the row (except the first and last), the value is calculated as the sum of the two numbers directly above it from the previous_row.

        current_row.append(1)
        triangle.append(current_row)
The row ends with another 1, and the current_row is appended to the triangle.

4. Printing the Triangle
    for row in triangle:
        print(" " * (n - len(row)), " ".join(map(str, row)))
Each row of the triangle is printed with formatting:
" " * (n - len(row)): Adds spaces to align rows, creating the triangular shape.
" ".join(map(str, row)): Converts numbers in the row to strings and joins them with spaces for proper display.

5. User Input and Function Call
rows = int(input("Enter the number of rows: "))
print_pascals_triangle(rows)
The program prompts the user to input the number of rows and calls the print_pascals_triangle function with the input.

Example Execution
Input:
Enter the number of rows: 5

Output:

     1
    1 1
   1 2 1
  1 3 3 1
 1 4 6 4 1

Tuesday, 17 December 2024

Day 43: Python Program To Find All Pythagorean Triplets in a Given Range


 def find_pythagorean_triplets(limit):
    triplets = []
    for a in range(1, limit + 1):
        for b in range(a, limit + 1): 
            for c in range(b, limit + 1):
                if a**2 + b**2 == c**2:
                    triplets.append((a, b, c))
    return triplets

limit = int(input("Enter the range limit: "))
triplets = find_pythagorean_triplets(limit)

print("Pythagorean Triplets in the range 1 to", limit, "are:")
for triplet in triplets:
    print(triplet)
#source code --> clcoding.com 

Code Explanation:

1.Function:
find_pythagorean_triplets(limit)
Purpose:
To find all the Pythagorean triplets for numbers in the range 1 to limit.

How it works:
It initializes an empty list triplets to store valid triplets.
It uses three nested for loops to iterate through all possible values of a, b, and c such that:
a starts from 1 and goes up to limit.
b starts from a (to avoid duplicate combinations like (3,4,5) and (4,3,5)) and goes up to limit.
c starts from b (ensuring a <= b <= c to maintain order) and also goes up to limit.
If the condition is true, the triplet (a, b, c) is added to the triplets list.
Finally, the list of valid triplets is returned.

2. Input:
The user is asked to enter a positive integer limit using input(). This defines the upper range for a, b, and c.

3. Output:
The function find_pythagorean_triplets(limit) is called with the input range.
It prints all valid Pythagorean triplets found within the range 1 to limit.

Example Execution:

Input:
Enter the range limit: 20

Output:
Pythagorean Triplets in the range 1 to 20 are:
(3, 4, 5)
(5, 12, 13)
(6, 8, 10)
(8, 15, 17)
(9, 12, 15)
(12, 16, 20)

Day 42: Python Program To Find Quotient And Remainder Of Two Number

 


numerator = int(input("Enter the numerator: "))

denominator = int(input("Enter the denominator: "))

if denominator == 0:

    print("Division by zero is not allowed.")

else:

    quotient = numerator // denominator

    remainder = numerator % denominator

     print(f"The quotient is: {quotient}")

    print(f"The remainder is: {remainder}")

#source code --> clcoding.com 

Code Explanation:

1. User Input

numerator = int(input("Enter the numerator: "))

denominator = int(input("Enter the denominator: "))

input(): This function takes user input as a string.

int(): Converts the input string into an integer so that arithmetic operations can be performed.

numerator: The number to be divided.

denominator: The number by which the numerator is divided.

Example Input:

Enter the numerator: 10  

Enter the denominator: 3  

2. Check for Division by Zero

if denominator == 0:

    print("Division by zero is not allowed.")

Why this check?

Division by zero is undefined in mathematics and causes a runtime error in Python.

The condition if denominator == 0 checks if the user entered 0 for the denominator.

If the condition is True, a message is printed:

Division by zero is not allowed.

The program stops further execution in this case.

3. Perform Division

If the denominator is not zero, the program proceeds to calculate the quotient and remainder:

    quotient = numerator // denominator

    remainder = numerator % denominator

// Operator (Integer Division):

Divides the numerator by the denominator and returns the quotient without any decimal places.

Example: 10 // 3 results in 3.

% Operator (Modulus):

Divides the numerator by the denominator and returns the remainder of the division.

Example: 10 % 3 results in 1.

4. Output the Results

    print(f"The quotient is: {quotient}")

    print(f"The remainder is: {remainder}")

f-strings: Used to format strings with variable values.

{quotient} and {remainder} are placeholders that will be replaced with their respective values.

Example Output:

The quotient is: 3  

The remainder is: 1

Popular Posts

Categories

100 Python Programs for Beginner (63) AI (34) Android (24) AngularJS (1) Assembly Language (2) aws (17) Azure (7) BI (10) book (4) Books (174) C (77) C# (12) C++ (82) Course (67) Coursera (228) Cybersecurity (24) data management (11) Data Science (128) Data Strucures (8) Deep Learning (21) 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 (60) Meta (22) MICHIGAN (5) microsoft (4) Nvidia (3) Pandas (4) PHP (20) Projects (29) Python (941) Python Coding Challenge (378) Python Quiz (34) Python Tips (3) Questions (2) R (70) React (6) Scripting (1) security (3) Selenium Webdriver (4) Software (17) SQL (42) UX Research (1) web application (8) Web development (4) web scraping (2)

Followers

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