Author name: Vikram Chiluka

Program to Convert Binary to Decimal using Recursion

Python Program to Convert Binary to Decimal using Recursion

In the previous article, we have discussed Python Program for Sign Change
Recursion:

Recursion is the process by which a function calls itself directly or indirectly, and the associated function is known as a recursive function. Certain issues can be addressed fairly easily using a recursive approach. Towers of Hanoi (TOH), Inorder /Preorder/Postorder Tree Traversals, DFS of Graph, and other analogous issues are examples.

Binary Code:

As previously stated, Binary Code is a Base-2 representation of a number. In Binary, all numbers are represented by simply two symbols: 0 and 1. Binary (also known as base-2) is a numerical system with only two digits: 0 and 1.

Given a binary string, the task is to convert the given binary string to a decimal number using recursion in Python.

Examples:

Example1:

Input:

Given binary number = 1011

Output:

The decimal Equivalent of the given binary number { 1011 } is : 11

Example2:

Input:

Given binary number = 10010101

Output:

The decimal Equivalent of the given binary number { 10010101 } is : 149

Program to Convert Binary to Decimal using Recursion in Python

Below are the ways to convert the given binary string to a decimal number using recursion in Python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the binary number as static input and store it in a variable.
  • Create a recursive function to say binaryToDeci() which accepts the binary number as an argument and returns the decimal equivalent of the given binary string.
  • Inside the binaryToDeci() function, Check if the binary number is equal to 0 using the if conditional statement.
  • If it is true then return 0.
  • Else return (n% 10 + 2* binaryToDeci(n // 10)) {Recursive logic where n%10 gives rightmostbit and n//10 divides the number by 10 which removes the last bit}.
  • Inside the main function pass the given binary number as an argument to binaryToDeci() which returns the decimal equivalent of the given binary number.
  • Print the decimal equivalent of the given binary number.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say binaryToDeci()
# which accepts the binary number as an argument
# and returns the decimal equivalent of the given binary string.


def binaryToDeci(binanumb):
    # Inside the binaryToDeci() function,
    # Check if the binary number is equal to 0 using the if conditional statement.
    if(binanumb == 0):
        # If it is true then return 0.
        return 0
    # Else return (n% 10 + 2* binaryToDeci(n // 10))
    # {Recursive logic where n%10 gives rightmostbit and n//10 divides the number by 10}.
    return (binanumb % 10 + 2 * binaryToDeci(binanumb // 10))


# Give the binary number as static input and store it in a variable.
gvnbinarynumb = 1011
# Inside the main function pass the given binary number as an argument
# to binaryToDeci() which returns the decimal equivalent of the given binary number.
resdecimalnumbr = binaryToDeci(gvnbinarynumb)
# Print the decimal equivalent of the given binary number.
print(
    'The decimal Equivalent of the given binary number {', gvnbinarynumb, '} is :', resdecimalnumbr)

Output:

The decimal Equivalent of the given binary number { 1011 } is : 11

Method #2: Using Recursion (User Input)

Approach:

  • Give the binary number as user input using int(input()) function and store it in a variable.
  • Create a recursive function to say binaryToDeci() which accepts the binary number as an argument and returns the decimal equivalent of the given binary string.
  • Inside the binaryToDeci() function, Check if the binary number is equal to 0 using the if conditional statement.
  • If it is true then return 0.
  • Else return (n% 10 + 2* binaryToDeci(n // 10)) {Recursive logic where n%10 gives rightmostbit and n//10 divides the number by 10 which removes the last bit}.
  • Inside the main function pass the given binary number as an argument to binaryToDeci() which returns the decimal equivalent of the given binary number.
  • Print the decimal equivalent of the given binary number.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say binaryToDeci()
# which accepts the binary number as an argument
# and returns the decimal equivalent of the given binary string.


def binaryToDeci(binanumb):
    # Inside the binaryToDeci() function,
    # Check if the binary number is equal to 0 using the if conditional statement.
    if(binanumb == 0):
        # If it is true then return 0.
        return 0
    # Else return (n% 10 + 2* binaryToDeci(n // 10))
    # {Recursive logic where n%10 gives rightmostbit and n//10 divides the number by 10}.
    return (binanumb % 10 + 2 * binaryToDeci(binanumb // 10))


# Give the binary number as user input using int(input()) function
# and store it in a variable.
gvnbinarynumb = int(input('Enter some random binary number = '))
# Inside the main function pass the given binary number as an argument
# to binaryToDeci() which returns the decimal equivalent of the given binary number.
resdecimalnumbr = binaryToDeci(gvnbinarynumb)
# Print the decimal equivalent of the given binary number.
print(
    'The decimal Equivalent of the given binary number {', gvnbinarynumb, '} is :', resdecimalnumbr)

Output:

Enter some random binary number = 10010101
The decimal Equivalent of the given binary number { 10010101 } is : 149

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Convert Binary to Decimal using Recursion Read More »

Program for Sign Change

Python Program for Sign Change

In the previous article, we have discussed Python Program to Find the Previous Armstrong Number
Given a String and the task is to change the ‘+’ sign into ‘-‘ and vice versa for a given string.

Examples:

Example1:

Input:

Given String = "  --btech++geeks-- "

Output:

The given string { --btech++geeks-- } after changing the '+' sign into '-' and vice versa = ++btech--geeks++

Example2:

Input:

Given String = "--1++2--3+"

Output:

The given string { --1++2--3+ } after changing the '+' sign into '-' and vice versa = ++1--2++3-

Program for Sign Change in Python

Below are ways to change the ‘+’ sign into ‘-‘ and vice versa for a given string  :

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take an empty string say “new_str” and store it in another variable.
  • Loop in the given string using the for loop.
  • Inside the loop, check if the iterator value is equal to ‘+’ sign using the if conditional statement.
  • If it is true, then concatenate the  ‘-‘ sign with the new_str and store it in the same variable new_str.
  • Check if the iterator value is equal to the ‘-‘ sign using the elif conditional statement.
  • If it is true, then concatenate the  ‘+’ sign with the new_str and store it in the same variable new_str.
  • Else concatenate the iterator value to the new_str and store it in the same variable new_str.
  • Print the given string after changing the ‘+’ sign into ‘-‘ and vice versa.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = "32--1++4"
# Take an empty string say "new_str" and store it in another variable.
new_str = ""
# Loop in the given string using the for loop.
for itr in gvn_str:
  # Inside the loop, check if the iterator value is equal to '+' sign using the if
    # conditional statement.
    if(itr == "+"):
        # If it is true, then concatenate the  '-' sign with the new_str and store it in the
        # same variable new_str.
        new_str += "-"
# Check if the iterator value is equal to the '-' sign using the elif conditional statement.
    elif(itr == "-"):
      # If it is true, then concatenate the  '+' sign with the new_str and store it in the
        # same variable new_str.
        new_str += "+"
    else:
     # Else concatenate the iterator value to the new_str and store it in the same variable new_str.
        new_str += itr
# Print the given string after changing the '+' sign into '-' and vice versa.
print("The given string {", gvn_str,
      "} after changing the '+' sign into '-' and vice versa =", new_str)

Output:

The given string { 32--1++4 } after changing the '+' sign into '-' and vice versa = 32++1--4

Method #2: Using For loop (User Input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Take an empty string say “new_str” and store it in another variable.
  • Loop in the given string using the for loop.
  • Inside the loop, check if the iterator value is equal to ‘+’ sign using the if conditional statement.
  • If it is true, then concatenate the  ‘-‘ sign with the new_str and store it in the same variable new_str.
  • Check if the iterator value is equal to the ‘-‘ sign using the elif conditional statement.
  • If it is true, then concatenate the  ‘+’ sign with the new_str and store it in the same variable new_str.
  • Else concatenate the iterator value to the new_str and store it in the same variable new_str.
  • Print the given string after changing the ‘+’ sign into ‘-‘ and vice versa.
  • The Exit of the program.

Below is the implementation:

# Give the string as user input using the input() function and
# store it in a variable.
gvn_str = input("Enter some random String = ")
# Take an empty string say "new_str" and store it in another variable.
new_str = ""
# Loop in the given string using the for loop.
for itr in gvn_str:
  # Inside the loop, check if the iterator value is equal to '+' sign using the if
    # conditional statement.
    if(itr == "+"):
        # If it is true, then concatenate the  '-' sign with the new_str and store it in the
        # same variable new_str.
        new_str += "-"
# Check if the iterator value is equal to the '-' sign using the elif conditional statement.
    elif(itr == "-"):
      # If it is true, then concatenate the  '+' sign with the new_str and store it in the
        # same variable new_str.
        new_str += "+"
    else:
     # Else concatenate the iterator value to the new_str and store it in the same variable new_str.
        new_str += itr
# Print the given string after changing the '+' sign into '-' and vice versa.
print("The given string {", gvn_str,
      "} after changing the '+' sign into '-' and vice versa =", new_str)

Output:

Enter some random String = btech++--geeks+++--
The given string { btech++--geeks+++-- } after changing the '+' sign into '-' and vice versa = btech--++geeks---++

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program for Sign Change Read More »

Program to Find Next Prime Number

Python Program to Find the Previous Armstrong Number

In the previous article, we have discussed Python Program to Find the Next Armstrong Number
Armstrong Number:

Beginners sometimes ask what the Armstrong number, also known as the narcissist number, is. Because of the way the number behaves in a given number base, it is particularly interesting to new programmers and those learning a new programming language. The Armstrong number meaning in numerical number theory is the number in any given number base that forms the sum of the same number when each of its digits is raised to the power of the number’s digits.

Itertools count() function:

The count(start, step) method generates an iterator that is used to generate equally spaced numbers, where the step argument defines the space between them. The start argument specifies the iterator’s starting value, which is set by default to start=0 and step=1.

In the absence of a breaking condition, the count() method will continue counting indefinitely (on a system with infinite memory)

Given a number, the task is to print the previous Armstrong number in Python.

Examples:

Example1:

Input:

Given Number =67

Output:

The previous armstrong number of { 67 } is : 9

Example2:

Input:

Given Number =450

Output:

The previous armstrong number of { 450 } is : 407

Program to Find the Previous Armstrong Number in Python

Below are the ways to find the previous Armstrong number in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Import the count from the itertools module using the import and from keyword.
  • Give the number n as static input and store it in a variable.
  • Loop till the given number in decreasing order using the For loop and the count() function.
  • Convert the given number to the string using the str() function and store it in a variable say strngnumb.
  • Take a variable say cuntsum and initialize its value to 0.
  • Loop in the strngnumb using the nested For loop(Inner For loop).
  • Calculate the length of the string using the len() function and store it in a variable to say strnglengt.
  • Convert the inner loop iterator value to an integer using the int() function and store it as a new variable say intitr.
  • Inside the for loop, increment the value of cuntsum with intitr**strnglengt(where ** is power operator).
  • After the end of For loop check if cuntsum is equal to the iterator value of the inner for loop using the if conditional statement.
  • If it is true then print the value of cuntsum.
  • Break the parent for loop using the break keyword.
  • The Exit of the program.

Below is the implementation:

# Import the count from the itertools module using the import and from keyword.
from itertools import count
# Give the number n as static input and store it in a variable.
gvnnumb = 67
# Loop till the given number in decreasing order using the For loop
# and the count() function.
for m in count(gvnnumb, -1):
        # Convert the given number to the string using the str() function
    # and store it in a variable say strngnumb.
    strngnumb = str(m)
    # Take a variable say cuntsum and initialize its value to 0.
    cuntsum = 0
    # Calculate the length of the string using the len() function
    # and store it in a variable to say
    strnglengt = len(strngnumb)
    # Loop in the strngnumb using the nested For loop(Inner For loop).
    for dgtval in strngnumb:
                # Convert the inner loop iterator value to an integer using the int() function
        # and store it as a new variable say intitr.
        intitr = int(dgtval)
        # Inside the for loop, increment the value of cuntsum with intitr**strnglengt(where ** is power operator).
        cuntsum += intitr**strnglengt
        # After the end of For loop check if cuntsum is equal to the iterator value
    # of the inner for loop using the if conditional statement.

    if(cuntsum == m):
                # If it is true then print the value of cuntsum.
        print('The previous armstrong number of {', gvnnumb, '} is :', cuntsum)
        # Break the parent for loop using the break keyword.
        break

Output:

The previous armstrong number of { 67 } is : 9

Method #2: Using For loop (User Input)

Approach:

  • Import the count from the itertools module using the import and from keyword.
  • Give the number n as user input using the int(input()) function and store it in a variable.
  • Loop till the given number in decreasing order using the For loop and the count() function.
  • Convert the given number to the string using the str() function and store it in a variable say strngnumb.
  • Take a variable say cuntsum and initialize its value to 0.
  • Loop in the strngnumb using the nested For loop(Inner For loop).
  • Calculate the length of the string using the len() function and store it in a variable to say strnglengt.
  • Convert the inner loop iterator value to an integer using the int() function and store it as a new variable say intitr.
  • Inside the for loop, increment the value of cuntsum with intitr**strnglengt(where ** is power operator).
  • After the end of For loop check if cuntsum is equal to the iterator value of the inner for loop using the if conditional statement.
  • If it is true then print the value of cuntsum.
  • Break the parent for loop using the break keyword.
  • The Exit of the program.

Below is the implementation:

# Import the count from the itertools module using the import and from keyword.
from itertools import count
# Give the number n as user input using the int(input()) function and store it in a variable.
gvnnumb = int(input('Enter some random number = '))
# Loop till the given number in decreasing order using the For loop
# and the count() function.
for m in count(gvnnumb, -1):
        # Convert the given number to the string using the str() function
    # and store it in a variable say strngnumb.
    strngnumb = str(m)
    # Take a variable say cuntsum and initialize its value to 0.
    cuntsum = 0
    # Calculate the length of the string using the len() function
    # and store it in a variable to say
    strnglengt = len(strngnumb)
    # Loop in the strngnumb using the nested For loop(Inner For loop).
    for dgtval in strngnumb:
                # Convert the inner loop iterator value to an integer using the int() function
        # and store it as a new variable say intitr.
        intitr = int(dgtval)
        # Inside the for loop, increment the value of cuntsum with intitr**strnglengt(where ** is power operator).
        cuntsum += intitr**strnglengt
        # After the end of For loop check if cuntsum is equal to the iterator value
    # of the inner for loop using the if conditional statement.

    if(cuntsum == m):
                # If it is true then print the value of cuntsum.
        print('The previous armstrong number of {', gvnnumb, '} is :', cuntsum)
        # Break the parent for loop using the break keyword.
        break

Output:

Enter some random number = 450
The previous armstrong number of { 450 } is : 407

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Find the Previous Armstrong Number Read More »

Program to Find the Next Armstrong Number

Python Program to Find the Next Armstrong Number

In the previous article, we have discussed Python Program to Find next Prime Number
Armstrong Number:

Beginners sometimes ask what the Armstrong number, also known as the narcissist number, is. Because of the way the number behaves in a given number base, it is particularly interesting to new programmers and those learning a new programming language. The Armstrong number meaning in numerical number theory is the number in any given number base that forms the sum of the same number when each of its digits is raised to the power of the number’s digits.

Itertools count() function:

The count(start, step) method generates an iterator that is used to generate equally spaced numbers, where the step argument defines the space between them. The start argument specifies the iterator’s starting value, which is set by default to start=0 and step=1.

In the absence of a breaking condition, the count() method will continue counting indefinitely (on a system with infinite memory)

Given a number, the task is to print the next Armstrong number in Python.

Examples:

Example1:

Input:

Given Number =56

Output:

The Next armstrong number of { 56 } is : 153

Example2:

Input:

Given Number =250

Output:

The Next armstrong number of { 250 } is : 370

Program to Find the Next Armstrong Number in Python

Below are the ways to find the next Armstrong number in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Import the count from the itertools module using the import and from keyword.
  • Give the number n as static input and store it in a variable.
  • Loop till the given number using the For loop and the count() function.
  • Convert the given number to the string using the str() function and store it in a variable say strngnumb.
  • Take a variable say cuntsum and initialize its value to 0.
  • Loop in the strngnumb using the nested For loop(Inner For loop).
  • Calculate the length of the string using the len() function and store it in a variable to say strnglengt.
  • Convert the inner loop iterator value to an integer using the int() function and store it as a new variable say intitr.
  • Inside the for loop, increment the value of cuntsum with intitr**strnglengt(where ** is power operator).
  • After the end of For loop check if cuntsum is equal to the iterator value of the inner for loop using the if conditional statement.
  • If it is true then print the value of cuntsum.
  • Break the parent for loop using the break keyword.
  • The Exit of the program.

Below is the implementation:

# Import the count from the itertools module using the import and from keyword.
from itertools import count
# Give the number n as static input and store it in a variable.
gvnnumb = 56
# Loop till the given number using the For loop and the count() function.
for m in count(gvnnumb):
        # Convert the given number to the string using the str() function
    # and store it in a variable say strngnumb.
    strngnumb = str(m)
    # Take a variable say cuntsum and initialize its value to 0.
    cuntsum = 0
    # Calculate the length of the string using the len() function
    # and store it in a variable to say
    strnglengt = len(strngnumb)
    # Loop in the strngnumb using the nested For loop(Inner For loop).
    for dgtval in strngnumb:
                # Convert the inner loop iterator value to an integer using the int() function
        # and store it as a new variable say intitr.
        intitr = int(dgtval)
        # Inside the for loop, increment the value of cuntsum with intitr**strnglengt(where ** is power operator).
        cuntsum += intitr**strnglengt
        # After the end of For loop check if cuntsum is equal to the iterator value
    # of the inner for loop using the if conditional statement.

    if(cuntsum == m):
                # If it is true then print the value of cuntsum.
        print('The Next armstrong number of {', gvnnumb, '} is :', cuntsum)
        # Break the parent for loop using the break keyword.
        break

Output:

The Next armstrong number of { 56 } is : 153

Method #2: Using For loop (User Input)

Approach:

  • Import the count from the itertools module using the import and from keyword.
  • Give the number n as user input using the int(input()) function and store it in a variable.
  • Loop till the given number using the For loop and the count() function.
  • Convert the given number to the string using the str() function and store it in a variable say strngnumb.
  • Take a variable say cuntsum and initialize its value to 0.
  • Loop in the strngnumb using the nested For loop(Inner For loop).
  • Calculate the length of the string using the len() function and store it in a variable to say strnglengt.
  • Convert the inner loop iterator value to an integer using the int() function and store it as a new variable say intitr.
  • Inside the for loop, increment the value of cuntsum with intitr**strnglengt(where ** is power operator).
  • After the end of For loop check if cuntsum is equal to the iterator value of the inner for loop using the if conditional statement.
  • If it is true then print the value of cuntsum.
  • Break the parent for loop using the break keyword.
  • The Exit of the program.

Below is the implementation:

# Import the count from the itertools module using the import and from keyword.
from itertools import count
# Give the number n as user input using the int(input()) function and store it in a variable.
gvnnumb = int(input('Enter some random number = '))
# Loop till the given number using the For loop and the count() function.
for m in count(gvnnumb):
        # Convert the given number to the string using the str() function
    # and store it in a variable say strngnumb.
    strngnumb = str(m)
    # Take a variable say cuntsum and initialize its value to 0.
    cuntsum = 0
    # Calculate the length of the string using the len() function
    # and store it in a variable to say
    strnglengt = len(strngnumb)
    # Loop in the strngnumb using the nested For loop(Inner For loop).
    for dgtval in strngnumb:
                # Convert the inner loop iterator value to an integer using the int() function
        # and store it as a new variable say intitr.
        intitr = int(dgtval)
        # Inside the for loop, increment the value of cuntsum with intitr**strnglengt(where ** is power operator).
        cuntsum += intitr**strnglengt
        # After the end of For loop check if cuntsum is equal to the iterator value
    # of the inner for loop using the if conditional statement.

    if(cuntsum == m):
                # If it is true then print the value of cuntsum.
        print('The Next armstrong number of {', gvnnumb, '} is :', cuntsum)
        # Break the parent for loop using the break keyword.
        break

Output:

Enter some random number = 250
The Next armstrong number of { 250 } is : 370

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Find the Next Armstrong Number Read More »

Program to Find Next Prime Number

Python Program to Find Next Prime Number

In the previous article, we have discussed Python Program to Compute the Perimeter of Trapezoid
Itertools count() function:

The count(start, step) method generates an iterator that is used to generate equally spaced numbers, where the step argument defines the space between them. The start argument specifies the iterator’s starting value, which is set by default to start=0 and step=1.

In the absence of a breaking condition, the count() method will continue counting indefinitely (on a system with infinite memory)

Given a number N, the task is to print the next prime number in Python.

Examples:

Example1:

Input:

Given Number =48

Output:

The Next prime number of { 48 } is: 53

Example2:

Input:

Given Number =75

Output:

The Next prime number of { 75 } is: 79

Program to Find next Prime Number in Python

Below are the ways to print the next prime number in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Import the count from the itertools module using the import and from keyword.
  • Give the number n as static input and store it in a variable.
  • Loop till the given number using the For loop and the count() function.
  • Inside the For loop, Iterate from 2 to the iterator value of the parent loop using another For loop and range() functions(Nested For loop).
  • Check if the inner loop iterator value divides the parent loop iterator value using the if conditional statement.
  • If it is true then break the inner for loop using the break keyword.
  • else print the iterator value of the parent For loop.
  • Break the parent for loop using the break keyword.
  • The Exit of the Program.

Below is the implementation:

# Import the count from the itertools module using the import and from keyword.
from itertools import count
# Give the number n as static input and store it in a variable.
gvnnumb = 48

# Loop from 1 to given number using the For loop and the count() function.
for m in count(gvnnumb+1):
        # Inside the For loop, Iterate from 2 to the iterator value
    # of the parent loop using another For loop and range() functions(Nested For loop).
    for n in range(2, m):
        # Check if the inner loop iterator value divides
        # the parent loop iterator value using the if conditional statement.
        if(m % n == 0):
            # If it is true then break the inner for loop using the break keyword.
            break
    else:
        # else print the iterator value of the parent For loop.
        print('The Next prime number of {', gvnnumb, '} is:', m)
        # Break the parent for loop using the break keyword.
        break

Output:

The Next prime number of { 48 } is: 53

Method #2: Using For loop (User Input)

Approach:

  • Import the count from the itertools module using the import and from keyword.
  • Give the number n as user input using the int(input()) function and store it in a variable.
  • Loop from 1 to given number using the For loop and the count() function.
  • Inside the For loop, Iterate from 2 to the iterator value of the parent loop using another For loop and range() functions(Nested For loop).
  • Check if the inner loop iterator value divides the parent loop iterator value using the if conditional statement.
  • If it is true then break the inner for loop using the break keyword.
  • else print the iterator value of the parent For loop.
  • Break the parent for loop using the break keyword.
  • The Exit of the Program.

Below is the implementation:

# Import the count from the itertools module using the import and from keyword.
from itertools import count
# Give the number n as user input using the int(input()) function
# and store it in a variable.
gvnnumb = int(input('Enter some random number = '))

# Loop from 1 to given number using the For loop and the count() function.
for m in count(gvnnumb+1):
        # Inside the For loop, Iterate from 2 to the iterator value
    # of the parent loop using another For loop and range() functions(Nested For loop).
    for n in range(2, m):
        # Check if the inner loop iterator value divides
        # the parent loop iterator value using the if conditional statement.
        if(m % n == 0):
            # If it is true then break the inner for loop using the break keyword.
            break
    else:
        # else print the iterator value of the parent For loop.
        print('The Next prime number of {', gvnnumb, '} is:', m)
        # Break the parent for loop using the break keyword.
        break

Output:

Enter some random number = 75
The Next prime number of { 75 } is: 79

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Find Next Prime Number Read More »

Program to Compute the Perimeter of Trapezoid

Python Program to Compute the Perimeter of Trapezoid

In the previous article, we have discussed Python Program to Compute 1/N!
Trapezoid:

A trapezoid is a four-sided geometrical figure with two sides that are parallel to each other. the sides that are parallel to each other are referred to as the “base” The other sides are referred to as “legs” (which may or may not be equal).

Formula to calculate Perimeter of a Trapezoid :

Perimeter (P) = a+b+c+d

where a, b = Bases of Trapezoid

c, d = Side length of Trapezoid

Given the values of a, b, c, d, and the task is to calculate the perimeter of the given Trapezoid.
Examples:

Example1:

Input:

Given a= 10
Given b= 20
Given c= 35
Given d= 45

Output:

The Trapezoid's perimeter with the given values of a,b,c,d { 10 20 35 45 } = 110

Example2:

Input:

Given a= 43
Given b= 17
Given c=  25.5
Given d= 32

Output:

The Trapezoid's perimeter with the given values of a,b,c,d { 43 17 25.5 32 } = 117.5

Program to Compute the Perimeter of Trapezoid in Python

Below are the ways to calculate the perimeter of the given Trapezoid:

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Give the first base of the trapezoid as static input and store it in a variable.
  • Give another base of the trapezoid as static input and store it in another variable.
  • Give the first side length of the trapezoid as static input and store it in a variable.
  • Give another side length of the trapezoid as static input and store it in another variable.
  • Calculate the perimeter of the given trapezoid using the above given mathematical formula.
  • Store it in another variable.
  • Print the Trapezoid’s perimeter with the given values of bases and side lengths.
  • The Exit of the program.

Below is the implementation:

# Give the first base of the trapezoid as static input and store it in a variable.
gvn_a = 10
# Give another base of the trapezoid as static input and store it in another variable.
gvn_b = 20
# Give the first side length of the trapezoid as static input and store it in a variable.
gvn_c = 35
# Give another side length of the trapezoid as static input and store it in another variable.
gvn_d = 45
# Calculate the perimeter of the given trapezoid using the above given mathematicalformula.
# Store it in another variable.
Trapzod_perimetr = gvn_a+gvn_b+gvn_c+gvn_d
# Print the Trapezoid's perimeter with the given values of bases and side lengths.
print(
    "The Trapezoid's perimeter with the given values of a,b,c,d {", gvn_a, gvn_b, gvn_c, gvn_d, "} =", Trapzod_perimetr)

Output:

The Trapezoid's perimeter with the given values of a,b,c,d { 10 20 35 45 } = 110

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Give the first base of the trapezoid as user input using the float(input()) function and store it in a variable.
  • Give another base of the trapezoid as user input using the float(input()) function and store it in another variable.
  • Give the first side length of the trapezoid as user input using the float(input()) function and store it in a variable.
  • Give another side length of the trapezoid as user input using the float(input()) function and store it in another variable.
  • Calculate the perimeter of the given trapezoid using the above given mathematical formula.
  • Store it in another variable.
  • Print the Trapezoid’s perimeter with the given values of bases and side lengths.
  • The Exit of the program.

Below is the implementation of the above given approach:

# Give the first base of the trapezoid as user input using the float(input()) function
# and store it in a variable.
gvn_a = float(input("Enter some random variable = "))
# Give another base of the trapezoid as user input using the float(input()) function
# and store it in another variable.
gvn_b = float(input("Enter some random variable = "))
# Give the first side length of the trapezoid as user input using the float(input())
# function and store it in a variable.
gvn_c = float(input("Enter some random variable = "))
# Give another side length of the trapezoid as user input using the float(input())
# function and store it in another variable.
gvn_d = float(input("Enter some random variable = "))
# Calculate the perimeter of the given trapezoid using the above given mathematicalformula.
# Store it in another variable.
Trapzod_perimetr = gvn_a+gvn_b+gvn_c+gvn_d
# Print the Trapezoid's perimeter with the given values of bases and side lengths.
print(
    "The Trapezoid's perimeter with the given values of a,b,c,d {", gvn_a, gvn_b, gvn_c, gvn_d, "} =", Trapzod_perimetr)

Output:

Enter some random variable = 43
Enter some random variable = 12.6
Enter some random variable = 4.9
Enter some random variable = 20
The Trapezoid's perimeter with the given values of a,b,c,d { 43.0 12.6 4.9 20.0 } = 80.5

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Compute the Perimeter of Trapezoid Read More »

Program to Compute 1N!

Python Program to Compute 1/N!

In the previous article, we have discussed Python Program to Calculate the Surface Area and Volume of a Hemisphere
Factorial:

The product of all positive integers less than or equal to n is the factorial of a non-negative integer n, denoted by n! in mathematics:

n! = n * (n – 1) *(n – 2) * . . . . . . . . . . 3 * 2 * 1.

4 != 4 * 3 * 2 *1= 24

Given a number N and the task is to calculate the value of 1/N!

Examples:

Example1:

Input:

Given Number = 4

Output:

The value of 1/n! with given n value{ 4 } = 0.041666666666666664

Example2:

Input:

Given Number = 6

Output:

The value of 1/n! with given n value{ 6 } = 0.001388888888888889

Program to Compute 1/N! in Python

Below are the ways to calculate the value of 1/N! :

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a variable, initialize it with the value ‘1’, and store it in another variable say ‘factorl‘.
  • Loop from 1 to the given number using the for loop.
  • Inside the loop, calculate the factorial of a given number by multiplying the value of the above variable “factorl” with the iterator value.
  • Store it in the same variable ‘factorl‘.
  • Calculate the value of 1/factorl and store it in another variable.
  • Print the value of 1/N! for the given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gven_nval = 4
# Take a variable, initialize it with the value '1', and store it in another variable say
# 'factorl'.
factorl = 1
# Loop from 1 to the given number using the for loop.
for itr in range(1, gven_nval+1):
  # Inside the loop, calculate the factorial of a given number by multiplying the value of
    # the above variable "factorl" with the iterator value.
    # Store it in the same variable 'factorl'.
    factorl *= itr
# Calculate the value of 1/factorl and store it in another variable.
fnl_reslt = 1.0/factorl
# Print the value of 1/N! for the given number.
print("The value of 1/n! with given n value{", gven_nval, "} =", fnl_reslt)

Output:

The value of 1/n! with given n value{ 4 } = 0.041666666666666664

Method #2: Using For loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Take a variable, initialize it with the value ‘1’, and store it in another variable say ‘factorl‘.
  • Loop from 1 to the given number using the for loop.
  • Inside the loop, calculate the factorial of a given number by multiplying the value of the above variable “factorl” with the iterator value.
  • Store it in the same variable ‘factorl‘.
  • Calculate the value of 1/factorl and store it in another variable.
  • Print the value of 1/N! for the given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and store it in a variable.
gven_nval = int(input("Enter some random Number = "))
# Take a variable, initialize it with the value '1', and store it in another variable say
# 'factorl'.
factorl = 1
# Loop from 1 to the given number using the for loop.
for itr in range(1, gven_nval+1):
  # Inside the loop, calculate the factorial of a given number by multiplying the value of
    # the above variable "factorl" with the iterator value.
    # Store it in the same variable 'factorl'.
    factorl *= itr
# Calculate the value of 1/factorl and store it in another variable.
fnl_reslt = 1.0/factorl
# Print the value of 1/N! for the given number.
print("The value of 1/n! with given n value{", gven_nval, "} =", fnl_reslt)

Output:

Enter some random Number = 6
The value of 1/n! with given n value{ 6 } = 0.001388888888888889

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Compute 1/N! Read More »

Program to Calculate the Surface Area and Volume of a Hemisphere

Python Program to Calculate the Surface Area and Volume of a Hemisphere

In the previous article, we have discussed Python Program to Compute x^n/n!
Math Module :

Python’s math module is a built-in module. By importing this module, we can perform mathematical computations.

Numerous mathematical operations like ceil( ),floor( ),factorial( ),mod( ),value of pi ,…..etc .can be computed with the help of math module.

Hemisphere:

The word hemisphere can be broken down into hemi and sphere, where hemi means half and sphere is a 3D geometric shape used in mathematics.

As a result, a hemisphere is a three-dimensional geometric shape that is half of a sphere, with one side flat and the other as a circular bowl.

Formula to calculate the surface area of a Hemisphere:

surface area = 3????r²

In which, r is the radius of the hemisphere.

Formula to calculate the volume of a Hemisphere:
Volume = (2/3)*????*r3
Given the Hemisphere’s radius and the task is to calculate the surface area and volume of the given Hemisphere.

Examples:

Example1:

Input:

Given Hemisphere's Radius = 9

Output:

The Surface Area of the given Hemisphere with radius { 9  } =  763.02
The Volume of the given Hemisphere with radius { 9 } =  1526.04

Example2:

Input:

Given Hemisphere's Radius = 12.5

Output:

The Surface Area of the given Hemisphere with radius { 12.5 } = 1471.875
The Volume of the given Hemisphere with radius { 12.5 } = 4088.5416666666665

Program to Calculate the Surface Area and Volume of a Hemisphere in Python

Below are the ways to Calculate the surface area and volume of a hemisphere with the given hemisphere’s  radius :

Method #1: Using Mathematical Formula (Static Input)

Approach:

  • Import the math module using the import keyword.
  • Give the hemisphere’s radius as static input and store it in a variable.
  • Take a variable and initialize it with the value of pi as 3.14.
  • Calculate the surface area of the given hemisphere using the above given mathematical formula and math.pow() function.
  • Store it in another variable.
  • Calculate the volume of the given hemisphere using the above given mathematical formula and math.pow() function.
  • Store it in another variable.
  • Print the hemisphere’s surface area with the given radius of the hemisphere.
  • Print the hemisphere’s perimeter with the given radius of the hemisphere.
  • The Exit of the program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the hemisphere's radius as static input and store it in a variable.
gvn_radus = 9
# Take a variable and initialize it with the value of pi as 3.14 .
valof_pi = 3.14
# Calculate the surface area of the given hemisphere using the above given mathematical
# formula and math.pow() function.
# Store it in another variable.
hemi_surfceara = 3*valof_pi*math.pow(gvn_radus, 2)
# Calculate the volume of the given hemisphere using the above given mathematical formula
# and math.pow() function.
# Store it in another variable.
hemi_volum = (2.0/3.0)*valof_pi*math.pow(gvn_radus, 3)
# Print the hemisphere's surface area with the given radius of the hemisphere.
print("The Surface Area of the given Hemisphere with radius {",
      gvn_radus, " } = ", hemi_surfceara)
# Print the hemisphere's perimeter with the given radius of the hemisphere.
print("The Volume of the given Hemisphere with radius {",
      gvn_radus, "} = ", hemi_volum)

Output:

The Surface Area of the given Hemisphere with radius { 9  } =  763.02
The Volume of the given Hemisphere with radius { 9 } =  1526.04

Method #2: Using Mathematical Formula (User Input)

Approach:

  • Import the math module using the import keyword.
  • Give the hemisphere’s radius as user input using the float(input()) function and store it in a variable.
  • Take a variable and initialize it with the value of pi as 3.14.
  • Calculate the surface area of the given hemisphere using the above given mathematical formula and math.pow() function.
  • Store it in another variable.
  • Calculate the volume of the given hemisphere using the above given mathematical formula and math.pow() function.
  • Store it in another variable.
  • Print the hemisphere’s surface area with the given radius of the hemisphere.
  • Print the hemisphere’s perimeter with the given radius of the hemisphere.
  • The Exit of the program.

Below is the implementation:

# Import the math module using the import keyword.
import math
# Give the hemisphere's radius as user input using the float(input()) function and
# store it in a variable.
gvn_radus = float(input("Enter some random variable = "))
# Take a variable and initialize it with the value of pi as 3.14 .
valof_pi = 3.14
# Calculate the surface area of the given hemisphere using the above given mathematical
# formula and math.pow() function.
# Store it in another variable.
hemi_surfceara = 3*valof_pi*math.pow(gvn_radus, 2)
# Calculate the volume of the given hemisphere using the above given mathematical formula
# and math.pow() function.
# Store it in another variable.
hemi_volum = (2.0/3.0)*valof_pi*math.pow(gvn_radus, 3)
# Print the hemisphere's surface area with the given radius of the hemisphere.
print("The Surface Area of the given Hemisphere with radius {",
      gvn_radus, " } = ", hemi_surfceara)
# Print the hemisphere's perimeter with the given radius of the hemisphere.
print("The Volume of the given Hemisphere with radius {",
      gvn_radus, "} = ", hemi_volum)

Output:

Enter some random variable = 12.5
The Surface Area of the given Hemisphere with radius { 12.5 } = 1471.875
The Volume of the given Hemisphere with radius { 12.5 } = 4088.5416666666665
Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Calculate the Surface Area and Volume of a Hemisphere Read More »

Program to Compute x^nn!

Python Program to Compute x^n/n!

In the previous article, we have discussed Python Program to Compute the Area and Perimeter of Pentagon
Factorial:

The product of all positive integers less than or equal to n is the factorial of a non-negative integer n, denoted by n! in mathematics:

n! = n * (n – 1) *(n – 2) * . . . . . . . . . . 3 * 2 * 1.

5 != 5* 4 * 3 * 2 *1= 120

Given the values of x, n and the task is to calculate the value of x^n/n!

Examples:

Example1:

Input:

Given Number = 3
Given x value =  6

Output:

The value of x^n/n! with the given n,x { 3 6 } values= 36.0

Example2:

Input:

Given Number = 5
Given x value = 8

Output:

The value of x^n/n! with the given n,x { 5 8 } values= 273.06666666666666

Program to Compute x^n/n! in Python

Below are the ways to calculate the value of x^n/n! :

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Give the value of x as static input and store it in another variable.
  • Take a variable, initialize it with the value ‘1’, and store it in another variable say ‘factorl‘.
  • Loop from 1 to the given number using the for loop.
  • Inside the loop, calculate the factorial of a given number by multiplying the value of the above variable “factorl” with the iterator value.
  • Store it in the same variable ‘factorl‘.
  • Calculate the value of x^n/n! using the pow() function and store it in another variable.
  • Print the value of  x^n/n! for the given n, x values.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_n_val = 3
# Give the value of x as static input and store it in another variable.
gvn_x_val = 6
# Take a variable, initialize it with the value '1', and store it in another variable say
# 'factorl'.
factorl = 1
# Loop from 1 to the given number using the for loop.
for itr in range(1, gvn_n_val+1):
    # Inside the loop, calculate the factorial of a given number by multiplying the value of
    # the above variable "factorl" with the iterator value.
    # Store it in the same variable 'factorl'.
    factorl *= itr
# Calculate the value of x^n/n! using the pow() function and store it in another variable.
fnl_reslt = pow(gvn_x_val, gvn_n_val)/factorl
# Print the value of  x^n/n! for the given n, x values.
print("The value of x^n/n! with the given n,x {",
      gvn_n_val, gvn_x_val, "} values=", fnl_reslt)

Output:

The value of x^n/n! with the given n,x { 3 6 } values= 36.0

Method #2: Using For loop (User Input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the value of x as user input using the int(input()) function and store it in another variable.
  • Take a variable, initialize it with the value ‘1’, and store it in another variable say ‘factorl‘.
  • Loop from 1 to the given number using the for loop.
  • Inside the loop, calculate the factorial of a given number by multiplying the value of the above variable “factorl” with the iterator value.
  • Store it in the same variable ‘factorl‘.
  • Calculate the value of x^n/n! using the pow() function and store it in another variable.
  • Print the value of  x^n/n! for the given n, x values.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function and 
# store it in a variable.
gvn_n_val = int(input("Enter some random Number= "))
# Give the value of x as user input using the int(input()) function and 
# store it in another variable.
gvn_x_val = int(input("Enter some random Number= "))
# Take a variable, initialize it with the value '1', and store it in another variable say
# 'factorl'.
factorl = 1
# Loop from 1 to the given number using the for loop.
for itr in range(1, gvn_n_val+1):
    # Inside the loop, calculate the factorial of a given number by multiplying the value of
    # the above variable "factorl" with the iterator value.
    # Store it in the same variable 'factorl'.
    factorl *= itr
# Calculate the value of x^n/n! using the pow() function and store it in another variable.
fnl_reslt = pow(gvn_x_val, gvn_n_val)/factorl
# Print the value of  x^n/n! for the given n, x values.
print("The value of x^n/n! with the given n,x {",
      gvn_n_val, gvn_x_val, "} values=", fnl_reslt)

Output:

Enter some random Number= 2
Enter some random Number= 10
The value of x^n/n! with the given n,x { 2 10 } values= 50.0

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Python Program to Compute x^n/n! Read More »

Semicolon in Python

Semicolon in Python | How & Why Python Semicolon is Used?

Let’s have a look at how the semicolon is used in Python. In different programming languages, the semicolon(;) signifies the end or termination of the current statement.

A semicolon is required to end a line of code in programming languages such as C, C++, and Java. Python, on the other hand, is not like that. So, does using semicolons in Python programming make a difference? Let’s have a look.

All About Python Semicolon

Explore more instances related to python concepts from Python Programming Examples Guide and get promoted from beginner to professional programmer level in Python Programming Language.

Why Python semicolons are allowed?

To terminate the statements, Python does not require semicolons. If you want to write a number of statements on the same line, Semicolons may be used to delimit statements.

In Python, a semicolon denotes separation instead of completion. It enables many statements to be written on the same line. It also makes it legal at the end of a single sentence to put a semicolon. In fact, it’s two statements that empty the second.

When to Use a Semi-colon?

The most commonly asked logical question here would be: Why are Semi-colons allowed in Python?

I believe that it was done to make a transition from other programming languages slightly easier. Programmers with a background in Java, C++, and PHP habitually put a (useless) terminator at the end of every line.

But, there are certain conditions where semicolons are helpful.

  • Running Scripts from Shell
  • Evaluating Expressions for Side Effects

Role of Semicolons in Python

  1. Python is known as a simple coding language as there is no need of using Semicolon and if we even forget to place, it doesn’t throw an error.
  2. In Python, a Semicolon is not used to denote the end of the line.
  3. Python doesn’t use Semicolons but it is not restricted.
  4. Sometimes Python makes use of Semicolon as a line terminator where it is used as a divider to separate multiple lines.

How to Print a Semi-Colon in Python?

A semi-colon in Python means separation, rather than termination. It lets you compose various statements on the same line. Let’s examine what happens to us when we attempt to print semi-colons.

Below is the implementation:

#printing the semi colon
print(";")

Output:

;

It just treats the semicolon as a string (having one character) in python.

Split Statements Using Semicolons

Now, let’s look at how we can separate declarations using semicolons into Python. In this situation, we are going to try to employ a semicolon with more than two statements on the same course.

Syntax:

statement1; statement2 ; statement3

Semicolon in Python

Example:

Let us take four statements without semicolons

# printing four statements without using the semicolon
print("Hello")
print("This")
print("is")
print("BTechGeeks")

Output:

Hello
This
is
BTechGeeks

Now, let us take the same four statements using semicolons:

# printing four statements with using the semicolon
print("Hello");print("This");print("is");print("BTechGeeks")

Output:

Hello
This
is
BTechGeeks

As you can see, after splitting them with semicolons, Python performs the four commands individually. The interpreter would give us an error without this use.

Using semicolons with loops in Python

A semicolon may be used in loops like ‘For loop,’ if the entire statement begins with a loop and a semi-colon is used for a cohesive statement like a loop body.

Below is the implementation:

for i in range(10):print("Hello");print("this");print("is BTechGeeks python");print("Online Platform")

Output:

Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform
Hello
this
is BTechGeeks python
Online Platform

If you use a semicolon to separate a normal expression from a block statement, such as a loop, Python will throw an error.

print('hello') ; for i in range (10): print ('BTechGeeks')

Output:

  File "/home/36390fc9b8b053533f2165af206c5441.py", line 1
    print('hello') ; for i in range (10): print ('BTechGeeks')
                       ^
SyntaxError: invalid syntax

Conclusion on Python Program to Use Semicolon at the end of the Sentence

This takes us to the end of this little module where we learn how to use a semicolon at the end of multiple statements on the Python program. Let’s sum up the tutorial with two reminders:

  • In Python, a semicolon is commonly used to separate numerous statements written on a single line. So, you can use the python semicolon in a statement on the same line and attain the output that you wish.
  • Semicolons are used to write tiny statements and conserve some space, such as name = Vikram; age = 20; print (name, age)

The usage of semicolons is quite “non-pythonic” and should be avoided until absolutely necessary. But, Multiple statements on a single line should be avoided.

Though the language specification permits for the use of a semicolon to separate statements, doing so without cause makes one’s code more difficult to comprehend.

Related Programs:

Semicolon in Python | How & Why Python Semicolon is Used? Read More »