Author name: Vikram Chiluka

Program to Take in the Marks of 5 Subjects and Display the Grade

Python Program to Take in the Marks of 5 Subjects and Display the Grade

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Given the marks of 5 subjects of the student, the task is to display the grade of the student based on the marks in

Python.

Examples:

Example1:

Input:

Enter first subject marks as integer = 75
Enter second subject marks as integer = 79
Enter third subject marks as integer = 65
Enter fourth subject marks as integer = 82
Enter fifth subject marks as integer = 63

Output:

Average of 5 marks = 72.8 Grade =C

Example2:

Input:

Enter first subject marks as integer = 63
Enter second subject marks as integer = 19
Enter third subject marks as integer = 99
Enter fourth subject marks as integer = 85
Enter fifth subject marks as integer = 73

Output:

Average of 5 marks = 67.8 Grade =D

Program to Take in the Marks of 5 Subjects and Display the Grade in Python

There are several ways to calculate the grade of the student based on the marks of 5 subjects in Python some of them are:

Method #1:Using IF..elif..else Statements(Static Input)

Approach:

  • Give the 5 subject marks as static input and store them in 5 variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as static input and store them in 5 variables.
marks1 = 95
marks2 = 85
marks3 = 89
marks4 = 93
marks5 = 87
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Average of 5 marks = 89.8 Grade =B

Explanation:

  • The user must enter 5 different values as static input and store them in different variables.
  • Then add together all five marks and divide by five to get the average.
  • If the average is more than 90, the grade is displayed as “A.”
  • If the average is between 80 and 90, the letter “B” is printed.
  • If the average is between 70 and 80, the letter “C” is printed.
  • If the average is between 60 and 70, the letter “D” is printed.
  • If the average falls below 60, the letter “F” is printed.

Method #2:Using IF..elif..else Statements (User Input separated by newline)

Approach:

  • Give the 5 subject marks as user input using int(input()) which converts the string to an integer.
  • Store them in 5 separate variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as user input using int(input()) which converts the string to an integer.
# Store them in 5 separate variables.
marks1 = int(input('Enter first subject marks as integer = '))
marks2 = int(input('Enter second subject marks as integer = '))
marks3 = int(input('Enter third subject marks as integer = '))
marks4 = int(input('Enter fourth subject marks as integer = '))
marks5 = int(input('Enter fifth subject marks as integer = '))
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Enter first subject marks as integer = 75
Enter second subject marks as integer = 79
Enter third subject marks as integer = 65
Enter fourth subject marks as integer = 82
Enter fifth subject marks as integer = 63
Average of 5 marks = 72.8 Grade =C

Method #3:Using IF..elif..else Statements and map(),split() functions (User Input separated by spaces)

Approach:

  • Give the 5 subject marks as user input separated by spaces using map(), split() functions.
  • Store them in 5 separate variables.
  • Calculate the sum of the 5 subject marks and store it in a variable.
  • Divide the sum by 5 to get the average of all the given marks.
  • To determine the grade based on the average of the marks, use an if…Elif..else conditions.
  • Print the grade.
  • The Exit of the Program.

Below is the implementation:

# Give the 5 subject marks as user input separated by spaces using map(), split() functions.
# Store them in 5 separate variables.
marks1, marks2, marks3, marks4, marks5 = map(int, input(
    'Enter 5 subject marks separated by spaces = ').split())
# Calculate the sum of the 5 subject marks and store it in a variable.
summarks = marks1+marks2+marks3+marks4+marks5
# Divide the sum of marks by 5 to get the average of all the given marks.
avgmark = summarks/5
# To determine the grade based on the average of the marks, use an if...Elif..else conditions.
if(avgmark >= 90):
    print("Average of 5 marks =", avgmark, 'Grade =A')
elif(avgmark >= 80 and avgmark < 90):
    print("Average of 5 marks =", avgmark, 'Grade =B')
elif(avgmark >= 70 and avgmark < 80):
    print("Average of 5 marks =", avgmark, 'Grade =C')
elif(avgmark >= 60 and avgmark < 70):
    print("Average of 5 marks =", avgmark, 'Grade =D')
else:
    print("Average of 5 marks =", avgmark, 'Grade =E')

Output:

Enter 5 subject marks separated by spaces = 45 96 78 99 92
Average of 5 marks = 82.0 Grade =B

Related Programs:

Python Program to Take in the Marks of 5 Subjects and Display the Grade Read More »

Program for Exponential Squaring (Fast Modulo Multiplication)

Python Program for Exponential Squaring (Fast Modulo Multiplication)

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Given two numbers base value and the exponential value, the task is to find the power of base and exponent modular 10^9+7

Examples:

Example1:

Input:

Given base value =  5
Given exponent value = 3

Output:

The value of the power of base and exponent modular 10^9+7 =  125

Example2:

Input:

Given base value =  3
Given exponent value = 10000

Output:

The value of the power of base and exponent modular 10^9+7 =  895629451

Program for Exponential Squaring (Fast Modulo Multiplication) in Python

Below are the ways to find the power of base and exponent modular 10^9+7 for the given base and exponential values:

Method #1: Using While Loop (Static Input)

Approach:

  • Give the base value as static input and store it in a variable.
  • Give the exponential value as static input and store it in another variable.
  • Pass the given base and exponential values as the arguments to the exponentl_squaring() function and store it in a variable.
  • Take a variable to say numb and initialize its value with 1000000007(10^9+7).
  • Create a function to say exponentl_squaring() which takes the given two base and exponential values as the arguments and returns the value of the power of base and exponent modular 10^9+7.
  • Inside the function, take a variable say p, and initialize its value to 1.
  • Loop until the given exponential value is greater than 0 using the while loop.
  • Check if the given exponential value is odd using the if conditional statement.
  • If it is true, multiply p with the given base value and store it in another variable.
  • Calculate the value of the above result modulus numb(10^9+7) and store it in the same variable p.
  • Multiply the given base value with itself and apply the modulus operator with 10^9+7(numb).
  • Store it in the same variable given base value.
  • Divide the given exponential value by 2 and convert it to an integer using the int() function.
  • Store it in the same variable given exponential value.
  • Return the value of p modulus 10^9+7.
  • Print the value of the power of base and exponent modular 10^9+7.
  • The Exit of the Program.

Below is the implementation:

# Take a variable to say numb and initialize its value with 1000000007(10^9+7).
numb = 1000000007

# Create a function to say exponentl_squaring() which takes the given two base and
# exponential values as the arguments and returns the value of the power of base and
# exponent modular 10^9+7.


def exponentl_squaring(gvn_baseval, gvn_exponentlval):
  # Inside the function, take a variable say p, and initialize its value to 1.
    p = 1
    # Loop until the given exponential value is greater than 0 using the while loop.
    while(gvn_exponentlval > 0):
           # Check if the given exponential value is odd using the if conditional statement.
        if (gvn_exponentlval % 2 != 0):
            # If it is true, multiply p with the given base value and store it in another
            # variable.
            k = p * gvn_baseval
            # Calculate the value of the above result modulus numb(10^9+7) and store it in the
            # same variable p.
            p = k % numb
      # Multiply the given base value with itself and apply the modulus operator with
      # 10^9+7(numb).
      # Store it in the same variable given base value.
        gvn_baseval = (gvn_baseval * gvn_baseval) % numb
        # Divide the given exponential value by 2 and convert it to an integer using the
        # int() function.
        # Store it in the same variable given exponential value.
        gvn_exponentlval = int(gvn_exponentlval / 2)
   # Return the value of p modulus 10^9+7.
    return p % numb


# Give the base value as static input and store it in a variable.
gvn_baseval = 5
# Give the exponential value as static input and store it in another variable.
gvn_exponentlval = 3
# Pass the given base and exponential values as the arguments to the exponentl_squaring()
# function and store it in a variable.
rslt = exponentl_squaring(gvn_baseval, gvn_exponentlval)
# Print the value of the power of base and exponent modular 10^9+7.
print("The value of the power of base and exponent modular 10^9+7 = ", rslt)

Output:

The value of the power of base and exponent modular 10^9+7 =  125

Method #2: Using While loop (User Input)

Approach:

  • Give the base value as user input using the int(input()) function and store it in a variable.
  • Give the exponential value as user input using the int(input()) function and store it in another variable.
  • Pass the given base and exponential values as the arguments to the exponentl_squaring() function and store it in a variable.
  • Take a variable to say numb and initialize its value with 1000000007(10^9+7).
  • Create a function to say exponentl_squaring() which takes the given two base and exponential values as the arguments and returns the value of the power of base and exponent modular 10^9+7.
  • Inside the function, take a variable say p, and initialize its value to 1.
  • Loop until the given exponential value is greater than 0 using the while loop.
  • Check if the given exponential value is odd using the if conditional statement.
  • If it is true, multiply p with the given base value and store it in another variable.
  • Calculate the value of the above result modulus numb(10^9+7) and store it in the same variable p.
  • Multiply the given base value with itself and apply the modulus operator with 10^9+7(numb).
  • Store it in the same variable given the base value.
  • Divide the given exponential value by 2 and convert it to an integer using the int() function.
  • Store it in the same variable given exponential value.
  • Return the value of p modulus 10^9+7.
  • Print the value of the power of base and exponent modular 10^9+7.
  • The Exit of the Program.

Below is the implementation:

# Take a variable to say numb and initialize its value with 1000000007(10^9+7).
numb = 1000000007

# Create a function to say exponentl_squaring() which takes the given two base and
# exponential values as the arguments and returns the value of the power of base and
# exponent modular 10^9+7.


def exponentl_squaring(gvn_baseval, gvn_exponentlval):
  # Inside the function, take a variable say p, and initialize its value to 1.
    p = 1
    # Loop until the given exponential value is greater than 0 using the while loop.
    while(gvn_exponentlval > 0):
           # Check if the given exponential value is odd using the if conditional statement.
        if (gvn_exponentlval % 2 != 0):
            # If it is true, multiply p with the given base value and store it in another
            # variable.
            k = p * gvn_baseval
            # Calculate the value of the above result modulus numb(10^9+7) and store it in the
            # same variable p.
            p = k % numb
      # Multiply the given base value with itself and apply the modulus operator with
      # 10^9+7(numb).
      # Store it in the same variable given base value.
        gvn_baseval = (gvn_baseval * gvn_baseval) % numb
        # Divide the given exponential value by 2 and convert it to an integer using the
        # int() function.
        # Store it in the same variable given exponential value.
        gvn_exponentlval = int(gvn_exponentlval / 2)
   # Return the value of p modulus 10^9+7.
    return p % numb

# Give the base value as user input using the int(input()) function and store it in a variable.
gvn_baseval = int(input("Enter some random number = "))
# Give the exponential value as user input using the int(input()) function and 
# store it in another variable.
gvn_exponentlval = int(input("Enter some random number = "))
# Pass the given base and exponential values as the arguments to the exponentl_squaring()
# function and store it in a variable.
rslt = exponentl_squaring(gvn_baseval, gvn_exponentlval)
# Print the value of the power of base and exponent modular 10^9+7.
print("The value of the power of base and exponent modular 10^9+7 = ", rslt)

Output:

Enter some random number = 3
Enter some random number = 10000
The value of the power of base and exponent modular 10^9+7 = 895629451

Python Program for Exponential Squaring (Fast Modulo Multiplication) Read More »

Program Divide all Elements of a List by a Number

Python Program Divide all Elements of a List by a Number

In the previous article, we have discussed Python Program to Get Sum of all the Factors of a Number

Given a list, and the task is to divide all the elements of a given List by the given Number in Python

As we know, elements such as int, float, string, and so on can be stored in a List. As we all know, dividing a string by a number is impossible. To divide elements of a list, all elements must be int or float.

Examples:

Example1:

Input:

Given List = [3, 2.5, 42, 24, 15, 32]
Given Number = 2

Output:

The above given list after division all elements of a List by the given Number= [1.5, 1.25, 21.0, 12.0, 7.5, 16.0]

Example 2:

Input:

Given List =  [5, 10, 15, 20, 25, 30, 35, 40, 45, 50]
Given Number = 5

Output:

The above given list after division all elements of a List by the given Number= [1.0, 2.0, 3.0, 4.0, 5.0, 6.0, 7.0, 8.0, 9.0, 10.0]

Program Divide all Elements of a List by a Number

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Below are the ways to divide all Elements of a List by a Number.

Method #1: Using For Loop (Static Input)

Approach:

  • Give the list as static input and store it in a variable.
  • Give the number as static input and store it in another variable.
  • Take a new empty list and store it in a variable.
  • Iterate in the above-given list using For Loop.
  • Divide the iterator by the above-given number and append the result to the above declared new list.
  • print the above given new list after division all elements of a List by the given Number.
  • The Exit of the program.

Below is the implementation:

# Give the list as static input and store it in a variable.
gven_Lst = [3, 2.5, 42, 24, 15, 32]
# Give the number as static input and store it in another variable.
gvn_numb = 2
# Take a new empty list and store it in a variable.
Lst_aftr_div = []
# Iterate in the above given list using For Loop.
for itr in gven_Lst:
  # Divide the iterator  by  the above given number and append the result to the
  # above declared new list.
    Lst_aftr_div.append(itr/gvn_numb)
# print the above given list after division all elements of a List by the given Number.
print("The above given list after division all elements of a List by the given Number=", Lst_aftr_div)

Output:

The above given list after division all elements of a List by the given Number= [1.5, 1.25, 21.0, 12.0, 7.5, 16.0]

Method #2: Using For Loop (User Input)

Approach:

  • Give the list as user input using list(),map(),input(),and split() functions and store it in a variable.
  • Give the number as user input using the int(input()) function and store it in another variable.
  • Take a new empty list and store it in a variable.
  • Iterate in the above-given list using the For Loop.
  • Divide the iterator by the above-given number and append the result to the above declared new list.
  • Print the above given new list after division all elements of a List by the given Number.
  • The Exit of the program.

Below is the implementation:

#Give the list as user input using list(),map(),input(),and split() functions.
gven_Lst = list(map(float, input(
   'Enter some random List Elements separated by spaces = ').split()))
# Give the number as user input using int(input()) and store it in another variable.
gvn_numb = int(input("Enter some random number = " ))
#Take a new empty list and store it in a variable.
Lst_aftr_div = []
# Iterate in the above given list using For Loop.
for itr in gven_Lst:
  # Divide the iterator by the above given number and append the result to the
  # above declared new list.
    Lst_aftr_div.append(itr/gvn_numb)
# print the above given list after division all elements of a List by the given Number.
print("The above given list after division all elements of a List by the given Number=", Lst_aftr_div)

Output:

Enter some random List Elements separated by spaces = 4 5 8 9.6 15 63 32 84
Enter some random number = 4
The above given list after division all elements of a List by the given Number= [1.0, 1.25, 2.0, 2.4, 3.75, 15.75, 8.0, 21.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 Divide all Elements of a List by a Number Read More »

Program to Find the Smallest Divisor of an Integer

Python Program to Find the Smallest Divisor of an Integer

Our website provided core java programs examples with output aid beginners and expert coders to test their knowledge gap and learn accordingly.

Given a number, the task is to find the smallest number which divides the given number in Python.

Examples:

Example1:

Input:

given number = 91

Output:

The smallest which divides the given number [ 91 ] = 7

Example2:

Input:

given number = 169

Output:

Enter some random number = 169
The smallest which divides the given number [ 169 ] = 13

Program to Find the Smallest Divisor of an Integer in Python

There are several ways to find the smallest divisor of the given number in Python some of them are:

Method #1:Using for loop(Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Loop from 2 to given number using For loop.
  • Check if the iterator value divides the given number perfectly using the if statement and modulus operator.
  • Print the iterator value.
  • Break the loop using the break statement.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvnNumb = 91
# Loop from 2 to given number using For loop.
for itervalue in range(2, gvnNumb+1):
    # Check if the iterator value divides the given number
    # perfectly using the if statement and modulus operator.
    if(gvnNumb % itervalue == 0):
        # Print the iterator value.

        print(
            'The smallest which divides the given number [', gvnNumb, '] =', itervalue)
        # Break the loop using the break statement.
        break

Output:

The smallest which divides the given number [ 91 ] = 7

Method #2: Using for loop(User Input )

Approach:

  • Give the number as user input using the int(input()) function that converts the string to an integer.
  • Store it in a variable.
  • Loop from 2 to given number using For loop.
  • Check if the iterator value divides the given number perfectly using the if statement and modulus operator.
  • Print the iterator value.
  • Break the loop using the break statement.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function that converts
# the string to an integer.
# Store it in a variable.
gvnNumb = int(input('Enter some random number = '))
# Loop from 2 to given number using For loop.
for itervalue in range(2, gvnNumb+1):
    # Check if the iterator value divides the given number
    # perfectly using the if statement and modulus operator.
    if(gvnNumb % itervalue == 0):
        # Print the iterator value.

        print(
            'The smallest which divides the given number [', gvnNumb, '] =', itervalue)
        # Break the loop using the break statement.
        break

Output:

Enter some random number = 369
The smallest which divides the given number [ 369 ] = 3

Explanation:

  • The user must enter a number.
  • The for loop has a range of 2 to the number
  • If the remainder of the number is zero when divided by the value of i the element is a divisor of the number.
  • Print the number and break the loop.

Method #3:Using While Loop(Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Take a temporary variable and initialize it with 2.
  • Loop till the temporary variable is less than or equal to the given number using the while loop.
  • Check if the temporary variable divides the given number perfectly using the if statement and modulus operator.
  • Print the temporary variable.
  • Break the loop using the break statement.
  • Increase the value of the temporary variable by 1.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvnNumb = 125
# Take a temporary variable and initialize it with 2.
tempnumber = 2
# Loop till the temporary variable is less than
# or equal to the given number using the while loop.
while(tempnumber <= gvnNumb):
    # Check if the temporary variable divides the given number perfectly
    # using the if statement and modulus operator.
    if(gvnNumb % tempnumber == 0):
        # Print the iterator value.
        print(
            'The smallest which divides the given number [', gvnNumb, '] =', tempnumber)
        # Break the loop using the break statement.
        break
 # Increase the value of the temporary variable by 1.
    tempnumber = tempnumber+1

Output:

The smallest which divides the given number [ 125 ] = 5

Method #4:Using While Loop(User Input)

Approach:

  • Give the number as user input using the int(input()) function that converts the string to an integer.
  • Store it in a variable.
  • Take a temporary variable and initialize it with 2.
  • Loop till the temporary variable is less than or equal to the given number using the while loop.
  • Check if the temporary variable divides the given number perfectly using the if statement and modulus operator.
  • Print the temporary variable.
  • Break the loop using the break statement.
  • Increase the value of the temporary variable by 1.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function that converts
# the string to an integer.
# Store it in a variable.
gvnNumb = int(input('Enter some random number = '))
# Take a temporary variable and initialize it with 2.
tempnumber = 2
# Loop till the temporary variable is less than
# or equal to the given number using the while loop.
while(tempnumber <= gvnNumb):
    # Check if the temporary variable divides the given number perfectly
    # using the if statement and modulus operator.
    if(gvnNumb % tempnumber == 0):
        # Print the iterator value.
        print(
            'The smallest which divides the given number [', gvnNumb, '] =', tempnumber)
        # Break the loop using the break statement.
        break
 # Increase the value of the temporary variable by 1.
    tempnumber = tempnumber+1

Output:

Enter some random number = 578
The smallest which divides the given number [ 578 ] = 2

Method #5:Using List Comprehension

Approach:

  • Give the number as user input using the int(input()) function that converts the string to an integer.
  • Store it in a variable.
  • Using List Comprehension, for loop and if statements add all the divisors of the given number from 2 to given number into the list.
  • Print the first element in the given list.
  • The Exit of the Program.

Below is the implementation:

# Give the number as user input using the int(input()) function that converts
# the string to an integer.
# Store it in a variable.
gvnNumb = int(input('Enter some random number = '))
# Using List Comprehension, for loop and if statements add
# all the divisors of the given number
# from 2 to given number into the list.
divList = [numbe for numbe in range(2, gvnNumb+1) if(gvnNumb % numbe == 0)]
smalldivi = divList[0]
# Print the first element in the given list.
print('The smallest which divides the given number [', gvnNumb, '] =', smalldivi)

Output:

Enter some random number = 169
The smallest which divides the given number [ 169 ] = 13

Related Programs:

Python Program to Find the Smallest Divisor of an Integer Read More »

Python Program for Double Factorial

In the previous article, we have discussed Python Program for Product of Maximum in First array and Minimum in Second
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

Double Factorial:

The product of all the integers from 1 to n with the same parity (odd or even) as n is the double factorial of a non-negative integer n. It is also known as a number’s semi factorial and is denoted by!!.

For example, the double factorial of 7 is 7*5*3*1 = 105

It is worth noting that as a result of this definition, 0!! = 1.

The double factorial for even number ‘n’ is:

n!!=prod_{k=1}^{n/2}(2k)=n(n-2)(n-4).....4*2

The double factorial for odd number ‘n’ is:

n!!=prod_{k=1}^{{n+1}/2}(2k-1)=n(n-2)(n-4).....3*1

Given a number ‘n’ and the task is to find the double factorial of a given number.

Examples:

Example 1:

Input:

Given number = 5

Output:

The double factorial of a given number{ 5 } =  15

Example 2:

Input:

Given number = 10

Output:

The double factorial of a given number{ 10 } =  3840

Program for Double Factorial in Python

Below are the ways to find the double factorial of a given number.

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 ‘c’.
  • Loop from the given number to 0 in decreasing order with the stepsize of -2 using the for loop.
  • Inside the loop multiply the above initialized variable c with the iterator value and store it in the same variable ‘c’.
  • Print the double factorial of a given number.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
numbr = 8
# Take a variable, initialize it with the value '1', and store it in another
# variable say 'c'.
c = 1
# Loop from the given number to 0 in decreasing order with the stepsize of -2
# using the for loop.
for i in range(numbr, 0, -2):
    # Inside the loop multiply the above initialized variable c with the iterator value
    # and store it in the same variable 'c'.
    c *= i
 # Print the double factorial of a given number.
print("The double factorial of a given number{", numbr, "} = ", c)

Output:

The double factorial of a given number{ 8 } =  384

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 ‘c’.
  • Loop from the given number to 0 in decreasing order with the stepsize of -2 using the for loop.
  • Inside the loop multiply the above initialized variable c with the iterator value and store it in the same variable ‘c’.
  • Print the double factorial of a 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.
numbr = int(input("Enter a random number = "))
# Take a variable, initialize it with the value '1', and store it in another
# variable say 'c'.
c = 1
# Loop from the given number to 0 in decreasing order with the stepsize of -2
# using the for loop.
for i in range(numbr, 0, -2):
    # Inside the loop multiply the above initialized variable c with the iterator value
    # and store it in the same variable 'c'.
    c *= i
 # Print the double factorial of a given number.
print("The double factorial of a given number{", numbr, "} = ", c)

Output:

Enter a random number = 7
The double factorial of a given number{ 7 } = 105

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 Double Factorial Read More »

Program to Compute Prime Factors of an Integer

Python Program to Compute Prime Factors of an Integer

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

In this post, we’ll look at a Python program that prints out all the prime factors of a given number. A number is considered to be a prime factor of another number if it is a prime number and perfectly divides the given number. In this section, we will look at what a prime factor is, how to discover a prime factor, and the python program.

A number’s prime factors are the prime numbers that, when multiplied together, give the number. Two conditions can be used to determine a number’s prime factor:

The digit should be a prime number.

The number should perfectly divide the number.

Examples:

Example1:

Input:

given number =240

Output:

The prime factors of the given number are : 
2
3
5

Example2:

Input:

given number =33

Output:

Enter some random number = 33
The prime factors of the given number are : 
3
11

Program to Compute Prime Factors of an Integer in Python

There are several ways to compute prime factors of an integer in python some of them are:

Method #1: Using while loop (Static Input)

Approach:

  • Give the integer value as static input.
  • Using a while loop, first determine the number’s components.
  • Calculate whether the factors are prime or not using another while loop within the previous one.
  • Exit of program.

Below is the implementation:

# given number
numb = 240
# Printing the prime factors
print("The prime factors of the given number are : ")
value = 1
while(value <= numb):
    k = 0
    if(numb % value == 0):
        j = 1
        while(j <= value):
            if(value % j == 0):
                k = k+1
            j = j+1
        if(k == 2):
          # printing the prime factor
            print(value)
    # incremeent the value by 1
    value = value+1

Output:

The prime factors of the given number are : 
2
3
5

Explanation:

  • Given the number as static input.
  • The while loop is utilized, and the integer factors are obtained by using the modulus operator and determining whether the remainder of the number divided by value is zero.
  • The integer’s factors are then checked again to see if they are prime.
  • The factor of an integer is prime if it has two factors.
  • The integer’s prime factor is printed.

Method #2: Using while loop (User Input)

Approach:

  • Scan the number using int(input()) function.
  • Using a while loop, first determine the number’s components.
  • Calculate whether the factors are prime or not using another while loop within the previous one.
  • Exit of program.

Below is the implementation:

# Scan the number using int(input()) function.
numb = int(input("Enter some random number = "))
# Printing the prime factors
print("The prime factors of the given number are : ")
value = 1
while(value <= numb):
    k = 0
    if(numb % value == 0):
        j = 1
        while(j <= value):
            if(value % j == 0):
                k = k+1
            j = j+1
        if(k == 2):
          # printing the prime factor
            print(value)
    # incremeent the value by 1
    value = value+1

Output:

Enter some random number = 220
The prime factors of the given number are : 
2
5
11

Method #3:Efficient Method (User input)

Approach:

  • Scan the given number using int(input()) function.
  • We will print 2 and divide numb by 2 while it is divisible by 2.
  • Following step 2, numb must always be odd.
  • Begin a loop with I = 3 and work your way up to the square root of n. If I divide numb by I print I and divide numb by i. If we  unable to divide numb , increase the I value by 2 and proceed.
  • If numb is a prime number and higher than 2, it cannot be reduced to 1.
  • So, if numb is larger than 2, print it.

Below is the implementation:

import math
# Scan the number using int(input()) function.
numb = int(input("Enter some random number = "))
# Printing the prime factors
print("The prime factors of the given number are : ")
while numb % 2 == 0:
      print(2),
      numb = numb / 2

   # n became odd
for i in range(3,int(math.sqrt(numb))+1,2):
    while (numb % i == 0):
        print (int(i))
        numb = numb / i
    
if numb > 2:
    print (int(numb))

Output:

Enter some random number = 33
The prime factors of the given number are : 
3
11

Related Programs:

Python Program to Compute Prime Factors of an Integer Read More »

Program to Calculate the HCF

Python Program to Calculate the HCF/GCD

Have you mastered basic programming topics of java and looking forward to mastering advanced topics in a java programming language? Go with these ultimate Advanced java programs examples with output & achieve your goal in improving java coding skills.

Highest Common Factor (HCF) / Greatest Common Divisor (GCD) :

When at least one of the integers is not zero, the greatest positive integer that evenly divides the numbers without a remainder is called the Highest Common Factor or Greatest Common Divisor.

The GCD of 12 and 16 is, for example, 4.

Given two numbers the task is to find the highest common factor of the two numbers in Python.

Examples:

Example1:

Input:

a= 24   b=36

Output:

The Highest Common Factor (HCF) of the numbers 24 36 = 12

Example2:

Input:

a= 18 b=72

Output:

The Highest Common Factor (HCF) of the numbers 18 72 = 18

Example3:

Input:

a= 4 b=8

Output:

The Highest Common Factor (HCF) of the numbers 4 8 = 4

Example4:

Input:

a= 9 b=9

Output:

The Highest Common Factor (HCF) of the numbers 9 9 = 9

Explanation:

 The Highest common factor of two numbers is number itself if both the numbers are equal

Python Program to Calculate the HCF/GCD

There are several ways to calculate the hcf of the two numbers in python some of them are:

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.

Method #1:Using loops

Below is the implementation:

# function which computes and returns the highest common factor of the given two numbers
def findGcd(number1, number2):

    # finding the smaller number
    if number1 > number2:
        smallNumber = number2
    else:
        smallNumber = number1
    # using for loop to traverse from 1 to smaller number
    for i in range(1, smallNumber+1):
      # if it divides the given two numbers without leaving the
      # remainder then assign result it with that loop iterator value
        if((number1 % i == 0) and (number2 % i == 0)):
            result = i
    # return the final result which is greatest common divisor(GCD)
    return result


# given two numbers
# given number a
number1 = 24
# given number b
number2 = 36
# passing the given two numbers to findGcd function which returns the greatest common factor of the given two numbers
ans = findGcd(number1, number2)
# print the hcf of the given two numbers
print("The Highest Common Factor (HCF) of the numbers", number1, number2, "=", ans)

Output:

The Highest Common Factor (HCF) of the numbers 24 36 = 12

Explanation:

The findGcd() function is called with two integers stored in variables number1 and number2. The function computes and returns the H.C.F. of these two integers.

Because the H.C.F can only be less than or equal to the lowest number, we first find the smaller of the two integers in the function. Then, to move from 1 to that number, we utilize a for loop.

We check if our number divides both input numbers precisely in each cycle. If this is the case, the number is saved as H.C.F. We wind up with the greatest integer that divides both numbers properly at the end of the loop.

The method described above is simple to learn and apply, but it is inefficient. The Euclidean algorithm is a significantly more efficient technique of calculating the H.C.F.

Method #2:Using Euclidean algorithm

This approach is based on the fact that the H.C.F. of two numbers also divides their difference.

We divide the greater by the smaller and take the remainder in this algorithm. Divide the smaller number by the remainder. Repeat until the residual equals zero.

Facts of Euclidean Algorithm:

GCD does not change when we subtract a smaller number from a larger number (we reduce a larger number). So, if we keep subtracting the largest of two numbers, we get GCD.
Instead of subtracting, we can divide the smaller integer, and the procedure will terminate when we find a remainder of zero.

Algorithm:

  1. Let number1 and number2 be the two numbers in the pseudocode of the algorithm.
  2. number1 mod number2 =R
  3. Assume that number1= number2 and number2 = R.
  4. Continue with Steps 2 and 3 until number1 mod number2 is greater than 0.
  5. GCD = number2
  6. Print the GCD

Below is the implementation:

# function which computes and returns the highest common factor of the given two numbers
def findGcd(number1, number2):
    while(number2):
        number1, number2 = number2, number1 % number2
    return number1


# given two numbers
# given number a
number1 = 24
# given number b
number2 = 36
# passing the given two numbers to findGcd function which returns the greatest common factor of the given two numbers
ans = findGcd(number1, number2)
# print the hcf of the given two numbers
print("The Highest Common Factor (HCF) of the numbers", number1, number2, "=", ans)

Output:

The Highest Common Factor (HCF) of the numbers 24 36 = 12

Explanation:

We’ll keep looping until y equals zero. In Python, the statement number1, number2 = number2, number1 % number2 swaps values.

In each iteration, the value of number2 is placed in number1 and the remainder (number1 % number2) is placed in number2. We have H.C.F. in number1 when number2 becomes zero.

Method #3:Using gcd() function in math module

This is the simplest and quick method to calculate the greatest common divisor of the given two numbers.

Approach:

  • Import the math module
  • Use math.gcd(number1,number2) to calculate the gcd of the numbers number1 and number2.
  • Print the result.

Below is the implementation:

# importing math module
import math
# function which computes and returns the highest common factor of the given two numbers


def findGcd(number1, number2):
    # calculating gcd using gcd() function
    resGcd = math.gcd(number1, number2)
    # return the gcd of the number 1 and number2
    return resGcd


# given two numbers
# given number a
number1 = 24
# given number b
number2 = 36
# passing the given two numbers to findGcd function which returns the greatest common factor of the given two numbers
ans = findGcd(number1, number2)
# print the hcf of the given two numbers
print("The Highest Common Factor (HCF) of the numbers", number1, number2, "=", ans)

Output:

The Highest Common Factor (HCF) of the numbers 24 36 = 12

Explanation :It just calculated the gcd in 1 line which is math.gcd()
Related Programs:

Python Program to Calculate the HCF/GCD Read More »

Pascal’s Triangle using Python

Python program to print Pascal’s Triangle

Want to excel in java coding? Practice with these Java Programs examples with output and write any kind of easy or difficult programs in the java language

Pascal Triangle Definition:

Pascal’s triangle is a lovely shape produced by arranging numbers. The sum of the two numbers above it is used to produce each number. This triangle’s outside edges are always 1. The triangle is depicted in the diagram below.

Explanation:

To illustrate the triangle in a nutshell, the first line is 1. There are two ones in the line after that. The second line is here.

1 2 1 is the third line, which is created by adding the ones from the previous line. Similarly, the number of 1 and 2 in an alternative pattern forms the fourth line, and so on.

Examples of pascal Triangle

Example 1:

Input :

height =5

Output:

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

Example 1:

Input :

height =10

Output :

           1
          1 1
         1 2 1
        1 3 3 1
       1 4 6 4 1
      1 5 10 10 5 1
     1 6 15 20 15 6 1
    1 7 21 35 35 21 7 1
   1 8 28 56 70 56 28 8 1
  1 9 36 84 126 126 84 36 9 1

Pascal Triangle in Python

Below are the methods to print the pascal triangle.

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.

Method #1: Implementation Using zip function

Using the oneval variable, we will first initialise the top row in this function. Variable zerovalue=0 is also set to zero. To run the code for n iterations, we’ll use a for loop.

We’ll print the list generated by the oneval variable within the for loop. We’ll now add the onevalue to left and right elements. We’ve also used the zip feature in this case.

Below is the implementation:

def printPascal(height):
    onevalue = [1]
    zero = [0]
    for i in range(height):
        print(*onevalue)
        onevalue = [left+right for left,
                    right in zip(onevalue+zero, zero+onevalue)]


# given height
height = 5
# passing the height as paramter to printPascal function
printPascal(height)

Output:

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

Method #2:Using NCR

Approach:

  • Consider the number of rows to be printed; let’s say it’s n.
  • To print the rows, repeat iteration I from 0 to n times.
  • Iterate for j from 0 to (N – 1) in the inner loop.
  • ” “ is a single blank space to be printed.
  • It’s enough to close the inner loop (j loop) for left spacing.
  • Make an inner iteration from 0 to I for j.
  • nCr of I and j should be printed.
  • Close the inner loop.
  • For each inner iteration, print a newline character (\n).

Below is the implementation:

# impoerting factorial fucntion from math module
from math import factorial


def printPascal(height):
    for i in range(height):
        for j in range(height-i+1):

            # for spacing in left
            print(end=" ")

        for j in range(i+1):
            print(factorial(i)//(factorial(j)*factorial(i-j)), end=" ")

    # printing in new line
        print()


# given height
height = 5
# passing the height as paramter to printPascal function
printPascal(height)

Output:

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

Method #3:Using Binomial Coefficients

The following definition of a Binomial Coefficient may be used to optimise the above code the i’th entry in a line number line is Binomial Coefficient C(line, i) and all lines begin with value 1. The idea is to use C to measure C(line, i) using C(line, i-1).

C(line, i) = C(line, i-1) * (line - i + 1) / i

Below is the implementation:

def printPascal(height):
    for i in range(1, height+1):
        for j in range(0, height-i+1):
            print(' ', end='')

        # since first eelement is always 1
        onevalue = 1
        for j in range(1, i+1):

            # first value of every line is 1 always.
            print(' ', onevalue, sep='', end='')

            # using binomial cofficients to calculat using onevalue
            onevalue = onevalue * (i - j) // j
        print()


# given height
height = 5
# passing the height as paramter to printPascal function
printPascal(height)

Output:

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

Related Programs:

Python program to print Pascal’s Triangle Read More »

Program to Find the Factors of a Number in Python and C++ Programming

Python Program to Find the Factors of a Number | C++ Program to Find Factors

Beginners and experienced programmers can rely on these Best Java Programs Examples and code various basic and complex logics in the Java programming language with ease.

Factors of a number:

When two whole numbers are multiplied, the result is a product. The factors of the product are the numbers we multiply.

In mathematics, a factor is a number or algebraic expression that equally divides another number or expression, leaving no remainder.

The prime number is defined as a number that has only two factors one and itself. Composite numbers are those that contain more than two variables.

Given a number the task is to print the factors of the given number.

Examples:

Example1:

Input:

given_number=360

Output:

printing the factors of given number
1
2
3
4
5
6
8
9
10
12
15
18
20
24
30
36
40
45
60
72
90
120
180
360

Example2:

Input:

given_number=10

Output:

printing the factors of given number
1
2
5
10

Program to Find the Factors of a Number

Below are the ways to find the factors of a number:

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.

1)Using for loop to loop from 1 to N in Python

Algorithm:

Divide a positive number “N” by the natural numbers 1 to “N” to find the factor. If a number is divisible by a natural number, the factor is the natural number. A number N can only have factors in the range of 1 to N.

Approach:

  • Assume the input is a number N.
  • Create an iterator variable and set its value to 1.
  • Using an iterator variable to divide the number N
  • It is a factor of the given number N if it is divisible.
  • The iterator variable should be increased.
  • Rep steps 4 and 5 until the iterator variable reaches the value N.

This is the simplest and most straightforward way to find variables in a Python number programme. While declaring the variables, we’ll take a number. Python software that uses a for-loop to find factors of a number and print the factors on the screen.

Below is the implementation:

# given number
number = 360
# printing the factors of given number
print("printing the factors of given number : ")
# using for loop
for i in range(1, number+1):
    # checking if iterator divides the number if so then print it(because it is factor)
    if(number % i == 0):
        print(i)

Output:

printing the factors of given number : 
1
2
3
4
5
6
8
9
10
12
15
18
20
24
30
36
40
45
60
72
90
120
180
360

2)Using for loop to loop from 1 to N in C++

It is similar to method 1 except the syntax. Let us see how to find factors  using for loop in c++

Below is the implementation:

#include <iostream>
using namespace std;
int main()
{ // given number
    int number = 360;
    // printing the factors
    cout << "printing the factors of given number :"
         << endl;
    // using for loop to loop from 1 to N
    for (int i = 1; i <= number; i++)
        // checking if iterator divides the number if so
        // then print it(because it is factor)
        if (number % i == 0)
            cout << i << endl;
    return 0;
}

Output:

printing the factors of given number :
1
2
3
4
5
6
8
9
10
12
15
18
20
24
30
36
40
45
60
72
90
120
180
360

We can see that the outputs of both the programs are same

3)Limitations of running loop from 1 to N

In these two methods the loop runs from 1 to number N.

Hence we can say that the time complexity of above methods are O(n).

What if the number is very large?

Like 10^18 the above methods takes nearly 31 years to execute.

Then How to avoid this?

We can see that the factors of the numbers exist from 1 to N/2 except number itself.

But this also takes nearly 15 yrs to execute.

So to above this we loop till square root of N in next method which gives Time Complexity O(Sqrt(n)).

4)Using while loop to loop from 1 to SQRT(N) in Python

Many of the divisors are present in pairs if we look closely. For eg, if n = 16, the divisors are (1,16), (2,8), and (3,8), (4,4)
We could significantly speed up our program if we took advantage of this fact.
However, if there are two equal divisors, as in the case of, we must be cautious (4, 4). In that case, we’d just print one of them.

We use while loop to loop from 1 to sqrt(number)

Below is the implementation:

# importing math module
import math
# given number
number = 360
# taking a iterator and initlaizing it with 1
i = 1
print("printing the factors of given number : ")
# looping till sqrt(number) using while
while i <= math.sqrt(number):

    if (number % i == 0):

        # If both thee divisors are equal then print only one divisor
        if (number / i == i):
            print(i)
        else:
            # else print both the divisors
            print(i)
            print(number//i)
   # increment the iterator by 1
    i += 1

Output:

printing the factors of given number : 
1
360
2
180
3
120
4
90
5
72
6
60
8
45
9
40
10
36
12
30
15
24
18
20

Related Programs:

Python Program to Find the Factors of a Number | C++ Program to Find Factors Read More »

Python Programs for Class 12

Python Programs for Class 12 | Python Practical Programs for Class 12 Computer Science

Grab the opportunity to learn all effective java programming language concepts from basic to advance levels by practicing these Java Program Examples with Output

CBSE Class 12 Computer Science Python Programs with Output are provided in this tutorial. Students who are pursuing 12th can refer to this page for practical files of python programs in order to prepare and learn well for the board exams. Basically, the Class XII python practical file must have 20 python programs and 5 SQL Queries. But today, in this tutorial, we are going to compile some of the important python programs for class 12 CBSE computer science.

Practicing more and more with the provided python practical programs for Class XII CBSE can make you win in the race of python programming and in your software career too. So, dive into this article completely and start learning python programming language easily and efficiently.

List of Python Programs for Class 12 Practical File with Output PDF

Here are some of the python programs for class 12 pursuing students. Just take a look at them before kickstarting your programming preparation for board exams. Click on the available links and directly jump into the respective python program to understand & continue with other programs that are listed in the CBSE Class 12 Computer Science Python Programming Practical File.

1)Program for Arithmetic Operations in Python

Task is to perform Arithmetic Operations in python

Below is the implementation:

#python program which performs simple arithmetic operations
# given two numbers
# given first number
numberone = 29
numbertwo = 13
# adding the  given two numbers
addnumb = numberone+numbertwo
# printing the result of sum of two numbers
print("Adding the given two numbers", numberone, "+", numbertwo, "=", addnumb)
# subtracting the given two numbers
diffnumb = numberone-numbertwo
# printing the result of difference of two numbers
print("Subtracting the given two numbers",
      numberone, "-", numbertwo, "=", diffnumb)
# multiply the given two numbers
mulnumb = numberone*numbertwo
# printing the result of product of two numbers
print("Multiplying the given two numbers",
      numberone, "*", numbertwo, "=", mulnumb)
# diving the given two numbers
divnumb = numberone+numbertwo
# printing the result of sum of two numbers
print("Dividing the given two numbers",
      numberone, "/", numbertwo, "=", divnumb)

Output:

Adding the given two numbers 29 + 13 = 42
Subtracting the given two numbers 29 - 13 = 16
Multiplying the given two numbers 29 * 13 = 377
Dividing the given two numbers 29 / 13 = 42

2)Program to Generate a Random Number

We’ll write a program that produces a random number between a specific range.

Below is the implementation:

# Program which generates the random number between a specific range.
# importing random module as below
import random
# generating random number
randNumber = random.randint(1, 450)
# print the random number which is generated above
print("Generating random numbers between 1 to 450 = ", randNumber)

Output:

Generating random numbers between 1 to 450 =  420

3)Program to Convert Celsius To Fahrenheit

We will convert the given temp in celsius to fahrenheit as below.

Below is the implementation:

# Python program for converting celsius to fahrenheit temperature.
# given temp in celsius
celsiusTemp = 42.5

# converting the given temp in celsius to fahrenheit temperature
fahrenheitTemp = (celsiusTemp * 1.8) + 32
# print the converted temperature value
print('Converting the given temp in celsius =',
      celsiusTemp, " to Fahrenhiet = ", fahrenheitTemp)

Output:

Converting the given temp in celsius = 42.5  to Fahrenhiet =  108.5

4)Python Program to Check if a Number is Positive, Negative or zero

We will write a program to check if the given number is positive number , negative number or zero using if else conditional statements.

Below is the implementation:

# Python Program to Check if a Number is Positive number, Negative number or zero
# Function which prints whether the given number
#is positive number ,negative number or zero


def checkNumber(given_Num):
    # checking if the given number is positive number
    if(given_Num > 0):
        print("The given number", given_Num, "is positive")
    # checking if the given number is negative number
    elif(given_Num < 0):
        print("The given number", given_Num, "is negative")
    # if the above conditions are not satisfied then the given number is zero
    else:
        print("The given number", given_Num, "is zero")


# given numbers
# given number 1
given_num1 = 169
# passing the given number to checkNumber Function which prints the type of number(+ve,-ve,0)
checkNumber(given_num1)
# given number 2
given_num1 = -374
# passing the given number to checkNumber Function which prints the type of number(+ve,-ve,0)
checkNumber(given_num1)

# given number 3
given_num1 = 0
# passing the given number to checkNumber Function which prints the type of number(+ve,-ve,0)
checkNumber(given_num1)

Output:

The given number 169 is positive
The given number -374 is negative
The given number 0 is zero

5)Python Program to Check if a Number is Odd or Even

We will write a program which checks whether the given number is even number or odd number using if else conditional statements.

Below is the implementation:

# Python Program to Check if a Number is Odd or Even
# Function which prints whether the given number
# is even number ,odd number


def checkNumber(given_Num):
    # checking if the given number is even number
    if(given_Num % 2 == 0):
        print("The given number", given_Num, "is even number")
    # checking if the given number is odd number that is if given number is not even then it is odd number
    else:
        print("The given number", given_Num, "is odd number")


# given numbers
# given number 1
given_num1 = 169
# passing the given number to checkNumber Function which
# prints the type of number(even number or odd number)
checkNumber(given_num1)
# given number 2
given_num1 = 26
# passing the given number to checkNumber Function which
# prints the type of number(even number or odd number)
checkNumber(given_num1)

Output:

The given number 169 is odd number
The given number 26 is even number

6)Python Program to Check Leap Year

We will check whether the given number is leap year or not.

Below is the implementation:

# Python program to check if year is a leap year
# given year
given_year = 2024

if (given_year % 4) == 0:
    if (given_year % 100) == 0:
        if (given_year % 400) == 0:
            print("Given year", given_year, "is leap year")
        else:
            print("Given year", given_year, "is not leap year")
    else:
        print("Given year", given_year, "is leap year")
else:
    print("Given year", given_year, "is not leap year")

Output:

Given year 2024 is leap year

7)Python Program to Find ASCII Value of given_Character

We will find the ascii value of given character in python using ord() function.

Below is the implementation:

# Python Program to Find ASCII Value of given_Character
# given character
given_character = 's'
# finding ascii value of given character
asciiValue = ord(given_character)
# printing ascii value of given character
print(" ascii value of given character", given_character, "=", asciiValue)

Output:

ascii value of given character s = 115

8)Python program to print grades based on marks scored by a student

We will display the grades of students based on given marks using if elif else statements.

Below is the implementation:

# Python program to print grades based on marks scored by a student
# given marks scored by student
given_marks = 68
markGrade = given_marks//10
# cheecking if grade greater than 9
if(markGrade >= 9):
    print("grade A+")
elif(markGrade < 9 and markGrade >= 8):
    print("grade A")
elif(markGrade < 8 and markGrade >= 7):
    print("grade B+")
elif(markGrade < 7 and markGrade >= 6):
    print("grade B")
elif(markGrade < 6 and markGrade >= 5):
    print("grade C+")
else:
    print("Fail")

Output:

grade B

9)Python program to print the sum of all numbers in the given range

Given two ranges(lower limit range and upper limit range) the task is to print the sum of all numbers in the given range.

i)Using for loop

We will use for loop and range function to literate from lower range limit and upper range limit.

Below is the implementation:

# Python program to print the sum of all numbers in the given range
# given lower limit range
lower_range = 17
# given upper limit range
upper_range = 126
# initializing sum of range to 0
rangeSum = 0
# Using for loop to traverse from lower limit range to upper limit range
for i in range(lower_range, upper_range+1):
    rangeSum = rangeSum+i
print("the sum of all numbers between",
      lower_range, "to", upper_range, "=", rangeSum)

Output:

the sum of all numbers between 17 to 126 = 7865

ii)Using mathematical formula of sum of n natural numbers

We we subtract the sum of upper range limit with lower range limit.

sum of n natural numbers =( n * (n+1) ) /2

Below is the implementation:

# Python program to print the sum of all numbers in the given range
# given lower limit range
lower_range = 17
# given upper limit range
upper_range = 126
low_range = lower_range-1
# calculating the sum of natural numbers from 1 to lower limit range
lowSum = (low_range*(low_range+1))/2
# calculating the sum of natural numbers from 1 to upper limit range
highSum = (upper_range*(upper_range+1))/2
# calculating the sum of all numbers between the given range
rangeSum = highSum-lowSum
# printing the sum of all natural numbers between the given range
print("the sum of all numbers between",
      lower_range, "to", upper_range, "=", int(rangeSum))

Output:

the sum of all numbers between 17 to 126 = 7865

10)Python program to print all even numbers in given range

Given two ranges(lower limit range and upper limit range) the task is to print all even numbers in given range

We will use for loop and range function to literate from lower range limit and upper range limit and print all the numbers which are divisible by 2 that  is even numbers

Below is the implementation:

# Python program to print the even numbers in
#  given range(lower limit range and upper limit range)
# given lower limit range
lower_range = 17
# given upper limit range
upper_range = 126
# printing the even numbers in the giveen range using looop
# Iterate from lowe limit range to upper limit range
for numb in range(lower_range, upper_range+1):
    # checking if the number is divisible by 2
    if(numb % 2 == 0):
        # we will print the number if the number is divisible by 2
        print(numb)

Output:

18
20
22
24
26
28
30
32
34
36
38
40
42
44
46
48
50
52
54
56
58
60
62
64
66
68
70
72
74
76
78
80
82
84
86
88
90
92
94
96
98
100
102
104
106
108
110
112
114
116
118
120
122
124
126

11)Python program to print  star pyramid pattern

We will print the star pyramid using nested for loops

Below is the implementation:

# Python program to print  star pyramid pattern
# given number  of rows
given_rows = 15
for i in range(given_rows+1):
    for j in range(i):
        print("*", end=" ")
    print()

Output:

* 
* * 
* * * 
* * * * 
* * * * * 
* * * * * * 
* * * * * * * 
* * * * * * * * 
* * * * * * * * * 
* * * * * * * * * * 
* * * * * * * * * * * 
* * * * * * * * * * * * 
* * * * * * * * * * * * * 
* * * * * * * * * * * * * * 
* * * * * * * * * * * * * * *

12)Python program to print  number pyramid pattern

We will print the number pyramid using nested for loops

Below is the implementation:

# Python program to print  star pyramid pattern
# given number  of rows
given_rows = 15
for i in range(1, given_rows+1):
    for j in range(1, i+1):
        print(j, end=" ")
    print()

Output:

1 
1 2 
1 2 3 
1 2 3 4 
1 2 3 4 5 
1 2 3 4 5 6 
1 2 3 4 5 6 7 
1 2 3 4 5 6 7 8 
1 2 3 4 5 6 7 8 9 
1 2 3 4 5 6 7 8 9 10 
1 2 3 4 5 6 7 8 9 10 11 
1 2 3 4 5 6 7 8 9 10 11 12 
1 2 3 4 5 6 7 8 9 10 11 12 13 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15

13)Python program to print Fibonacci numbers to given limit

Given two ranges(lower limit range and upper limit range) the task is to print all fibonacci numbers in given range

Below is the implementation:

# Python program to print the all the fibonacci numbers in the given range
# given lower limit range
lower_range = 2
# given upper limit range
upper_range = 1000
first, second = 0, 1
# using while loop
while (first < upper_range):
    if(upper_range >= lower_range and first <= upper_range):
        print(first)
    first, second = second, first+second

Output:

0
1
1
2
3
5
8
13
21
34
55
89
144
233
377
610
987

14)Python program to print numbers from 1 to n except 5 multiples

We will use the for loop to print all numbers from 1 to n except 5 multiples.

Below is the implementation:

# Python program to print numbers from 1 to n except 5 multiples
# given number
numb = 49
# using for loop to iterate from 1 to n
for num in range(1, numb+1):
    # if number is not divisible by 5 then print it
    if(num % 5 != 0):
        print(num)

Output:

1
2
3
4
6
7
8
9
11
12
13
14
16
17
18
19
21
22
23
24
26
27
28
29
31
32
33
34
36
37
38
39
41
42
43
44
46
47
48
49

15)Python program to split and join a string

Given a string the task is to split the given string and join the string

Example split the string with ‘@’ character and join with ‘-‘ character.

Below is the implementation:

#python program to split and join a string
# given string
string = "Hello@this@is@BTechGeeks"
# splitting thee given string with @ character
string = string.split('@')
print("After splitting the string the given string =", *string)
# joining the given string
string = '-'.join(string)
print("After joining the string the given string =", string)

Output:

After splitting the string the given string = Hello this is BTechGeeks
After joining the string the given string = Hello-this-is-BTechGeeks

16)Python program to sort the given list

We will sort the given list using sort() function

Below is the implementation:

# Python program to sort the given list
given_list = ["Hello", "This", "Is", "BTechGeeks"]
# printing the list before sorting
print("Before sorting the list given list :")
print(given_list)
# sorting the given list using sort() function
given_list.sort()
# printing thre list after sorting
print("after sorting the list given list :")
print(given_list)

Output:

Before sorting the list given list :
['Hello', 'This', 'Is', 'BTechGeeks']
after sorting the list given list :
['BTechGeeks', 'Hello', 'Is', 'This']

17)Python program to sort a string

Given  list of strings the task is to sort the strings using sort() function.

We will use the split() function to split the string with spaces and store it in list.

Sort the list.

Below is the implementation:

# Python program to sort a string
given_string = "Hello This Is BTechGeeks"
# split the given string using spilt() function(string is separated by spaces)
given_string = given_string.split()
# printing the string before sorting
print("Before sorting the sorting given sorting :")
print(*given_string)
# sorting the given string(list) using sort() function
given_string.sort()
# printing the string after sorting
print("after sorting the string given string :")
print(*given_string)

Output:

Before sorting the sorting given sorting :
Hello This Is BTechGeeks
after sorting the string given string :
BTechGeeks Hello Is This

18)Python Program to Search an element in given list

Given a list and the task is to search for a given element in the list .

We will use the count function to search an element in given list.

If the count is 0 then the element is not present in list

Else the given element is present in list

Below is the implementation:

# Python program to search an element in given list
given_list = ["Hello", "This", "Is", "BTechGeeks"]
# given element to search
element = "BTechGeeks"
# using count function to check whether the given element the present in list or not
countelement = given_list.count(element)
# if count of element is zero then element is not present in list
if(countelement == 0):
    print("The given element", element, "is not present in given list")
else:
    print("The given element", element, "is present in given list")

Output:

The given element BTechGeeks is present in given list

19)Python program to count the frequency of given element in list

Given a list and the task is to find the frequency of a given element in the list .

We will use the count function to find frequency of given element in given list.

Below is the implementation:

# Python program to count the frequency of given element in list
given_list = ["Hello", "BTechGeeks", "This", "Is", "BTechGeeks"]

# given element to search
element = "BTechGeeks"
# using count function to count the given element in list
countelement = given_list.count(element)
# printing the count
print("The given element", element, "occurs",
      countelement, "times in the given list")

Output:

The given element BTechGeeks occurs 2 times in the given list

20)Python program to print list in reverse order

We will use slicing to print the given list in reverse order

Below is the implementation:

# Python program to print list in reverse order
given_list = ["Hello", "This", "Is", "BTechGeeks"]
# printing the list before reversing
print("printing the list before reversing :")
print(given_list)
# reversing the given list
given_list = given_list[::-1]
# printing the list after reversing
print("printing the list after reversing :")
print(given_list)

Output:

printing the list before reversing :
['Hello', 'This', 'Is', 'BTechGeeks']
printing the list after reversing :
['BTechGeeks', 'Is', 'This', 'Hello']

21)Python program to Print odd indexed elements in given list

We will use slicing to print the odd indexed elements in the given list .

Below is the implementation:

# Python program to Print odd indexed elements in given list
given_list = ["Hello", "This", "Is", "BTechGeeks", "Online", "Platform"]
#  odd indexed elements in given list using slicing
odd_elements = given_list[1::2]
# printing the odd indexed elements in given list
for i in odd_elements:
    print(i)

Output:

This
BTechGeeks
Platform

22)Python program for Adding two lists in Python(Appending two lists)

We will use the + operator to add(append) the two lists in python as below:

Below is the implementation:

# Python program for Adding two lists in Python(Appending two lists)
# given list 1
given_list1 = ["Hello", "This", "Is", "BTechGeeks", "Online", "Platform"]
# given list 2
given_list2 = ["Good", "Morning", "Python"]
# adding two lists using + operator
# we add all the elements of second list to first list
given_list1 = given_list1+given_list2
# print the result after adding the two lists
for i in given_list1:
    print(i)

Output:

Hello
This
Is
BTechGeeks
Online
Platform
Good
Morning
Python

23)Python program for finding frequency of each element in the given list

We will use the counter function to calculate the frequency of each element in the given list in efficient way.

Below is the implementation:

# Python program for finding frequency of each element in the given list
# importing counter function from collections
from collections import Counter
# given list which may contains the duplicates
given_list1 = ["Hello", "this", "is", "this", "is", "BTechGeeks", "Hello",
               "is", "is", "this", "BTechGeeks", "is", "this", "Hello", "python"]
# finding frequency of each elements using Counter() function
freqcyCounter = Counter(given_list1)
# printing the frequency of each element
for key in freqcyCounter:
    # frequency of the respective key
    count = freqcyCounter[key]
    # print the element and its frequency
    print("The element", key, "Has frequency =", count)

Output:

The element Hello Has frequency = 3
The element this Has frequency = 4
The element is Has frequency = 5
The element BTechGeeks Has frequency = 2
The element python Has frequency = 1

24)Python program for printing all distinct elements in given list

We will use counter function and print all the keys in it

Below is the implementation:

# Python program for printing all distinct elements in given list
# importing counter function from collections
from collections import Counter
# given list which may contains the duplicates
given_list1 = ["Hello", "this", "is", "this", "is", "BTechGeeks", "Hello",
               "is", "is", "this", "BTechGeeks", "is", "this", "Hello", "python"]
# finding frequency of each elements using Counter() function
freqcyCounter = Counter(given_list1)
# printing the distinct elements of the given list
print("printing the distinct elements of the given list :")
for key in freqcyCounter:
    print(key)

Output:

printing the distinct elements of the given list :
Hello
this
is
BTechGeeks
python

25)Python program to Print even indexed elements in given list

We will use slicing to print the even indexed elements in the given list .

Below is the implementation:

# Python program to Print even indexed elements in given list
given_list = ["Hello", "This", "Is", "BTechGeeks", "Online", "Platform"]
#  odd indexed elements in given list using slicing
odd_elements = given_list[::2]
# printing the even indexed elements in given list
print("printing the even indexed elements in given list :")
for i in odd_elements:
    print(i)

Output:

printing the even indexed elements in given list :
Hello
Is
Online

26)Python program to Print the given list elements in the same line

We have two methods to print the given lists elements in the same line

i)Using end 

Below is the implementation:

# Python program to Print the given list elements in the same line
given_list = ["Hello", "This", "Is", "BTechGeeks", "Online", "Platform"]

# Traveersing the list using for loop
# printing the given list elements
print("printing the given list elements :")
for element in given_list:
    print(element, end=" ")

Output:

printing the given list elements :
Hello This Is BTechGeeks Online Platform

ii)Using * operator

We can use * operator to print all the elements of given list in single line

Below is the implementation:

# Python program to Print the given list elements in the same line
given_list = ["Hello", "This", "Is", "BTechGeeks", "Online", "Platform"]
# printing the given list elements
print("printing the given list elements :")
print(*given_list)

Output:

printing the given list elements :
Hello This Is BTechGeeks Online Platform

27)Python program to count distinct characters in the given string

We will use counter function and print all the keys in it to print all distinct characters in given string

Below is the implementation:

# Python program to count distinct characters in the given string
# importing counter function from collections
from collections import Counter
# given string
string = "Hello@--472BtechGeeks!!;<>?"
# using counter function
distchars = Counter(string)
# Traversing through distchars dictionary
# printing the distinct characters in given string
print("printing the distinct characters in given string", string)
for key in distchars:
    print(key)

Output:

printing the distinct characters in given string Hello@--472BtechGeeks!!;<>?
H
e
l
o
@
-
4
7
2
B
t
c
h
G
k
s
!
;
<
>
?

28)Python program to Sort the given list elements in descending order

We will use the sort() and reverse=True to sort the given list in descending order

Below is the implementation:

# Python program to sort the given list in descending order
given_list = ["Hello", "This", "Is", "BTechGeeks", "online", "platform"]
# printing the list before sorting
print("Before sorting the list given list :")
for i in given_list:
    print(i)
# sorting the given list using sort() function
given_list.sort(reverse=True)
# printing the list after sorting
print("after sorting the list given list  in descending order:")
for i in given_list:
    print(i)

Output:

Before sorting the list given list :
Hello
This
Is
BTechGeeks
online
platform
after sorting the list given list  in descending order:
platform
online
This
Is
Hello
BTechGeeks

29)Python program to print character if ascii value is given

We will use chr function to print character if ascii value is given

Below is the implementation:

# Python program to print character if ascii value is given
# given ascii value
givenvalue = 104
# getting the character having given ascii value
character = chr(givenvalue)
# printing the character having given ascii value
print("The character which is having ascii value", givenvalue, "=", character)

Output:

The character which is having ascii value 104 = h

30)Python program to split the given number into list of digits

We will use map and list function to split the given number into list of digits

Below is the implementation:

# Python program to split the given number into list of digits
# given number
numb = 123883291231775637829
# converting the given number to string
strnu = str(numb)
# splitting the given number into list of digits using map and list functions
listDigits = list(map(int, strnu))
# print the list of digits of given number
print(listDigits)

Output:

[1, 2, 3, 8, 8, 3, 2, 9, 1, 2, 3, 1, 7, 7, 5, 6, 3, 7, 8, 2, 9]

31)Python program to split the given string into list of characters

We will use the list() function to split the given string into list of characters

Below is the implementation:

# Python program to split the given string into list of characters
# given string
string = "HellothisisBtechGeeks"
# splitting the string into list of characters
splitstring = list(string)
# print the list of characters of the given string
print(splitstring)

Output:

['H', 'e', 'l', 'l', 'o', 't', 'h', 'i', 's', 'i', 's', 'B', 't', 'e', 'c', 'h', 'G', 'e', 'e', 'k', 's']

Here the string is converted into a list of characters.

Objectives to Practice Python Programming for Class XII Computer Science CBSE Exam

  • Students should have the understanding power to implement functions and recursion concepts while programming.
  • They study the topics of file handling and utilize them respectively to read and write files as well as other options.
  • Learn how to practice efficient concepts in algorithms and computing.
  • Also, they will be proficient to create Python libraries and utilizing them in different programs or projects.
  • Can learn SQL and Python together with their connectivity.
  • Students can also understand the basics of computer networks.
  • Furthermore, they will have the ability to practice fundamental data structures such as Stacks and Queues.

Must Check: CBSE Class 12 Computer Science Python Syllabus

FAQs on Python Practical Programming for 12th Class CBSE

1. From where students can get the list of python programs for class 12?

Students of class 12 CBSE can get the list of python practical programs with output from our website @ Btechgeeks.com

2. How to download a class 12 CBSE Computer Science practical file on python programming?

You can download CBSE 12th Class Computer science practical file on python programming for free from the above content provided in this tutorial.

3. What is the syllabus for class 12 python programming?

There are 3 chapters covered in the computer science syllabus of class 12 python programs to learn and become pro in it.

  1. Computational Thinking and Programming – 2
  2. Computer Networks
  3. Database Management

Python Programs for Class 12 | Python Practical Programs for Class 12 Computer Science Read More »