Python

Program to Find the Cumulative Sum of a List

Python Program to Find the Cumulative Sum of a List using Different Methods | How to Calculate Cumulative Sum in Python with Examples?

The best and excellent way to learn a java programming language is by practicing Simple Java Program Examples as it includes basic to advanced levels of concepts.

Are you searching everywhere for a Program to Print the Cumulative Sum of Elements in a List? Then, this is the right place as it gives you a clear idea of what is meant by lists, the cumulative sum, different methods for finding the cumulative sum of numbers in a list, etc. Learn the simple codes for finding the cumulative sum of a list in python provided with enough examples and make the most out of them to write new codes on your own.

Lists in Python

Python’s built-in container types are List and Tuple. Objects of both classes can store various additional objects that can be accessed via index. Lists and tuples, like strings, are sequence data types. Objects of different types can be stored in a list or a tuple.

A list is an ordered collection of objects (of the same or distinct types) separated by commas and surrounded by square brackets.

Cumulative Sum

The cumulative total denotes “how much thus far” The cumulative sum is defined as the sum of a given sequence that grows or increases with successive additions. The growing amount of water in a swing pool is a real-world illustration of a cumulative accumulation.

Given a list, the task is to find the cumulative sum of the given list in python

Cumulative Sum in Python Examples

Example 1:

Input:

given list = [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421]

Output:

The given list before calculating cumulative sum [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421] 
The given list before calculating cumulative sum [34, 79, 91, 113, 146, 221, 231, 329, 551, 1550, 2573, 34994]

Example 2:

Input:

given list =[78, 45, 26, 95, 1, 2, 45, 13, 29, 39, 49, 68, 57, 13, 1, 2, 3, 1000, 2000, 100000]

Output:

The given list before calculating cumulative sum [78, 45, 26, 95, 1, 2, 45, 13, 29, 39, 49, 68, 57, 13, 1, 2, 3, 1000,
 2000, 100000]
The given list before calculating cumulative sum [78, 123, 149, 244, 245, 247, 292, 305, 334, 373, 422, 490, 547,
560, 561, 563, 566, 1566, 3566, 103566]

How to find the Cumulative Sum of Numbers in a List?

There are several ways to find the Cumulative sum in python some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using Count Variable and for loop (Static Input)

Approach:

  • Give the list input as static
  • Take a variable that stores the sum and initialize it with 0.
  • Take an empty list say cumulative list which stores the cumulative sum.
  • Using the for loop, repeat a loop length of the given list of times.
  • Calculate the sum till i th index using Count variable.
  • Append this count to the cumulative list using the append() function.
  • Print the cumulative list.

Write a Program to find the Cummulative Sum in a List?

# given list
given_list = [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421]
# Take a variable which stores the sum and initialize it with 0.
countsum = 0
# Take a empty list say cumulativelist which stores the cumulative sum.
cumulativelist = []
# calculating the length of given list
length = len(given_list)
# Using the for loop, repeat a loop length of the given list of times.
for i in range(length):
    # Calculate the sum till i th index using Count variable
    # increasing the count with the list element
    countsum = countsum+given_list[i]
    # Append this count to the cumulativelist  using append() function.
    cumulativelist.append(countsum)
# printing the given list  before calculating cumulative sum
print("The given list before calculating cumulative sum ", given_list)
# printing the list  after calculating cumulative su
print("The given list before calculating cumulative sum ", cumulativelist)

Python Program to Find the Cumulative Sum of a List using Count Variable and For Loop(Static Input)

Output:

The given list before calculating cumulative sum  [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421]
The given list before calculating cumulative sum  [34, 79, 91, 113, 146, 221, 231, 329, 551, 1550, 2573, 34994]

Method #2:Using Count Variable and for loop (User Input)

Approach:

  • Scan the given separated by spaces using a map, list, and split functions.
  • Take a variable that stores the sum and initialize it with 0.
  • Take an empty list say cumulative list which stores the cumulative sum.
  • Using the for loop, repeat a loop length of the given list of times.
  • Calculate the sum till i th index using Count variable.
  • Append this count to the cumulative list using the append() function.
  • Print the cumulative list.

Below is the implementation:

# Scan the given separated by spaces using map, list and split functions.
given_list = list(map(int, input(
    'enter some random numbers to the list separated by spaces = ').split()))
# Take a variable which stores the sum and initialize it with 0.
countsum = 0
# Take a empty list say cumulativelist which stores the cumulative sum.
cumulativelist = []
# calculating the length of given list
length = len(given_list)
# Using the for loop, repeat a loop length of the given list of times.
for i in range(length):
    # Calculate the sum till i th index using Count variable
    # increasing the count with the list element
    countsum = countsum+given_list[i]
    # Append this count to the cumulativelist  using append() function.
    cumulativelist.append(countsum)
# printing the given list  before calculating cumulative sum
print("The given list before calculating cumulative sum ", given_list)
# printing the list  after calculating cumulative su
print("The given list before calculating cumulative sum ", cumulativelist)

Python Program for finding the Cumulative Sum of a List using Loop Count Variable and for Loop(User Input)

Output:

enter some random numbers to the list separated by spaces = 78 45 26 95 1 2 45 13 29 39 49 68 57 13 1 2 3 1000 2000 100000
The given list before calculating cumulative sum [78, 45, 26, 95, 1, 2, 45, 13, 29, 39, 49, 68, 57, 13, 1, 2, 3, 1000,
2000, 100000]
The given list before calculating cumulative sum [78, 123, 149, 244, 245, 247, 292, 305, 334, 373, 422, 490, 547,
560, 561, 563, 566, 1566, 3566, 103566]

Method #3:Using Slicing (Static Input)

Approach:

  • Give the list input as static
  • Take an empty list say cumulative list which stores the cumulative sum.
  • Using the for loop, repeat a loop length of the given list of times.
  • Calculate the sum till ith index using slicing and sum function.
  • Append this count to the cumulative list using the append() function.
  • Print the cumulative list.

Below is the implementation:

# given list
given_list = [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421]
# Take a empty list say cumulativelist which stores the cumulative sum.
cumulativelist = []
# calculating the length of given list
length = len(given_list)
# Using the for loop, repeat a loop length of the given list of times.
for i in range(length):
    # Calculate the sum till i th index using slicing
    countsum = sum(given_list[:i+1])
    # Append this count to the cumulativelist  using append() function.
    cumulativelist.append(countsum)
# printing the given list  before calculating cumulative sum
print("The given list before calculating cumulative sum ", given_list)
# printing the list  after calculating cumulative su
print("The given list before calculating cumulative sum ", cumulativelist)

Python Program for finding the Cumulative Sum of a List Using Slicing(Static Input)

Output:

The given list before calculating cumulative sum  [34, 45, 12, 22, 33, 75, 10, 98, 222, 999, 1023, 32421]
The given list before calculating cumulative sum  [34, 79, 91, 113, 146, 221, 231, 329, 551, 1550, 2573, 34994]
Program to Calculate BMI

Python Program to Calculate BMI

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

Body Mass Index (BMI) :

The “Quetelet Index ” is another name for the BMI. It is a value calculated using a person’s weight (in kg) and height (in meters), whether male or female. The body mass index (BMI) is calculated by multiplying the body mass by the square of the body height. BMI is measured in kilograms per square meter.

The BMI is used to determine if a person is underweight, normal weight, overweight, or obese. A table with data from the four categories listed above is provided below.

BMI Weight Status
Below 18.5 Underweight
18.5 – 24.9 Normal or Healthy Weight
25.0 – 29.9 Overweight
30.0 and Above Obese

Formula to calculate BMI :

BMI = [mass/(height*height)]

where mass is the body’s mass in kilograms and

height is the body’s height in meters

Given Height, Weight and the task is to calculate BMI for given input values.

Examples:

Example1:

Input:

Given Height = 2.5
Given Weight = 50

Output:

The BMI for the above given values =  8.0
Health status of a person for the above obtained BMI = The person is Underweight

Example2:

Input:

Given Height =  1.5
Given Weight =  70

Output:

The BMI for the above given values =  31.11111111111111
Health status of a person for the above obtained BMI = The person is Suffering from Obesity

Program to Calculate BMI

Below are the ways to Calculate BMI for Given values of height, weight.

Method #1: Using Mathematical Formula (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.
  • Calculate the BMI Value using the above given mathematical formula and store it in another variable.
  • Check If the obtained BMI value is less than 18.5 using the if conditional statement.
  • If it is True, Print “The person is Underweight”.
  • Check If the obtained BMI  is greater than or equal to 18.5 and less than 24.9 using elif conditional statement.
  • If it is True, Print “The person is Healthy”.
  • Check If the obtained BMI  is greater than or equal to 24.9 and less than 30 using elif conditional statement.
  • If it is True, Print “The person is Overweight”.
  • Check If the obtained BMI  is greater than or equal to 30 using elif conditional statement.
  • If it is True, Print “The person is Suffering from Obesity”
  • The Exit of the program.

Below is the implementation:

# Give the first number as static input and store it in a variable.
gvn_heigt = 2.5
# Give the second number as static input and store it in another variable.
gvn_weigt = 50
# Calculate the BMI Value using the above given mathematical formula and
# store it in another variable.
Bmi_vlue = gvn_weigt/(gvn_heigt**2)
print("The BMI for the above given values = ", format(Bmi_vlue))
print("Health status of a person for the above obtained BMI = ", end="")
# Check If the obtained BMI value is less than 18.5 using if conditional statement .
# If it is True, Print "The person is Underweight".
if (Bmi_vlue < 18.5):
    print("The person is Underweight")
# Check If the obtained BMI  is greater than or equal to 18.5 and less than 24.9 using 
# elif conditional statement .
# If it is True, Print "The person is Healthy".
elif (Bmi_vlue >= 18.5 and Bmi_vlue < 24.9):
    print("The person is Healthy")
# Check If the obtained BMI  is greater than or equal to 24.9 and less than 30 using 
# elif conditional statement .
# If it is True, Print "The person is Overweight".
elif (Bmi_vlue >= 24.9 and Bmi_vlue < 30):
    print("The person is Overweight")
# Check If the obtained BMI  is greater than or equal to 30 using 
# elif conditional statement .
# If it is True, Print "The person is Suffering from Obesity"
elif (Bmi_vlue >= 30):
    print("The person is Suffering from Obesity")

Output:

The BMI for the above given values =  8.0
Health status of a person for the above obtained BMI = The person is Underweight

Method #2: Using Mathematical Formula (User input)

Approach:

  • Give the first number as user input using float(input()) and store it in a variable.
  • Give the second number as user input using float(input()) and store it in another variable.
  • Calculate the BMI Value using the above given mathematical formula and store it in another variable.
  • Check If the obtained BMI value is less than 18.5 using the if conditional statement.
  • If it is True, Print “The person is Underweight”.
  • Check If the obtained BMI  is greater than or equal to 18.5 and less than 24.9 using elif conditional statement.
  • If it is True, Print “The person is Healthy”.
  • Check If the obtained BMI  is greater than or equal to 24.9 and less than 30 using elif conditional statement.
  • If it is True, Print “The person is Overweight”.
  • Check If the obtained BMI  is greater than or equal to 30 using elif conditional statement.
  • If it is True, Print “The person is Suffering from Obesity”
  • The Exit of the program.

Below is the implementation:

# Give the first number as user input using float(input()) and store it in a variable.
gvn_heigt = float(input("Enter some Random Number = "))
# Give the second number as user input float(input()) and store it in another variable.
gvn_weigt = float(input("Enter some Random Number = "))
# Calculate the BMI Value using the above given mathematical formula and
# store it in another variable.
Bmi_vlue = gvn_weigt/(gvn_heigt**2)
print("The BMI for the above given values = ", format(Bmi_vlue))
print("Health status of a person for the above obtained BMI = ", end="")
# Check If the obtained BMI value is less than 18.5 using if conditional statement .
# If it is True, Print "The person is Underweight".
if (Bmi_vlue < 18.5):
    print("The person is Underweight")
# Check If the obtained BMI  is greater than or equal to 18.5 and less than 24.9 using 
# elif conditional statement .
# If it is True, Print "The person is Healthy".
elif (Bmi_vlue >= 18.5 and Bmi_vlue < 24.9):
    print("The person is Healthy")
# Check If the obtained BMI  is greater than or equal to 24.9 and less than 30 using 
# elif conditional statement .
# If it is True, Print "The person is Overweight".
elif (Bmi_vlue >= 24.9 and Bmi_vlue < 30):
    print("The person is Overweight")
# Check If the obtained BMI  is greater than or equal to 30 using 
# elif conditional statement .
# If it is True, Print "The person is Suffering from Obesity"
elif (Bmi_vlue >= 30):
    print("The person is Suffering from Obesity")

Output:

Enter some Random Number = 1.5
Enter some Random Number = 70
The BMI for the above given values = 31.11111111111111
Health status of a person for the above obtained BMI = The person is Suffering from Obesity

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.

Program to Read Two Numbers and Print Their Quotient and Remainder

Python Program to Read Two Numbers and Print Their Quotient and Remainder

Don’t stop learning now. Get hold of all the important Java fundamentals with the Simple java program example guide and practice well.

Given two numbers , the task is to print their quotient and Remainder in  Python.

Examples:

i)Floating Division

Example1:

Input:

first number =45
second number =17

Output:

The value of quotient after dividing 45 / 17 = 2.6470588235294117
The value of remainder after dividing 45 / 17 = 11

ii)Integer Division

Input:

first number =45
second number =17

Output:

The value of quotient after dividing 45 / 17 = 2
The value of remainder after dividing 45 / 17 = 11

Program to Read Two Numbers and Print Their Quotient and Remainder in  Python

Below are the ways to print the quotient and Remainder:

1)Using / and % modulus operator in Python (User Input separated by new line, Float Division)

Approach:

  • Scan the given two numbers using int(input()) and store them in two separate variables.
  • Calculate the quotient by using the syntax first number /second number and store it in a variable.
  • Calculate the remainder by using the syntax first number %second number and store it in a variable.
  • Print the above two variables which are the result of the program
  • Exit of Program.

Below is the implementation:

# scanning the given two numbers using int(input()) function
# first number
numb1 = int(input("Enter some random number = "))
# second number
numb2 = int(input("Enter some random number = "))
# Calculate the quotient by using the syntax first number /second number
# and store it in a variable.
quotie = numb1/numb2
# Calculate the remainder by using the syntax first number %second number
# and store it in a variable.
remain = numb1 % numb2
# Print the above two variables which are the result of the program
print("The value of quotient after dividing", numb1, "/", numb2, " = ", quotie)
print("The value of remainder after dividing",
      numb1, "/", numb2, " = ", remain)

Output:

Enter some random number = 86
Enter some random number = 12
The value of quotient after dividing 86 / 12 = 7.166666666666667
The value of remainder after dividing 86 / 12 = 2

2)Using / and % modulus operator in Python (User Input separated by spaces , Float Division)

Approach:

  • Scan the given two numbers using map and split() functions to store them in two separate variables.
  • Calculate the quotient by using the syntax first number /second number and store it in a variable.
  • Calculate the remainder by using the syntax first number %second number and store it in a variable.
  • Print the above two variables which are the result of the program
  • Exit of Program.

Below is the implementation:

# Scan the given two numbers using map and split() functions
# to store them in two separate variables.
numb1, numb2 = map(int, input("Enter two random numbers separated by spaces = ").split())
# Calculate the quotient by using the syntax first number /second number
# and store it in a variable.
quotie = numb1/numb2
# Calculate the remainder by using the syntax first number %second number
# and store it in a variable.
remain = numb1 % numb2
# Print the above two variables which are the result of the program
print("The value of quotient after dividing", numb1, "/", numb2, " = ", quotie)
print("The value of remainder after dividing",
      numb1, "/", numb2, " = ", remain)

Output:

Enter two random numbers separated by spaces = 45 17
The value of quotient after dividing 45 / 17 = 2.6470588235294117
The value of remainder after dividing 45 / 17 = 11

3)Using // and % modulus operator in Python (User Input separated by spaces , Integer Division)

Approach:

  • Scan the given two numbers using map and split() functions to store them in two separate variables.
  • Calculate the integer quotient by using the syntax first number //second number and store it in a variable.
  • Calculate the remainder by using the syntax first number %second number and store it in a variable.
  • Print the above two variables which are the result of the program
  • Exit of Program.

Below is the implementation:

# Scan the given two numbers using map and split() functions
# to store them in two separate variables.
numb1, numb2 = map(int, input("Enter two random numbers separated by spaces = ").split())
# Calculate the quotient by using the syntax first number /second number
# and store it in a variable.
quotie = numb1//numb2
# Calculate the remainder by using the syntax first number %second number
# and store it in a variable.
remain = numb1 % numb2
# Print the above two variables which are the result of the program
print("The value of quotient after dividing", numb1, "/", numb2, " = ", quotie)
print("The value of remainder after dividing",
      numb1, "/", numb2, " = ", remain)

Output:

Enter two random numbers separated by spaces = 45 17
The value of quotient after dividing 45 / 17 = 2
The value of remainder after dividing 45 / 17 = 11

Related Programs:

Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

Python Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

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.

List in Python :

The list data type is one of the most often used data types in Python. The square brackets [ ] easily identify a Python List. Lists are used to store data items, with each item separated by a comma (,). A Python List can include data elements of any data type, including integers and Booleans.

One of the primary reasons that lists are so popular is that they are mutable. Any data item in a List can be replaced by any other data item if it is mutable. This distinguishes Lists from Tuples, which are likewise used to store data elements but are immutable.

Given a list the task is to print the sum of all positive even numbers ,odd numbers and negative numbers in the given list in python.

Examples:

Example1:

Input:

given list =[23, 128, -4, -19, 233, 726, 198, 199, 203, -13]

Output:

The sum of all positive even numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 1052
The sum of all positive odd numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 658
The sum of all positive negative numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = -36

Example2:

Input:

given list =[-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]

Output:

The sum of all positive even numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]  = 444 
The sum of all positive odd numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  210 
The sum of all positive negative numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  -36

Python Program to Print Sum of Negative Numbers, Positive Even Numbers and Positive Odd numbers in a List

Below are the ways to print the sum of all positive even numbers ,odd numbers and negative numbers in the given list in python.

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1:Using append() and Conditional Statements (User Input separated by newline)

Approach:

  • Take the user’s input on the number of elements to include in the list.
  •  Using a for loop, Scan the elements from the user and append them to a list.
  • Using a for loop, retrieve the elements from the list one at a time, determine whether they are positive odd, positive even or negative numbers and append them to various lists say posEven, posOdd ,negNum.
  • Calculate the sum of posEven, posOdd ,negNum and print them
  • Exit of program

Below is the implementation:

# scanning the total number of elements of the given list
totalCount = int(
    input("Enter the total number of elements of the given list = "))
# Taking a empty list
given_list = []
# Using for loop to loop totalCount times
for i in range(totalCount):
    eleme = int(input("Enter some random element(integer) = "))
    given_list.append(eleme)
# Taking three empty lists which stores positive
# ven numbers ,positive odd numbers and negative numbers
posEven = []
posOdd = []
negNum = []
# Traversing the list using for loop
for element in given_list:
    # checking if the number is greater than 0
    if(element > 0):
        # if the element is even then add this element to posEven using append() function
        if(element % 2 == 0):
            posEven.append(element)
    # if the element is even then add this element to posOdd using append() function
        else:
            posOdd.append(element)
    # else if the number is less than 0 then add to negNum list using append() function
    else:
        negNum.append(element)
        

# Calculating sum
posEvensum = sum(posEven)
posOddsum = sum(posOdd)
negNumsum = sum(negNum)
# printing the respectve sum's
print("The sum of all positive even numbers in thee given list = ",
      given_list, posEvensum)
print("The sum of all positive odd numbers in thee given list = ", given_list, posOddsum)
print("The sum of all positive negative numbers in thee given list = ",
      given_list, negNumsum)

Output:

Enter the total number of elements of the given list = 10
Enter some random element(integer) = -4
Enter some random element(integer) = 23
Enter some random element(integer) = 12
Enter some random element(integer) = -13
Enter some random element(integer) = 234
Enter some random element(integer) = 198
Enter some random element(integer) = 55
Enter some random element(integer) = -19
Enter some random element(integer) = 87
Enter some random element(integer) = 45
The sum of all positive even numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45]  = 444
The sum of all positive odd numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  210
The sum of all positive negative numbers in thee given list [-4, 23, 12, -13, 234, 198, 55, -19, 87, 45] =  -36

Method #2:Using append() and Conditional Statements (Static Input separated by spaces)

Approach:

  • Given the input of the list as static.
  • Using a for loop, retrieve the elements from the list one at a time, determine whether they are positive odd, positive even or negative numbers and append them to various lists say posEven, posOdd ,negNum.
  • Calculate the sum of posEven, posOdd ,negNum and print them
  • Exit of program

Below is the implementation:

# given list
given_list = [23, 128, -4, -19, 233, 726, 198, 199, 203, -13]
# Taking three empty lists which stores positive
# even numbers ,positive odd numbers and negative numbers
posEven = []
posOdd = []
negNum = []
# Traversing the list using for loop
for element in given_list:
    # checking if the number is greater than 0
    if(element > 0):
        # if the element is even then add this element to posEven using append() function
        if(element % 2 == 0):
            posEven.append(element)
    # if the element is even then add this element to posOdd using append() function
        else:
            posOdd.append(element)
    # else if the number is less than 0 then add to negNum list using append() function
    else:
        negNum.append(element)


# Calculating sum
posEvensum = sum(posEven)
posOddsum = sum(posOdd)
negNumsum = sum(negNum)
# printing the respectve sum's
print("The sum of all positive even numbers in thee given list ",
      given_list, "=", posEvensum)
print("The sum of all positive odd numbers in thee given list ",
      given_list, "=", posOddsum)
print("The sum of all positive negative numbers in thee given list ",
      given_list, "=", negNumsum)

Output:

The sum of all positive even numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 1052
The sum of all positive odd numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = 658
The sum of all positive negative numbers in thee given list  [23, 128, -4, -19, 233, 726, 198, 199, 203, -13] = -36

Related Programs:

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:

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.

Program to invert a Dictionary

Python Program to invert a Dictionary

In the previous article, we have discussed Python Program to Check if two Lines are Parallel or Not
Dictionary in python:

Python includes a class dictionary, which is typically defined as a set of key-value pairs. In Python, inverting a dictionary means swapping the key and value in the dictionary.

One thing is certain: complexity can be found in all of the different ways of storing key-value pairs. That is why dictionaries are used.

Python dictionaries are mutable collections of things that contain key-value pairs. The dictionary contains two main components: keys and values. These keys must be single elements, and the values can be of any data type, such as list, string, integer, tuple, and so on. The keys are linked to their corresponding values. In other words, the values can be retrieved using their corresponding keys.

A dictionary is created in Python by enclosing numerous key-value pairs in curly braces.

For example :

dictionary ={‘monday’:1, ‘tuesday’:2, ‘wednesday’:3}

The output after inverting the dictionary is { 1: [‘monday’] , 2: [‘tuesday’] , 3: [‘wednesday’] }

Given a dictionary, and the task is to invert the given dictionary.

Examples:

Example1:

Input:

Given dictionary = {10: 'jan', 20: 'feb', 30: 'march', 40: 'April', 50: 'may'}

Output:

The inverse of the given dictionary =  {'jan': [10], 'feb': [20], 'march': [30], 'April': [40], 'may': [50]}

Example 2:

Input:

Given dictionary = {'monday': 1, 'tuesday': 2, 'wednesday': 3}

Output:

The inverse of the given dictionary = {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Program to invert a Dictionary in Python

Below are the ways to invert a given dictionary

Method #1: Using For Loop (Static Input)

Approach:

  • Give the dictionary as static input and store it in a variable.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Give the dictionary as static input and store it in a variable.
gvn_dict = {'monday': 1, 'tuesday': 2, 'wednesday': 3}
# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

The inverse of the given dictionary =  {1: ['monday'], 2: ['tuesday'], 3: ['wednesday']}

Method #2: Using For Loop (User Input)

Approach:

  • Take a dictionary and initialize it with an empty dictionary using dict() or {}.
  • Give the number of keys as user input using int(input()) and store it in a variable.
  • Loop till the given number of keys using for loop.
  • Inside the for loop scan the key and value as user input using input(), split() functions, and store them in two separate variables.
  • Initialize the key with the value of the dictionary.
  • Create a new empty dictionary say ” inverse_dict” and store it in another variable.
  • Iterate in the above dictionary using the dictionary. items() and for loop.
  • Check if the value is present in the above declared  ” inverse_dict” using the if conditional statement and the ‘in’ keyword.
  • If the statement is true, then append the value to the “inverse_dict” dictionary using the append() function.
  • Else assign the value to the key.
  • Print the above declared ” inverse_dict” variable to get the inverse of the given dictionary.
  • The Exit of the program.

Below is the implementation:

# Take a dictionary and initialize it with an empty dictionary using dict() or {}.
gvn_dict = {}
# Give the number of keys as user input using int(input()) and store it in a variable.
numb_of_kys = int(
    input('Enter some random number of keys of the dictionary = '))
# Loop till the given number of keys using for loop.
for p in range(numb_of_kys):
        # Inside the for loop scan the key and value as
    # user input using input(),split() functions
    # and store them in two separate variables.
    keyy, valuee = input(
        'Enter key and value separated by spaces = ').split()
    # Initialize the key with the value of the dictionary.
    gvn_dict[keyy] = valuee

# Create a new empty dictionary say " inverse_dict" and store it in another variable.
inverse_dict = {}
# Iterate in the above dictionary using the dictionary. items() and for loop.
for key, value in gvn_dict.items():
  # Check if the value is present in the above declared  " inverse_dict" using
  # the if conditional statement and the 'in' keyword.
    if value in inverse_dict:
     # If the statement is true, then append the value to the "inverse_dict" dictionary
     # using the append() function.
        inverse_dict[value].append(key)
    else:
     # Else assign the value to the key.
        inverse_dict[value] = [key]
  # Print the above declared " inverse_dict" variable to get the inverse of the
  # given dictionary.
print("The inverse of the given dictionary = ", inverse_dict)

Output:

Enter some random number of keys of the dictionary = 5
Enter key and value separated by spaces = hello 785
Enter key and value separated by spaces = this 100
Enter key and value separated by spaces = is 900
Enter key and value separated by spaces = btechgeeks 500
Enter key and value separated by spaces = python 400
The inverse of the given dictionary = {'785': ['hello'], '100': ['this'], '900': ['is'], '500': ['btechgeeks'], '400': ['python']}

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.

Program to Find the Greatest Digit in a Number.

Python Program to Find the Greatest Digit in a Number.

In the previous article, we have discussed Python Program for Comma-separated String to Tuple
Given a number, and the task is to find the greatest digit in a given number.

Example: Let the number is 149.

The greatest digit in a given number is ‘9’

Examples:

Example1:

Input:

Given number = 639

Output:

The maximum digit in given number { 639 } =  9

Example2:

Input:

Given number = 247

Output:

The maximum digit in given number { 247 } =  7

Program to Find the Greatest Digit in a Number.

Below are the ways to find the greatest digit in a given number.

Method #1: Using list() Function (Static input)

Approach:

  • Give the number as static input and store it in a variable.
  • Convert the given number into the string using the str() function and store it in another variable.
  • Convert the above-obtained string number into a list of digits using the built-in list() method and store it in another variable.
  • Find the maximum list of digits using the built-in max() function and store it in another variable.
  • Print the greatest digit in a given number.
  • The Exit of the program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvn_num = 154
# Convert the given number into string using str() function and
# store it in another variable. 
str_numbr = str(gvn_num)
# Convert the above obtained string number into list of digits using bulit-in list()
# method and store it in another variable.
lst = list(str_numbr)
# Find the maximum of list of digits using bulit-in max() function
# and store it in another variable.
maxim_digit = max(lst)
# Print the greatest digit in a given number.
print("The maximum digit in given number {", gvn_num, "} = ", maxim_digit)

Output:

The maximum digit in given number { 154 } =  5

Method #2: Using list() Function (User input)

Approach:

  • Give the number as user input using the int(input()) function and store it in a variable.
  • Convert the given number into the string using the str() function and store it in another variable.
  • Convert the above-obtained string number into a list of digits using the built-in list() method and store it in another variable.
  • Find the maximum list of digits using the built-in max() function and store it in another variable.
  • Print the greatest digit in a given number.
  • The Exit of the program.

Below is the implementation:

#Give the number as user input using int(input()) and store it in a variable.
gvn_num = int(input("Enter some random number = "))
# Convert the given number into string using str() function and
# store it in another variable. 
str_numbr = str(gvn_num)
# Convert the above obtained string number into list of digits using bulit-in list()
# method and store it in another variable.
lst = list(str_numbr)
# Find the maximum of list of digits using bulit-in max() function
# and store it in another variable.
maxim_digit = max(lst)
# Print the greatest digit in a given number.
print("The maximum digit in given number {", gvn_num, "} = ", maxim_digit)

Output:

Enter some random number = 183
The maximum digit in given number { 183 } = 8

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.

Program for Comma-separated String to Tuple

Python Program for Comma-separated String to Tuple

In the previous article, we have discussed Python Program to Shuffle Elements of a Tuple
Tuple in Python:

A tuple is an immutable list of objects. That means the elements of a tuple cannot be modified or changed while the program is running.

split() function:

Syntax: input string.split(seperator=None, maxsplit=-1)

It delimits the string with the separator and returns a list of words from it. The maxsplit parameter specifies the maximum number of splits that can be performed. If it is -1 or not specified, all possible splits are performed.

Example:  Given string =  ‘hello btechgeeks goodmorning’.split()

Output : [‘hello’, ‘btechgeeks’, ‘goodmorning’ ]

Given a string and the task is to find a tuple with a comma-separated string.

Examples:

Example 1:

Input: 

Given String = 'good, morning, btechgeeks'     (static input)

Output:

Given input String =  good, morning, btechgeeks
A tuple with comma-separated string is :  ('good', ' morning', ' btechgeeks')

Example 2:

Input:

Given String = hello, btechgeeks, 123        (user input)

Output:

A tuple with comma-separated string is : ('hello', ' btechgeeks', ' 123')

Program for Comma-separated String to Tuple

Below are the ways to find a tuple with a comma-separated string.

Method #1: Using split() Method (Static input)

Approach:

  • Give the string as static input and store it in a variable.
  • Print the above-given input string.
  • Split the given input string separated by commas using the split() function and convert it into a tuple.
  • Store it in another variable.
  • Print the tuple with a comma-separated string.
  • The Exit of the program.

Below is the implementation:

# Give the string as static input and store it in a variable.
gvn_str = 'good, morning, btechgeeks'
# Print the above-given input string.
print("Given input String = ", gvn_str)
# Split the given input string separated by commas using the split() function
# and convert it into a tuple.
# Store it in another variable.
tupl = tuple(gvn_str.split(","))
# Print the tuple with a comma-separated string.
print("A tuple with comma-separated string is : ", tupl)

Output:

Given input String =  good, morning, btechgeeks
A tuple with comma-separated string is :  ('good', ' morning', ' btechgeeks')

Method #2: Using split() Method (User input)

Approach:

  • Give the string as user input using the input() function and store it in a variable.
  • Print the above-given input string.
  • Split the given input string separated by commas using the split() function and convert it into a tuple.
  • Store it in another variable.
  • Print the tuple with a comma-separated string.
  • The Exit of the program.

Below is the implementation:

#Give the string as user input using the input() function and store it in a variable.
gvn_str = input("Enter some random string = ")
# Print the above-given input string.
print("Given input String = ", gvn_str)
# Split the given input string separated by commas using the split() function
# and convert it into a tuple.
# Store it in another variable.
tupl = tuple(gvn_str.split(","))
# Print the tuple with a comma-separated string.
print("A tuple with comma-separated string is : ", tupl)

Output:

Enter some random string = hello, btechgeeks, 123
Given input String = hello, btechgeeks, 123
A tuple with comma-separated string is : ('hello', ' btechgeeks', ' 123')

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.

Program to Clear the Rightmost Set Bit of a Number in C++ and Python

Program to Clear the Rightmost Set Bit of a Number in C++ and Python

In the previous article, we have discussed about C++ Program to Check if it is Sparse Matrix or Not. Let us learn Program to Clear the Rightmost Set Bit of a Number in C++ Program and Python.

Binary Representation of a Number:

Binary is a base-2 number system in which a number is represented by two states: 0 and 1. We can also refer to it as a true and false state. A binary number is constructed in the same way that a decimal number is constructed.

Examples:

Examples1:

Input:

given number=19

Output:

The given number before removing right most set bit : 
19
The given number after removing right most set bit : 
18

Examples2:

Input:

given number =18

Output:

The given number before removing right most set bit : 
18
The given number after removing right most set bit : 
16

Examples3:

Input:

given number=512

Output:

The given number before removing right most set bit : 
512
The given number after removing right most set bit : 
0

Program to Clear the Rightmost Set Bit of a Number in C++ and Python

There are several ways to clear the rightmost set Bit of a Number in C++ and Python some of them are:

Drive into Python Programming Examples and explore more instances related to python concepts so that you can become proficient in generating programs in Python Programming Language.

Method #1: Using Bitwise Operators in C++

Approach:

  • There is a function called clear rightmost set bit that is defined.
  • It accepts n as an argument and returns n with its rightmost set bit cleared.
  • This is accomplished by computing n & (n – 1) and returning the result.
  • (n – 1) equals n when all the rightmost successive 0s are flipped and the initial rightmost 1 is flipped.
  • As a result, n & (n – 1) equals n with the rightmost 1 cleared.

Below is the implementation of above approach:

#include <bits/stdc++.h>
using namespace std;
// function which removes the right most set bit in the
// given number
int clearRight(int numb)
{
    // clearing the right most set bit from
    // the given number and store it in the result
    int reslt = (numb) & (numb - 1);
    // returing the calculated result
    return reslt;
}

// main function
int main()
{
    // given number
    int numb = 19;

    cout << "The given number before removing right most "
            "set bit : "
         << numb << endl;
    // passing the given number to clearRight function
    // to remove the clear the rightmost setbit
    cout << "The given number after removing right most "
            "set bit : "
         << clearRight(numb) << endl;
    return 0;
}

Output:

The given number before removing right most set bit : 19
The given number after removing right most set bit : 18

Method #2: Using Bitwise Operators in Python

Approach:

  • There is a function called clear rightmost set bit that is defined.
  • It accepts n as an argument and returns n with its rightmost set bit cleared.
  • This is accomplished by computing n & (n – 1) and returning the result.
  • (n – 1) equals n when all the rightmost successive 0s are flipped and the initial rightmost 1 is flipped.
  • As a result, n & (n – 1) equals n with the rightmost 1 cleared.
  • We will implement the same function in python

Below is the implementation:

# function which removes the right most set bit in the
# given number


def clearRight(numb):
    # clearing the right most set bit from
    # the given number and store it in the result
    reslt = (numb) & (numb - 1)
    # returing the calculated result
    return reslt
# Driver Code


# given number
numb = 19

print("The given number before removing right most "
      "set bit : ")
print(numb)
# passing the given number to clearRight function
# to remove the clear the rightmost setbit
print("The given number after removing right most set bit : ")
print(clearRight(numb))

Output:

The given number before removing right most set bit : 
19
The given number after removing right most set bit : 
18

Related Programs: