Author name: Vikram Chiluka

Program to Print Even Numbers in Given Range Using Recursion

Python Program to Print Even Numbers in Given Range Using Recursion

In the previous article, we have discussed Python Program to Divide Two Numbers Using Recursion

Given the Lower and upper limits as range and the task is to print the even numbers in a given range.

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.

Examples:

Example1:

Input:

 Given Lower Limit = 30
 Given Upper Limit = 50

Output:

The Even numbers in a given range 30 and 50 are :
30 32 34 36 38 40 42 44 46 48 50

Example2:

Input:

Given Lower Limit = 60
Given Upper Limit = 100

Output:

The Even numbers in a given range 60 and 100 are :
60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100

Program to Print Even Numbers in Given Range Using Recursion in Python

Below are the ways to print the even numbers in a given range in python:

Method #1: Using Recursion (Static Input)

Approach:

  • Give the lower limit as static input and store it in a variable.
  • Give the upper limit as static input and store it in another variable.
  • Pass the given lower and upper limits as the arguments to the even_range function.
  • Create a recursive function to say even_range which takes the given lower and upper limits as arguments and returns the even numbers in a given range using recursion.
  • Check if the given lower limit value is greater than the upper limit using the if conditional statement.
  • If the statement is true, then return.
  • After the return statement, print the given lower limit separated by spaces.
  • Return even_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
  • Print the Even Numbers in a given lower and upper limit range.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say even_range which takes the given lower and upper
# limits as arguments and returns the even numbers in a given range using recursion.


def even_range(gvnlowr_lmt, gvnuppr_lmt):
    # Check if the given lower limit value is greater than the upper limit using the if
    # conditional statement.
    if gvnlowr_lmt > gvnuppr_lmt:
        # If the statement is true, then return.
        return
    # After the return statement, print the given lower limit separated by spaces.
    print(gvnlowr_lmt, end=" ")
    # Return even_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
    return even_range(gvnlowr_lmt+2, gvnuppr_lmt)


# Give the lower limit as static input and store it in a variable.
gvnlowr_lmt = 30
# Give the upper limit as static input and store it in another variable.
gvnuppr_lmt = 50
# Pass the given lower and upper limits as the arguments to even_range function.
# Print the even Numbers in a given range.
print("The Even numbers in a given range",
      gvnlowr_lmt, "and", gvnuppr_lmt, "are :")
even_range(gvnlowr_lmt, gvnuppr_lmt)

Output:

The Even numbers in a given range 30 and 50 are :
30 32 34 36 38 40 42 44 46 48 50

Method #2: Using Recursion (User Input)

Approach:

  • Give the lower limit as user input using the int(input()) function and store it in a variable.
  • Give the upper limit as user input using the int(input()) function and store it in another variable.
  • Pass the given lower and upper limits as the arguments to the even_range function.
  • Create a recursive function to say even_range which takes the given lower and upper limits as arguments and returns the even numbers in a given range using recursion.
  • Check if the given lower limit value is greater than the upper limit using the if conditional statement.
  • If the statement is true, then return.
  • After the return statement, print the given lower limit separated by spaces.
  • Return even_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
  • Print the Even Numbers in a given lower and upper limit range.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say even_range which takes the given lower and upper
# limits as arguments and returns the even numbers in a given range using recursion.


def even_range(gvnlowr_lmt, gvnuppr_lmt):
    # Check if the given lower limit value is greater than the upper limit using the if
    # conditional statement.
    if gvnlowr_lmt > gvnuppr_lmt:
        # If the statement is true, then return.
        return
    # After the return statement, print the given lower limit separated by spaces.
    print(gvnlowr_lmt, end=" ")
    # Return even_range(gvnlowr_lmt+2, gvnuppr_lmt) {Recursive Logic}.
    return even_range(gvnlowr_lmt+2, gvnuppr_lmt)


# Give the lower limit as user input using the int(input()) function
# and store it in a variable.
gvnlowr_lmt = int(input("Enter some random number = "))
# Give the upper limit as user input using the int(input()) function
# and store it in another variable.
gvnuppr_lmt = int(input("Enter some random number = "))
# Pass the given lower and upper limits as the arguments to even_range function.
# Print the even Numbers in a given range.
print("The Even numbers in a given range",
      gvnlowr_lmt, "and", gvnuppr_lmt, "are :")
even_range(gvnlowr_lmt, gvnuppr_lmt)

Output:

Enter some random number = 60
Enter some random number = 100
The Even numbers in a given range 60 and 100 are :
60 62 64 66 68 70 72 74 76 78 80 82 84 86 88 90 92 94 96 98 100

Remediate your knowledge gap by attempting the Python Code Examples regularly and understand the areas of need and work on them.

Python Program to Print Even Numbers in Given Range Using Recursion Read More »

Program to Multiply Two Numbers Using Recursion

Python Program to Multiply Two Numbers Using Recursion

In the previous article, we have discussed Python Program to Find Subtraction of Two Numbers using Recursion

Given two numbers and the task is to find the multiplication of the given two numbers using recursion.

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.

Examples:

Example1:

Input:

Given First Number      =  3
Given Second Number =  5

Output:

The Multiplication of { 3 * 5 } using recursion = 15

Example2:

Input:

Given First Number      = 6
Given Second Number = 9

Output:

The Multiplication of { 6 * 9 } using recursion = 54

Program to Multiply Two Numbers Using Recursion in Python

Below are the ways to find the multiplication of the given two numbers using recursion :

Method #1: Using Recursion (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Pass the given two numbers as the arguments to recur_mult function.
  • Create a recursive function to say recur_mult which takes the two numbers as arguments and returns the multiplication of the given two numbers using recursion.
  • Check if the first number is less than the second number using the if conditional statement.
  • If the statement is true, then return the second number, first number as arguments to the recur_mult.{Recursive logic}.
  • Check if the second number is not equal to 0 using the elif conditional statement.
  • If the statement is true, then return fst_numb + recur_mult(fst_numb, secnd_numb – 1) {Recursive Logic}.
  • Else return 0.
  • Print the multiplication of the given two numbers using recursion.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say recur_mult which takes the two numbers as arguments
# and returns the multiplication of the given two numbers using recursion.


def recur_mult(fst_numb, secnd_numb):
  # Check if the first number is less than the second number using the if conditional
  # statement.
    if fst_numb < secnd_numb:
        # If the statement is true, then return the second number, first number as arguments
        # to the recur_mult.{Recursive logic}.
        return recur_mult(secnd_numb, fst_numb)
    # Check if the second number is not equal to 0 using the elif conditional statement.
    elif secnd_numb != 0:
        # If the statement is true, then return fst_numb + recur_mult(fst_numb, secnd_numb - 1)
        # {Recursive Logic}.

        return fst_numb + recur_mult(fst_numb, secnd_numb - 1)
    else:
        # Else return 0.
        return 0


# Give the first number as static input and store it in a variable.
fst_numb = 5
# Give the second number as static input and store it in another variable.
secnd_numb = 3
# Pass the given two numbers as the arguments to recur_mult function.
# Print the multiplication of given two numbers using recursion.
print("The Multiplication of {", fst_numb, "*", secnd_numb,
      "} using recursion =", recur_mult(fst_numb, secnd_numb))

Output:

The Multiplication of { 5 * 3 } using recursion = 15

Method #2: Using Recursion (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Pass the given two numbers as the arguments to recur_mult function.
  • Create a recursive function to say recur_mult which takes the two numbers as arguments and returns the multiplication of the given two numbers using recursion.
  • Check if the first number is less than the second number using the if conditional statement.
  • If the statement is true, then return the second number, first number as arguments to the recur_mult.{Recursive logic}.
  • Check if the second number is not equal to 0 using the elif conditional statement.
  • If the statement is true, then return fst_numb + recur_mult(fst_numb, secnd_numb – 1) {Recursive Logic}.
  • Else return 0.
  • Print the multiplication of the given two numbers using recursion.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say recur_mult which takes the two numbers as arguments
# and returns the multiplication of the given two numbers using recursion.


def recur_mult(fst_numb, secnd_numb):
  # Check if the first number is less than the second number using the if conditional
  # statement.
    if fst_numb < secnd_numb:
        # If the statement is true, then return the second number, first number as arguments
        # to the recur_mult.{Recursive logic}.
        return recur_mult(secnd_numb, fst_numb)
    # Check if the second number is not equal to 0 using the elif conditional statement.
    elif secnd_numb != 0:
        # If the statement is true, then return fst_numb + recur_mult(fst_numb, secnd_numb - 1)
        # {Recursive Logic}.

        return fst_numb + recur_mult(fst_numb, secnd_numb - 1)
    else:
        # Else return 0.
        return 0


# Give the first number as user input using the int(input()) function and 
# store it in a variable.
fst_numb = int(input("Enter some random number = "))
#Give the second number as user input using the int(input()) function and 
# store it in another variable.
secnd_numb = int(input("Enter some random number = "))
# Pass the given two numbers as the arguments to recur_mult function.
# Print the multiplication of given two numbers using recursion.
print("The Multiplication of {", fst_numb, "*", secnd_numb,
      "} using recursion =", recur_mult(fst_numb, secnd_numb))

Output:

Enter some random number = 7
Enter some random number = 0
The Multiplication of { 7 * 0 } using recursion = 0

If you are learning Python then the Python Programming Example is for you and gives you a thorough description of concepts for beginners, experienced programmers.

Python Program to Multiply Two Numbers Using Recursion Read More »

Program to Find Subtraction of Two Numbers using Recursion

Python Program to Find Subtraction of Two Numbers using Recursion

In the previous article, we have discussed Python Program to Find Sum of Two Numbers using Recursion

Given two numbers and the task is to find the subtraction of the given two numbers using recursion.

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.

Examples:

Example1:

Input:

Given First Number      =  10
Given Second Number =   4

Output:

The subtraction of { 10 - 4 } using recursion = 6

Example2:

Input:

Given First Number      = 35
Given Second Number = 12

Output:

The subtraction of { 35 - 12 } using recursion = 23

Program to Find Subtraction of Two Numbers using Recursion in Python

Below are the ways to find the subtraction of the given two numbers using recursion :

Method #1: Using Recursion (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Pass the given two numbers as the arguments to recur_sub function
  • Create a recursive function to say recur_sub which takes the two numbers as arguments and returns the subtraction of the given two numbers using recursion.
  • Check if the second number is equal to 0 using the if conditional statement.
  • If the statement is true, return the first number.
  • Else return (fst_numb-1, secnd_numb-1) {Recursive logic}
  • Print the subtraction of given two numbers using recursion.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say recur_sub which takes the two numbers as arguments
# and returns the subtraction of the given two numbers using recursion.


def recur_sub(fst_numb, secnd_numb):
    # Check if the second number is equal to 0 using the if conditional statement.
    if secnd_numb == 0:
        # If the statement is true, return the first number.
        return fst_numb
    # Else return (fst_numb-1, secnd_numb-1) {Recursive logic}
    return recur_sub(fst_numb-1, secnd_numb-1)


# Give the first number as static input and store it in a variable.
fst_numb = 10
# Give the second number as static input and store it in another variable.
secnd_numb = 4
#Pass the given two numbers as the arguments to recur_sub function
# Print the subtraction of given two numbers using recursion.
print("The subtraction of {", fst_numb, "-", secnd_numb,
      "} using recursion =", recur_sub(fst_numb, secnd_numb))

Output:

The subtraction of { 10 - 4 } using recursion = 6

Method #2: Using Recursion (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Pass the given two numbers as the arguments to recur_sub function
  • Create a recursive function to say recur_sub which takes the two numbers as arguments and returns the subtraction of the given two numbers using recursion.
  • Check if the second number is equal to 0 using the if conditional statement.
  • If the statement is true, return the first number.
  • Else return (fst_numb-1, secnd_numb-1) {Recursive logic}
  • Print the subtraction of given two numbers using recursion.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say recur_sub which takes the two numbers as arguments
# and returns the subtraction of the given two numbers using recursion.


def recur_sub(fst_numb, secnd_numb):
    # Check if the second number is equal to 0 using the if conditional statement.
    if secnd_numb == 0:
        # If the statement is true, return the first number.
        return fst_numb
    # Else return (fst_numb-1, secnd_numb-1) {Recursive logic}
    return recur_sub(fst_numb-1, secnd_numb-1)


# Give the first number as user input using the int(input()) function and
# store it in a variable.
fst_numb = int(input("Enter some random number = "))
# Give the second number as user input using the int(input()) function and 
# store it in another variable.
secnd_numb = int(input("Enter some random number = "))
#Pass the given two numbers as the arguments to recur_sub function
# Print the subtraction of given two numbers using recursion.
print("The subtraction of {", fst_numb, "-", secnd_numb,
      "} using recursion =", recur_sub(fst_numb, secnd_numb))

Output:

Enter some random number = 35
Enter some random number = 10
The subtraction of { 35 - 10 } using recursion = 25

Grab the opportunity and utilize the Python Program Code Examples over here to prepare basic and advanced topics too with ease and clear all your doubts.

Python Program to Find Subtraction of Two Numbers using Recursion Read More »

Program to Find Sum of Two Numbers using Recursion

Python Program to Find Sum of Two Numbers using Recursion

In the previous article, we have discussed Python Program to Find the First Small Letter in a Given String

Given two numbers and the task is to find the sum of the given two numbers using recursion.

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.

Examples:

Example1:

Input:

Given First Number      =  3
Given Second Number =  0

Output:

The sum of { 3 } and { 0 } using recursion = 3

Example2:

Input:

Given First Number      = 20
Given Second Number = 30

Output:

The sum of { 20 } and { 30 } using recursion = 50

Program to Find Sum of Two Numbers using Recursion in Python

Below are the ways to find the sum of the given two numbers using recursion :

Method #1: Using Recursion (Static Input)

Approach:

  • Give the first number as static input and store it in a variable.
  • Give the second number as static input and store it in another variable.
  • Pass the given two numbers as the arguments to recur_sum function
  • Create a recursive function to say recur_sum which takes the two numbers as arguments and returns the sum of the given two numbers using recursion.
  • Check if the second number is equal to 0 using the if conditional statement.
  • If the statement is true, return the first number.
  • Else return (fst_numb, secnd_numb-1)+1 {Recursive logic}.
  • Print the sum of the given two numbers using recursion.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say recur_sum which takes the two numbers as arguments
# and returns the sum of the given two numbers using recursion.


def recur_sum(fst_numb, secnd_numb):
    # Check if the second number is equal to 0 using the if conditional statement.
    if secnd_numb == 0:
        # If the statement is true, return the first number.
        return fst_numb
    # Else return (fst_numb, secnd_numb-1)+1 {Recursive logic}
    return recur_sum(fst_numb, secnd_numb-1)+1


# Give the first number as static input and store it in a variable.
fst_numb = 3
# Give the second number as static input and store it in another variable.
secnd_numb = 0
#Pass the given two numbers as the arguments to recur_sum function
print("The sum of {", fst_numb, "} and {", secnd_numb,
      "} using recursion =", recur_sum(fst_numb, secnd_numb))

Output:

The sum of { 3 } and { 0 } using recursion = 3

Method #2: Using Recursion (User Input)

Approach:

  • Give the first number as user input using the int(input()) function and store it in a variable.
  • Give the second number as user input using the int(input()) function and store it in another variable.
  • Pass the given two numbers as the arguments to recur_sum function
  • Create a recursive function to say recur_sum which takes the two numbers as arguments and returns the sum of the given two numbers using recursion.
  • Check if the second number is equal to 0 using the if conditional statement.
  • If the statement is true, return the first number.
  • Else return (fst_numb, secnd_numb-1)+1 {Recursive logic}.
  • Print the sum of the given two numbers using recursion.
  • The Exit of the Program.

Below is the implementation:

# Create a recursive function to say recur_sum which takes the two numbers as arguments
# and returns the sum of the given two numbers using recursion.


def recur_sum(fst_numb, secnd_numb):
    # Check if the second number is equal to 0 using the if conditional statement.
    if secnd_numb == 0:
        # If the statement is true, return the first number.
        return fst_numb
    # Else return (fst_numb, secnd_numb-1)+1 {Recursive logic}
    return recur_sum(fst_numb, secnd_numb-1)+1


# Give the first number as user input using the int(input()) function and
# store it in a variable.
fst_numb = int(input("Enter some random number = "))
# Give the second number as user input using the int(input()) function and 
# store it in another variable.
secnd_numb = int(input("Enter some random number = "))
#Pass the given two numbers as the arguments to recur_sum function
print("The sum of {", fst_numb, "} and {", secnd_numb,
      "} using recursion =", recur_sum(fst_numb, secnd_numb))

Output:

Enter some random number = 20
Enter some random number = 30
The sum of { 20 } and { 30 } using recursion = 50

Practice Python Program Examples to master coding skills and learn the fundamental concepts in the dynamic programming language Python.

Python Program to Find Sum of Two Numbers using Recursion Read More »

Program to Find the First Small Letter in a Given String

Python Program to Find the First Small Letter in a Given String

In the previous article, we have discussed Python Program to Find the First Capital Letter in a Given String

Given a string and the task is to find the first small letter in a given string in python.

Examples:

Example1:

Input:

Given String = "GOOD morning Btechgeeks"

Output:

The given String's first small letter =  m

Example2:

Input:

Given String =  "hello this is btechgeeks"

Output:

The given String's first small letter =  h

Program to Find the First Small Letter in a Given String in Python

Below are the ways to find the first small letter in a given string in python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a new empty string and store it in another variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Loop till the length of the given string using the for loop.
  • Check if the character which is present at the iterator value of the given string is greater than or equal to ‘a’ and less than or equal to ‘z’ using the if conditional statement.
  • If the statement is true, then add the character which is present at the iterator value of the given string to the above-initialized new string.
  • Break the statement.
  • If the statement is false, then continue.
  • Print the given string’s first small letter.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gven_str = "GOOD morning Btechgeeks"
# Take a new empty string and store it in another variable.
fstsmall_lettr = ' '
# Calculate the length of the given string using the len() function and store it in
# another variable.
str_lengt = len(gven_str)
# Loop till the length of the given string using the for loop.
for itr in range(str_lengt):
   # Check if the character which is present at the iterator value of the given string
   # is greater than or equal to 'a' and less than or equal to 'z' using the if
   # conditional statement.
    if gven_str[itr] >= 'a' and gven_str[itr] <= 'z':
       # If the statement is true, then add the character which is present at the iterator
       # value of the given string to the above-initialized new string.
        fstsmall_lettr = gven_str[itr]
    # Break the statement.
        break
    else:
      # If the statement is false, then continue.
        continue
# Print the given string's first small letter.
print("The given String's first small letter = ", fstsmall_lettr)

Output:

The given String's first small letter =  m

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 a new empty string and store it in another variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Loop till the length of the given string using the for loop.
  • Check if the character which is present at the iterator value of the given string is greater than or equal to ‘a’ and less than or equal to ‘z’ using the if conditional statement.
  • If the statement is true, then add the character which is present at the iterator value of the given string to the above-initialized new string.
  • Break the statement.
  • If the statement is false, then continue.
  • Print the given string’s first small letter.
  • 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.
gven_str = input("Enter some Random String = ")
# Take a new empty string and store it in another variable.
fstsmall_lettr = ' '
# Calculate the length of the given string using the len() function and store it in
# another variable.
str_lengt = len(gven_str)
# Loop till the length of the given string using the for loop.
for itr in range(str_lengt):
   # Check if the character which is present at the iterator value of the given string
   # is greater than or equal to 'a' and less than or equal to 'z' using the if
   # conditional statement.
    if gven_str[itr] >= 'a' and gven_str[itr] <= 'z':
       # If the statement is true, then add the character which is present at the iterator
       # value of the given string to the above-initialized new string.
        fstsmall_lettr = gven_str[itr]
    # Break the statement.
        break
    else:
      # If the statement is false, then continue.
        continue
# Print the given string's first small letter.
print("The given String's first small letter = ", fstsmall_lettr)

Output:

Enter some Random String = hello this is btechgeeks
The given String's first small letter = h

If you wanna write simple python programs as a part of your coding practice refer to numerous Simple Python Program Examples existing and learn the approach used.

Python Program to Find the First Small Letter in a Given String Read More »

Program to Find the First Capital Letter in a Given String

Python Program to Find the First Capital Letter in a Given String

In the previous article, we have discussed Python Program to Convert Alternate Characters to Capital Letters

Given a string and the task is to find the first capital letter in a given string in python.

Examples:

Example1:

Input:

Given String = "hello this is Btechgeeks"

Output:

The given String's first capital letter =  B

Example2:

Input:

Given String = "good Morning Btechgeeks"

Output:

The given String's first capital letter =  M

Program to Find the First Capital Letter in a Given String in Python

Below are the ways to find the first capital letter in a given string in python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a new empty string and store it in another variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Loop till the length of the given string using the for loop.
  • Check if the character which is present at the iterator value of the given string is greater than or equal to ‘A’ and less than or equal to ‘Z’ using the if conditional statement.
  • If the statement is true, then add the character which is present at the iterator value of the given string to the above-initialized new string.
  • Break the statement.
  • If the statement is false, then continue.
  • Print the given string’s first capital letter.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gven_str = "hello this is Btechgeeks"
# Take a new empty string and store it in another variable.
fstcapitl_lettr = ' '
# Calculate the length of the given string using the len() function and store it in
# another variable.
str_lengt = len(gven_str)
# Loop till the length of the given string using the for loop.
for itr in range(str_lengt):
   # Check if the character which is present at the iterator value of the given string
   # is greater than or equal to 'A' and less than or equal to 'Z' using the if
   # conditional statement.
    if gven_str[itr] >= 'A' and gven_str[itr] <= 'Z':
       # If the statement is true, then add the character which is present at the iterator
       # value of the given string to the above-initialized new string.
        fstcapitl_lettr = gven_str[itr]
    # Break the statement.
        break
    else:
      # If the statement is false, then continue.
        continue
# Print the given string's first capital letter.
print("The given String's first capital letter = ", fstcapitl_lettr)

Output:

The given String's first capital letter =  B

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 a new empty string and store it in another variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Loop till the length of the given string using the for loop.
  • Check if the character which is present at the iterator value of the given string is greater than or equal to ‘A’ and less than or equal to ‘Z’ using the if conditional statement.
  • If the statement is true, then add the character which is present at the iterator value of the given string to the above-initialized new string.
  • Break the statement.
  • If the statement is false, then continue.
  • Print the given string’s first capital letter.
  • 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.
gven_str = input("Enter some Random String = ")
# Take a new empty string and store it in another variable.
fstcapitl_lettr = ' '
# Calculate the length of the given string using the len() function and store it in
# another variable.
str_lengt = len(gven_str)
# Loop till the length of the given string using the for loop.
for itr in range(str_lengt):
   # Check if the character which is present at the iterator value of the given string
   # is greater than or equal to 'A' and less than or equal to 'Z' using the if
   # conditional statement.
    if gven_str[itr] >= 'A' and gven_str[itr] <= 'Z':
       # If the statement is true, then add the character which is present at the iterator
       # value of the given string to the above-initialized new string.
        fstcapitl_lettr = gven_str[itr]
    # Break the statement.
        break
    else:
      # If the statement is false, then continue.
        continue
# Print the given string's first capital letter.
print("The given String's first capital letter = ", fstcapitl_lettr)

Output:

Enter some Random String = good Morning Btechgeeks
The given String's first capital letter = M

Find a comprehensive collection of Examples of Python Programs ranging from simple ones to complex ones to guide you throughout your coding journey.

Python Program to Find the First Capital Letter in a Given String Read More »

Program to Convert Alternate Characters to Capital Letters

Python Program to Convert Alternate Characters to Capital Letters

In the previous article, we have discussed Python Program to Check Two Matrix are Equal or Not

Given a string, and the task is to convert the alternate characters to capital letters for a given string in python

Examples:

Example1:

Input:

Given String = "good morning btechgeeks"

Output:

The given string after converting alternate characters into capital letters :
GoOd MoRnInG bTeChGeEkS

Example2:

Input:

Given String = "hello this is btechgeeks"

Output:

The given string after converting alternate characters into capital letters :
HeLlO tHiS iS bTeChGeEkS

Program to Convert Alternate Characters to Capital Letters in Python

Below are the ways to convert the alternate characters to capital letters for a given string in python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the string as static input and store it in a variable.
  • Take a variable say k and initialize its value to zero.
  • Take a new empty string and store it in another variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Loop till the length of the given string using the for loop.
  • Check if the above-initialized k value modulus 2 is equal to zero using the if conditional statement.
  • If the Statement is true, Check if the character which is present at the iterator value of the given string is greater than or equal to ‘A’ and less than or equal to ‘Z’ using the if conditional statement.
  • If it is true, calculate the ASCII value of the character of the given string which is present at the iterator value index using the ord() function, and add 32 to it.
  • Find the character of the above ASCII value using the chr() function.
  • Concatenate the above character to the modified string.
  • If the statement is False, then concatenate the character which is present at the iterator value of the given string to the modified string.
  • Else, check if the character which is present at the iterator value is greater than or equal to ‘a’ and less than or equal to ‘z’ using the if conditional statement.
  • If it is true, calculate the ASCII value of the character of the given string which is present at the iterator value index using the ord() function, and subtract 32 from it.
  • Find the character of the above ASCII value using the chr() function.
  • Concatenate the above character to the modified string.
  • If the statement is False, then concatenate the character which is present at the iterator value of the given string to the modified string.
  • Check if the character present at the iterator value is equal to space using the if conditional statement.
  • If it is true, then continue.
  • Increment the value of k by 1 and store it in the same variable k.
  • Print the modified string to get the given string after converting alternate characters into capital letters.
  • The Exit of the Program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gven_str = "good morning btechgeeks"
# Take a variable say k and initialize its value to zero.
k = 0
# Take a new empty string and store it in another variable.
modified_strng = ""
# Calculate the length of the given string using the len() function and store it in
# another variable.
str_lengt = len(gven_str)
# Loop till the length of the given string using the for loop.
for itr in range(str_lengt):
     # Check if the above-initialized k value modulus 2 is equal to zero using the if
     # conditional statement.
    if k % 2 == 1:
      # If the Statement is true, Check if the character which is present at the iterator
      # value of the given string is greater than or equal to 'A' and less than or equal to 'Z' using the
      # if conditional statement.
        if gven_str[itr] >= 'A' and gven_str[itr] <= 'Z':
           # If it is true, calculate the ASCII value of the character of the given string which is
           # present at the iterator value index using the ord() function, and add 32 to it
           # Find the character of the above ASCII value using the chr() function.
            charctr = chr(ord(gven_str[itr])+32)
    # Concatenate the above character to the modified string.
            modified_strng = modified_strng+charctr
        else:
           # If the statement is False, then concatenate the character which is present at the
           # iterator value of the given string to the modified string.
            modified_strng = modified_strng+gven_str[itr]
    else:
      # Else, check if the character which is present at the iterator value of the given string is greater
      # than or equal to 'a' and less than or equal to 'z' using the if conditional statement.
        if gven_str[itr] >= 'a' and gven_str[itr] <= 'z':
          # If it is true, calculate the ASCII value of the character of the given string which
          # is present at the iterator value index using the ord() function, and subtract
          # 32 from it.
          # Find the character of the above ASCII value using the chr() function.
            charctr = chr(ord(gven_str[itr])-32)
          # Concatenate the above character to the modified string.
            modified_strng = modified_strng+charctr
        else:
         # If the statement is False, then concatenate the character which is present at the
         # iterator value of the given string to the modified string.
            modified_strng = modified_strng+gven_str[itr]
   # Check if the character present at the iterator value is equal to space using the if
   # conditional statement.

    if gven_str[itr] == ' ':
      # If it is true, then continue.
        continue
    # Increment the value of k by 1 and store it in the same variable k.
    k = k+1
# Print the modified string to get the given string after converting alternate characters
# into capital letters.
print("The given string after converting alternate characters into capital letters :")
print(modified_strng)

Output:

The given string after converting alternate characters into capital letters :
GoOd MoRnInG bTeChGeEkS

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 a variable say k and initialize its value to zero.
  • Take a new empty string and store it in another variable.
  • Calculate the length of the given string using the len() function and store it in another variable.
  • Loop till the length of the given string using the for loop.
  • Check if the above-initialized k value modulus 2 is equal to zero using the if conditional statement.
  • If the Statement is true, Check if the character which is present at the iterator value is greater than or equal to ‘A’ and less than or equal to ‘Z’ using the if conditional statement.
  • If it is true, calculate the ASCII value of the character of the given string which is present at the iterator value index using the ord() function, and add 32 to it.
  • Find the character of the above ASCII value using the chr() function.
  • Concatenate the above character to the modified string.
  • If the statement is False, then concatenate the character which is present at the iterator value of the given string to the modified string.
  • Else, check if the character which is present at the iterator value is greater than or equal to ‘a’ and less than or equal to ‘z’ using the if conditional statement.
  • If it is true, calculate the ASCII value of the character of the given string which is present at the iterator value index using the ord() function, and subtract 32 from it.
  • Find the character of the above ASCII value using the chr() function.
  • Concatenate the above character to the modified string.
  • If the statement is False, then concatenate the character which is present at the iterator value of the given string to the modified string.
  • Check if the character present at the iterator value is equal to space using the if conditional statement.
  • If it is true, then continue.
  • Increment the value of k by 1 and store it in the same variable k.
  • Print the modified string to get the given string after converting alternate characters into capital letters.
  • 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.
gven_str = input("Enter some Random String = ")
# Take a variable say k and initialize its value to zero.
k = 0
# Take a new empty string and store it in another variable.
modified_strng = ""
# Calculate the length of the given string using the len() function and store it in
# another variable.
str_lengt = len(gven_str)
# Loop till the length of the given string using the for loop.
for itr in range(str_lengt):
     # Check if the above-initialized k value modulus 2 is equal to zero using the if
     # conditional statement.
    if k % 2 == 1:
      # If the Statement is true, Check if the character which is present at the iterator
      # value of the given string is greater than or equal to 'A' and less than or equal to 'Z' 
      # using the if conditional statement.
        if gven_str[itr] >= 'A' and gven_str[itr] <= 'Z':
           # If it is true, calculate the ASCII value of the character of the given string which is
           # present at the iterator value index using the ord() function, and add 32 to it
           # Find the character of the above ASCII value using the chr() function.
            charctr = chr(ord(gven_str[itr])+32)
    # Concatenate the above character to the modified string.
            modified_strng = modified_strng+charctr
        else:
           # If the statement is False, then concatenate the character which is present at the
           # iterator value of the given string to the modified string.
            modified_strng = modified_strng+gven_str[itr]
    else:
      # Else, check if the character which is present at the iterator value of the given string 
      # is greater than or equal to 'a' and less than or equal to 'z' using the if
      # conditional statement.
        if gven_str[itr] >= 'a' and gven_str[itr] <= 'z':
          # If it is true, calculate the ASCII value of the character of the given string which
          # is present at the iterator value index using the ord() function, and subtract
          # 32 from it.
          # Find the character of the above ASCII value using the chr() function.
            charctr = chr(ord(gven_str[itr])-32)
  # Concatenate the above character to the modified string.
            modified_strng = modified_strng+charctr
        else:
         # If the statement is False, then concatenate the character which is present at the
         # iterator value of the given string to the modified string.
            modified_strng = modified_strng+gven_str[itr]
   # Check if the character present at the iterator value is equal to space using the if
   # conditional statement.

    if gven_str[itr] == ' ':
      # If it is true, then continue.
        continue
    # Increment the value of k by 1 and store it in the same variable k.
    k = k+1
# Print the modified string to get the given string after converting alternate characters
# into capital letters.
print("The given string after converting alternate characters into capital letters :")
print(modified_strng)

Output:

Enter some Random String = hello this is btechgeeks
The given string after converting alternate characters into capital letters :
HeLlO tHiS iS bTeChGeEkS

Find the best practical and ready-to-use Python Programming Examples that you can simply run on a variety of platforms and never stop learning.

Python Program to Convert Alternate Characters to Capital Letters Read More »

Program to Check Two Matrix are Equal or Not

Python Program to Check Two Matrix are Equal or Not

In the previous article, we have discussed Python Program to Check Whether a Matrix is a Scalar or Not

Given two matrixes and the task is to check if the given two matrixes are equal or not in Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Examples:

Example1:

Input:

Given first matrix :
5 2 0
0 5 0
0 0 5
Given second matrix :
5 2 0
0 5 0
0 0 5

Output:

The given first and second matrixes are equal.

Example2:

Input:

Given first matrix :
3 5
4 6
Given second matrix :
1 2
4 6

Output:

The given first and second matrixes are not equal.

Program to Check Two Matrix are Equal or Not in Python

Below are the ways to check if the given two matrixes are equal or not in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the first matrix as static input and store it in a variable.
  • Calculate the number of rows of the given first matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given first matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Give the second matrix as static input and store it in a variable.
  • Take a variable say tempo and initialize its value to zero.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition firstmatrix[n][m] is not equal to the secondmatrix[n][m] using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then make the value of tempo as 1.
  • Break the statement and exit the loop.
  • Check if the value of tempo is equal to 1 using the if conditional statement.
  • If the statement is true, then print “The given first and second matrixes are not equal.”
  • Else print “The given first and second matrixes are equal.”
  • The Exit of the Program.

Below is the implementation:

# Give the first matrix as static input and store it in a variable.
fst_mtrx = [[5, 2, 0], [0, 5, 0], [0, 0, 5]]
# Calculate the number of rows of the given first matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(fst_mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(fst_mtrx[0])
# Give the second matrix as static input and store it in a variable.
scnd_mtrx = [[5, 2, 0], [0, 5, 0], [0, 0, 5]]
# Take a variable say tempo and initialize its value to zero.
tempo = 0
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the condition firstmatrix[n][m] is not equal to the secondmatrix[n][m] using
        # the if conditional statement where n is the iterator value of the parent For loop
        # and m is the iterator value of the inner For loop.
        if fst_mtrx[n][m] != scnd_mtrx[n][m]:
            # If the statement is true, then make the value of tempo as 1.
            tempo = 1
        # Break the statement and exit the loop.
            break
# Check if the value of tempo is equal to 1 using the if conditional statement.              break
if tempo == 1:
  # If the statement is true, then print "The given first and second matrixes are not equal."
    print("The given first and second matrixes are not equal.")
else:
  # Else print "The given first and second matrixes are equal."
    print("The given first and second matrixes are equal.")

Output:

The given first and second matrixes are equal.

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Repeat the same for the second matrix.
  • Take a variable say tempo and initialize its value to zero.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition firstmatrix[n][m] is not equal to the secondmatrix[n][m] using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then make the value of tempo as 1.
  • Break the statement and exit the loop.
  • Check if the value of tempo is equal to 1 using the if conditional statement.
  • If the statement is true, then print “The given first and second matrixes are not equal.”
  • Else print “The given first and second matrixes are equal.”
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
fst_mtrx = []
print("Enter elements of the first matrix :")
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    fst_mtrx.append(l)
scnd_mtrx = []
print("Enter elements of the second matrix :")
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    scnd_mtrx.append(l)
    
# Take a variable say tempo and initialize its value to zero.
tempo = 0
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the condition firstmatrix[n][m] is not equal to the secondmatrix[n][m] using
        # the if conditional statement where n is the iterator value of the parent For loop
        # and m is the iterator value of the inner For loop.
        if fst_mtrx[n][m] != scnd_mtrx[n][m]:
            # If the statement is true, then make the value of tempo as 1.
            tempo = 1
        # Break the statement and exit the loop.
            break
# Check if the value of tempo is equal to 1 using the if conditional statement.              break
if tempo == 1:
  # If the statement is true, then print "The given first and second matrixes are not equal."
    print("The given first and second matrixes are not equal.")
else:
  # Else print "The given first and second matrixes are equal."
    print("The given first and second matrixes are equal.")

    

Output:

Enter some random number of rows of the matrix = 2
Enter some random number of columns of the matrix = 2
Enter elements of the first matrix :
Enter {2} elements of row {1} separated by spaces = 3 5
Enter {2} elements of row {2} separated by spaces = 4 6
Enter elements of the second matrix :
Enter {2} elements of row {1} separated by spaces = 1 2
Enter {2} elements of row {2} separated by spaces = 4 6
The given first and second matrixes are not equal.

Access the big list of Python Programming Code Examples with actual logical code asked in Programming and Coding Interviews for Python and stand out from the crowd.

Python Program to Check Two Matrix are Equal or Not Read More »

Program to Check Whether a Matrix is a Scalar or Not

Python Program to Check Whether a Matrix is a Scalar or Not

In the previous article, we have discussed Python Program to Find the Sum of a Lower Triangular Matrix

Given a matrix and the task is to check if the given matrix is a scalar matrix or not in Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Scalar Matrix :

A scalar matrix is a square matrix with all of its primary diagonal members equal and all off-diagonal elements equal. It’s an identity matrix’s multiplicative constant.

Examples:

Example1:

Input:

Given Matrix :
5 0 0
0 5 0
0 0 5

Output:

The Matrix given is a Scalar Matrix.

Example2:

Input:

Given Matrix :
0 8
2 5

Output:

The Matrix given is not a Scalar Matrix.

Program to Check Whether a Matrix is a Scalar or Not in Python

Below are the ways to check if the given matrix is a scalar matrix or not in Python:

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Take a variable say tempo and initialize its value to zero.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is not equal to m and gvnmatrix[n][m] not equal to 0 using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then make the value of tempo as 1.
  • Break the statement.
  • Check if the condition n is equal to m and gvnmatrix[n][m] not equal to gvnmatrix[n][m] using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then make the value of tempo as 1.
  • Break the statement and come out of the loop.
  • Check if the value of tempo is equal to 1 using the if conditional statement.
  • If the statement is true, then print “The Matrix given is not a Scalar Matrix.”
  • Else print “The Matrix given is a Scalar Matrix.”
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[5, 0, 0], [0, 5, 0], [0, 0, 5]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
# Take a variable and initialize its value to zero.
tempo = 0
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the condition n is not equal to m and gvnmatrix[n][m] not equal to 0 using the
        # if conditional statement where n is the iterator value of the parent For loop and m
        # is the iterator value of the inner For loop.
        if n != m and mtrx[n][m] != 0:
         # If the statement is true, then make the value of tempo as 1.
            tempo = 1
           # Break the statement.
            break
      # Check if the condition n is equal to m and gvnmatrix[n][m] not equal to gvnmatrix[n][m]
      # using the if conditional statement where n is the iterator value of the parent For loop
      # and m is the iterator value of the inner For loop.
        if n == m and mtrx[n][m] != mtrx[n][m]:
          # If the statement is true, then make the value of tempo as 1.
            tempo = 1
           # Break the statement.
            break
# Check if the value of tempo is equal to 1 using the if conditional statement.
if tempo == 1:
  # If the statement is true, then print "The Matrix given is not a Scalar Matrix."
    print("The Matrix given is not a Scalar Matrix.")
else:
  # Else print "The Matrix given is a Scalar Matrix."
    print("The Matrix given is a Scalar Matrix.")

Output:

The Matrix given is a Scalar Matrix.

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Take a variable say tempo and initialize its value to zero.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is not equal to m and gvnmatrix[n][m] not equal to 0 using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then make the value of tempo as 1.
  • Break the statement.
  • Check if the condition n is equal to m and gvnmatrix[n][m] not equal to gvnmatrix[n][m] using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, then make the value of tempo as 1.
  • Break the statement and come out of the loop.
  • Check if the value of tempo is equal to 1 using the if conditional statement.
  • If the statement is true, then print “The Matrix given is not a Scalar Matrix.”
  • Else print “The Matrix given is a Scalar Matrix.”
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
    
# Take a variable and initialize its value to zero.
tempo = 0
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
        # Check if the condition n is not equal to m and gvnmatrix[n][m] not equal to 0 using the
        # if conditional statement where n is the iterator value of the parent For loop and m
        # is the iterator value of the inner For loop.
        if n != m and mtrx[n][m] != 0:
         # If the statement is true, then make the value of tempo as 1.
            tempo = 1
           # Break the statement.
            break
      # Check if the condition n is equal to m and gvnmatrix[n][m] not equal to gvnmatrix[n][m]
      # using the if conditional statement where n is the iterator value of the parent For loop
      # and m is the iterator value of the inner For loop.
        if n == m and mtrx[n][m] != mtrx[n][m]:
          # If the statement is true, then make the value of tempo as 1.
            tempo = 1
           # Break the statement.
            break
# Check if the value of tempo is equal to 1 using the if conditional statement.
if tempo == 1:
  # If the statement is true, then print "The Matrix given is not a Scalar Matrix."
    print("The Matrix given is not a Scalar Matrix.")
else:
  # Else print "The Matrix given is a Scalar Matrix."
    print("The Matrix given is a Scalar Matrix.")

Output:

Enter some random number of rows of the matrix = 2
Enter some random number of columns of the matrix = 2
Enter {2} elements of row {1} separated by spaces = 0 8
Enter {2} elements of row {2} separated by spaces = 2 5
The Matrix given is not a Scalar Matrix.

The best way to learn Python for Beginners is to practice as much as they can taking help of the Sample Python Programs For Beginners. Using them you can develop code on your own and master coding skills.

Python Program to Check Whether a Matrix is a Scalar or Not Read More »

Program to Find the Sum of a Lower Triangular Matrix

Python Program to Find the Sum of a Lower Triangular Matrix

In the previous article, we have discussed Python Program to Find the Sum of an Upper Triangular Matrix

Given a matrix and the task is to find the sum of the lower triangular matrix of the given matrix in Python.

What is a matrix:

A matrix is a rectangular sequence of numbers divided into columns and rows. A matrix element or entry is a number that appears in a matrix.

Example:

Above is the matrix which contains 5 rows and 4 columns and having elements from 1 to 20.

In this order, the dimensions of a matrix indicate the number of rows and columns.

Here as there are 5 rows and 4 columns it is called a 5*4 matrix.

Lower Triangular Matrix:

A lower triangular matrix is one that has all of its upper triangular elements equal to zero. In other words, all non-zero elements are on the main diagonal or in the lower triangle.

Examples:

Example1:

Input:

Given Matix :
1 6 4 
8 1 3
1 6 2

Output:

The sum of Lower Triangular matrix of the given matrix is :
13

Example2:

Input:

Given Matix :
7 9 
3 6

Output:

The sum of Lower Triangular matrix of the given matrix is :
9

Program to Find the Sum of a Lower Triangular Matrix in Python

Below are the ways to find the sum of the lower triangular matrix of the given matrix in Python.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the matrix as static input and store it in a variable.
  • Calculate the number of rows of the given matrix by calculating the length of the nested list using the len() function and store it in a variable mtrxrows.
  • Calculate the number of columns of the given matrix by calculating the length of the first list in the nested list using the len() function and store it in a variable mtrxcolums.
  • Take a variable say lower_sum and initialize its value to 0.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is less than m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, add the gvnmatrix[n][m] to the above-initialized lower_sum and store it in the same variable lower_sum.
  • Print the variable lower_sum to get the sum of the lower triangular matrix of the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the matrix as static input and store it in a variable.
mtrx = [[1, 6, 4], [8, 1, 3], [1, 6, 2]]
# Calculate the number of rows of the given matrix by
# calculating the length of the nested list using the len() function
# and store it in a variable mtrxrows.
mtrxrows = len(mtrx)
# Calculate the number of columns of the given matrix by
# calculating the length of the first list in the nested list
# using the len() function and store it in a variable mtrxcols.
mtrxcols = len(mtrx[0])
print("The sum of Lower Triangular matrix of the given matrix is :")
# Take a variable say lower_sum and initialize its value to 0.
lower_sum = 0
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is less than m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n < m:
          # If the statement is true, add the gvnmatrix[n][m] to the above-initialized
          # lower_sum and store it in the same variable lower_sum.
            lower_sum += mtrx[n][m]
# Print the variable lower_sum to get the sum of the lower triangular matrix of the
# given matrix.
print(lower_sum)

Output:

The sum of Lower Triangular matrix of the given matrix is :
13

Method #2: Using For loop (User Input)

Approach:

  • Give the number of rows of the matrix as user input using the int(input()) function and store it in a variable.
  • Give the number of columns of the matrix as user input using the int(input()) function and store it in another variable.
  • Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
  • Loop till the given number of rows using the For loop
  • Inside the For loop, Give all the row elements of the given Matrix as a list using the list(),map(),int(),split() functions and store it in a variable.
  • Add the above row elements list to gvnmatrix using the append() function.
  • Take a variable say lower_sum and initialize its value to 0.
  • Loop till the given number of rows using the For loop.
  • Inside the For loop, Iterate till the given number of columns using another Nested For loop(Inner For loop).
  • Check if the condition n is less than m using the if conditional statement where n is the iterator value of the parent For loop and m is the iterator value of the inner For loop.
  • If the statement is true, add the gvnmatrix[n][m] to the above-initialized lower_sum and store it in the same variable lower_sum.
  • Print the variable lower_sum to get the sum of the lower triangular matrix of the given matrix.
  • The Exit of the Program.

Below is the implementation:

# Give the number of rows of the matrix as user input using the int(input()) function
# and store it in a variable.
mtrxrows = int(input('Enter some random number of rows of the matrix = '))
# Give the number of columns of the matrix as user input using the int(input()) function
# and store it in another variable.
mtrxcols = int(input('Enter some random number of columns of the matrix = '))
# Take a list and initialize it with an empty value using [] or list() to say gvnmatrix.
mtrx = []
# Loop till the given number of rows using the For loop
for n in range(mtrxrows):
    # Inside the For loop, Give all the row elements of the given Matrix as a list using
    # the list(),map(),int(),split() functions and store it in a variable.
    l = list(map(int, input(
        'Enter {'+str(mtrxcols)+'} elements of row {'+str(n+1)+'} separated by spaces = ').split()))
    # Add the above row elements list to gvnmatrix using the append() function.

    mtrx.append(l)
    
print("The sum of Lower Triangular matrix of the given matrix is :")
# Take a variable say lower_sum and initialize its value to 0.
lower_sum = 0
# To print all the elements of the given matrix.
# Loop till the given number of rows using the For loop.
for n in range(mtrxrows):
        # Inside the For loop, Iterate till the given number of columns using another
        # Nested For loop(Inner For loop).
    for m in range(mtrxcols):
      # Check if the condition n is less than m using the if conditional statement where n
      # is the iterator value of the parent For loop and m is the iterator value of the
      # inner For loop.
        if n < m:
          # If the statement is true, add the gvnmatrix[n][m] to the above-initialized
          # lower_sum and store it in the same variable lower_sum.
            lower_sum += mtrx[n][m]
# Print the variable lower_sum to get the sum of the lower triangular matrix of the
# given matrix.
print(lower_sum)

Output:

Enter some random number of rows of the matrix = 2
Enter some random number of columns of the matrix = 2
Enter {2} elements of row {1} separated by spaces = 7 9
Enter {2} elements of row {2} separated by spaces = 3 6
The sum of Lower Triangular matrix of the given matrix is :
9

Enhance your coding skills with our list of Python Basic Programs provided and become a pro in the general-purpose programming language Python in no time.

 

Python Program to Find the Sum of a Lower Triangular Matrix Read More »