Python

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.

BMIWeight Status
Below 18.5Underweight
18.5 – 24.9Normal or Healthy Weight
25.0 – 29.9Overweight
30.0 and AboveObese

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.

Python Program to Calculate BMI Read More »

Python Program to Calculate the Income Tax

Python Program to Calculate the Income Tax

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.

We will create a Python program that will assist us in calculating income tax based on certain conditions. Keep in mind that criteria are not fixed because income tax formats differ from country to country. In this code, I’m calculating income tax in Indian format.

Examples:

Example1:

Input:

Give Income = 670000

Output:

The tax for the income  670000 = 29500.0

Example2:

Input:

Give Income =1200000

Output:

The tax for the income 1200000 = 115000.0

Python Program to Calculate the Income Tax

Below are the ways to calculate the Income Tax in Python.

Method #1: Using If Statement (Static Input)

Approach:

Give the income as static input and store it in a variable.

Now we’ll place if and else statements here to complete our income tax calculating conditions, which are as follows,

If your income is less than or equivalent to Rs. 2,50,000, you will pay no tax.
If your income is less than or equal to Rs. 5,00,000, your tax will be 5% of your total income over Rs. 2,50,000.
If your income is less than or equal to Rs. 7,50,000, your tax rate will be 10% of your total income beyond Rs. 5,00,000, with an additional cost of Rs. 12,500.
If your income is less than or equivalent to Rs. 10,00,000, your tax rate will be 15% of your total income over Rs. 7,50,000, with an additional fee of Rs. 37,500.
If your income is less than or equal to Rs. 12,50,000, your tax rate will be 20% of your total income beyond Rs. 10,00,000, with an additional fee of Rs. 75,000.
If your income is less than or equal to Rs. 15,00,000, your tax rate will be 25% of your total income beyond Rs. 12,50,000, with an additional cost of Rs. 1,25,000.
If your income exceeds Rs. 15,00,000, you will be taxed at 30% of the excess, with an additional fee of Rs. 1,87,500.

Print the Tax.

The Exit of the Program.

Below is the implementation:

# Give the income as static input and store it in a variable.
givenincome = 670000
# We will use if and else statements here to complete our income tax calculating conditions,
# which are as follows,
# If your income is less than or equivalent to Rs. 2,50,000,the taxAmount=0.
if givenincome <= 250000:
    taxAmount = 0
# If your income is less than or equal to Rs. 5,00,000,
# the taxAmount will be 5% of your total income over Rs. 2,50,000.
elif givenincome <= 500000:
    taxAmount = (givenincome - 250000) * 0.05
# If your income is less than or equal to Rs. 7,50,000,
# your taxAmount rate will be 10% of your total income
# beyond Rs. 5,00,000, with an additional cost of Rs. 12,500.
elif givenincome <= 750000:
    taxAmount = (givenincome - 500000) * 0.10 + 12500
# If your income is less than or equivalent to Rs. 10,00,000,
# your taxAmount rate will be 15% of your total income over Rs. 7,50,000,
# with an additional fee of Rs. 37,500.
elif givenincome <= 1000000:
    taxAmount = (givenincome - 750000) * 0.15 + 37500
# If your income is less than or equal to Rs. 12,50,000,
# your taxAmount rate will be 20% of your total income beyond Rs. 10,00,000,
# with an additional fee of Rs. 75,000.
elif givenincome <= 1250000:
    taxAmount = (givenincome - 1000000) * 0.20 + 75000
# If your income is less than or equal to Rs. 15,00,000,
# your taxAmount rate will be 25% of your total income beyond Rs. 12,50,000,
# with an additional cost of Rs. 1,25,000.
elif givenincome <= 1500000:
    taxAmount = (givenincome - 1250000) * 0.25 + 125000
# If your income exceeds Rs. 15,00,000,
# you will be taxed at 30% of the excess, with an additional fee of Rs. 1,87,500.
else:
    taxAmount = (givenincome - 1500000) * 0.30 + 187500
# Print the Tax.
print('The tax for the income ', givenincome, '=', taxAmount)

Output:

The tax for the income  670000 = 29500.0

Method #2: Using For Loop (User Input)

Approach:

Give the income as user input using int(input()) and store it in a variable.

Now we’ll place if and else statements here to complete our income tax calculating conditions, which are as follows,

If your income is less than or equivalent to Rs. 2,50,000, you will pay no tax.
If your income is less than or equal to Rs. 5,00,000, your tax will be 5% of your total income over Rs. 2,50,000.
If your income is less than or equal to Rs. 7,50,000, your tax rate will be 10% of your total income beyond Rs. 5,00,000, with an additional cost of Rs. 12,500.
If your income is less than or equivalent to Rs. 10,00,000, your tax rate will be 15% of your total income over Rs. 7,50,000, with an additional fee of Rs. 37,500.
If your income is less than or equal to Rs. 12,50,000, your tax rate will be 20% of your total income beyond Rs. 10,00,000, with an additional fee of Rs. 75,000.
If your income is less than or equal to Rs. 15,00,000, your tax rate will be 25% of your total income beyond Rs. 12,50,000, with an additional cost of Rs. 1,25,000.
If your income exceeds Rs. 15,00,000, you will be taxed at 30% of the excess, with an additional fee of Rs. 1,87,500.

Print the Tax.

The Exit of the Program.

Below is the implementation:

# Give the income as user input using int(input()) and store it in a variable.
givenincome = int(input('Enter some random salary = '))
# We will use if and else statements here to complete our income tax calculating conditions,
# which are as follows,
# If your income is less than or equivalent to Rs. 2,50,000,the taxAmount=0.
if givenincome <= 250000:
    taxAmount = 0
# If your income is less than or equal to Rs. 5,00,000,
# the taxAmount will be 5% of your total income over Rs. 2,50,000.
elif givenincome <= 500000:
    taxAmount = (givenincome - 250000) * 0.05
# If your income is less than or equal to Rs. 7,50,000,
# your taxAmount rate will be 10% of your total income
# beyond Rs. 5,00,000, with an additional cost of Rs. 12,500.
elif givenincome <= 750000:
    taxAmount = (givenincome - 500000) * 0.10 + 12500
# If your income is less than or equivalent to Rs. 10,00,000,
# your taxAmount rate will be 15% of your total income over Rs. 7,50,000,
# with an additional fee of Rs. 37,500.
elif givenincome <= 1000000:
    taxAmount = (givenincome - 750000) * 0.15 + 37500
# If your income is less than or equal to Rs. 12,50,000,
# your taxAmount rate will be 20% of your total income beyond Rs. 10,00,000,
# with an additional fee of Rs. 75,000.
elif givenincome <= 1250000:
    taxAmount = (givenincome - 1000000) * 0.20 + 75000
# If your income is less than or equal to Rs. 15,00,000,
# your taxAmount rate will be 25% of your total income beyond Rs. 12,50,000,
# with an additional cost of Rs. 1,25,000.
elif givenincome <= 1500000:
    taxAmount = (givenincome - 1250000) * 0.25 + 125000
# If your income exceeds Rs. 15,00,000,
# you will be taxed at 30% of the excess, with an additional fee of Rs. 1,87,500.
else:
    taxAmount = (givenincome - 1500000) * 0.30 + 187500
# Print the Tax.
print('The tax for the income ', givenincome, '=', taxAmount)

Output:

Enter some random salary = 1200000
The tax for the income 1200000 = 115000.0

Related Programs:

Python Program to Calculate the Income Tax Read More »

Program to Convert Decimal to Binary, Octal and Hexadecimal

Python Program to Convert Decimal to Binary, Octal and Hexadecimal

Decimal System: The decimal system is the most extensively used number system. This is a base ten numbering system. A number is represented by 10 numbers (0-9) in this system.

Binary Number System: The binary number system is a base two number system. Because computers can only understand binary numbers, the binary system is utilized (0 and 1).

Octal system: Octal system is a base 8 numbering system.

Hexadecimal Number System: The Hexadecimal number system is a base 16 number system.

The decimal system is the most extensively used system of numbering. Computers, on the other hand, only understand binary. We may need to translate decimal into binary, octal, or hexadecimal number systems because they are closely connected.

The decimal system is based on base ten (ten symbols, 0-9, are used to represent a number), while binary is based on base 2, octal is based on base 8, and hexadecimal is based on base 16.

Binary numbers have the prefix 0b, octal numbers have the prefix 0o, and hexadecimal numbers have the prefix 0x.

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.

Examples:

Example1:

Input:

Decimal_number=1028

Output:

Printing the values after the conversion of bases that is decimal to binary,octal,hexadecimal:
The binary value of the given decimal number 1028 = 0b10000000100
The octal value of the given decimal number 1028 = 0o2004
The hexadecimal value of the given decimal number 1028 = 0x404

Example2:

Input:

Decimal_number=937238

Output:

Printing the values after the conversion of bases that is decimal to binary,octal,hexadecimal:
The binary value of the given decimal number 937238 = 0b11100100110100010110
The octal value of the given decimal number 937238 = 0o3446426
The hexadecimal value of the given decimal number 937238 = 0xe4d16

Example3:

Input:

Decimal_number=0

Output:

Printing the values after the conversion of bases that is decimal to binary,octal,hexadecimal:
The binary value of the given decimal number 0 = 0b0
The octal value of the given decimal number 0 = 0o0
The hexadecimal value of the given decimal number 0 = 0x0

Program to Convert Decimal to Binary, Octal and Hexadecimal in Python

Python provides different types of built in functions to convert into different number systems like

  1. bin() : To convert the given decimal number to binary number system
  2. hex() : To convert the given decimal number to binary number system
  3. oct()  :To convert the given decimal number to binary number system

We will use the above mentioned functions to convert the given decimal number into binary,octal,hexadecimal number system.

Below is the implementation:

# given number in decimal number system
decimal_Number = 1028
# converting the given decimal_number to binary_number system
# we use bin() function to convert given decimal_number to binary_number system
binValue = bin(decimal_Number)
# converting the given decimal_number to octal_number system
# we use bin() function to convert given decimal_number to binary_number system
octalValue = oct(decimal_Number)
# converting the given decimal_number to hexadecimal_number system
# we use bin() function to convert given decimal_number to binary_number system
hexValue = hex(decimal_Number)
# printing the values after the conversion of bases that is
# decimal to binary,octal,hexadecimal
print("Printing the values after the conversion of bases"
      " that is decimal to binary,octal,hexadecimal:")
# printing the binary converted value
print("The binary value of the given decimal number",
      decimal_Number, "=", binValue)
# printing the octal converted value
print("The octal value of the given decimal number",
      decimal_Number, "=", octalValue)
# printing the hexadecimal converted value
print("The hexadecimal value of the given decimal number",
      decimal_Number, "=", hexValue)

Output:

Printing the values after the conversion of bases that is decimal to binary,octal,hexadecimal:
The binary value of the given decimal number 1028 = 0b10000000100
The octal value of the given decimal number 1028 = 0o2004
The hexadecimal value of the given decimal number 1028 = 0b10000000100

Related Programs:

Python Program to Convert Decimal to Binary, Octal and Hexadecimal Read More »

Program to Calculate Electricity Bill

Python Program to Calculate Electricity Bill

Explore complete java concepts from the Java programming examples and get ready to become a good programmer and crack the java software developer interview with ease.

In this article, we will create a Python program that will assist us in calculating our electricity cost based on the inputs and conditions we provide. Keep in mind that conditions are not constant, as electricity rates vary from location to location. You can create your own program by adjusting the unit cost based on your present area.

Examples:

Example1:

Input:

Given number of units = 176

Output:

The Electricity bill for the units 176 = 1468.4207999999999

Example2:

Input:

Given number of units = 259

Output:

The Electricity bill for the units 259 = 2323.3871999999997

Python Program to Calculate Electricity Bill

Below are the ways to Calculate the Electricity Bill in Python.

Method #1:Using If  Else Statement (Static Input)

Approach:

Give the number of units consumed as static input and store it in a variable.

Here, I’m using the Indian Rupee (Rs) as the currency, and the requirements are as follows:

If the number of units used equals 100, the cost per unit is Rs 3.46.
If the number of units used is greater than 101 and less than 300, the cost per unit is Rs 7.43.
If you consume more than 301 units and less than 500 units, the cost per unit is Rs 10.32.
If the number of units consumed exceeds 501, the cost per unit is Rs 11.71.
The monthly line rent is Rs 1.45 per unit.
The additional fixed meter rent is Rs 100.
The tax on the bill is 16%, which is equal to 0.16.

Using If Else statements we check the conditions and calculate the cost per unit.

After Calculating cost per unit we multiply the number of units by 1.45 and add it to the bill(Adding monthly line rent to the bill)

We add Rs 100 to the bill as additional fixed meter rent.

We multiply the present bill amount by 0.16 (Adding the tax) and add this bill to the past bill.

Print the Final Electricity Bill.

The Exit of the Program.

Below is the Implementation:

# Give the number of units consumed as static input and store it in a variable.
numbOfUnits = 176
# Using If Else statements we check the conditions and calculate the cost per unit.
# If the number of units used equals 100, the cost per unit is Rs 3.46.
if numbOfUnits <= 100:
    totalbill = numbOfUnits * 3.46
# If the number of units used is greater than 101 and less than 300,
# the cost per unit is Rs 7.43.
elif numbOfUnits >= 101 and numbOfUnits <= 300:
    totalbill = 346 + ((numbOfUnits - 100) * 7.43)
# If you consume more than 301 units and less than 500 units,
# the cost per unit is Rs 10.32.
elif numbOfUnits >= 301 and numbOfUnits <= 500:
    totalbill = 346 + 1486 + ((numbOfUnits - 300) * 10.32)
# If the number of units consumed exceeds 501,
# the cost per unit is Rs 11.71.
else:
    totalbill = 346 + 1486 + 2064 + ((numbOfUnits - 500) * 11.71)
# After Calculating cost per unit we multiply the number of units by 1.45 and
# add it to the bill(Adding monthly line rent to the bill)
totalbill = totalbill + (numbOfUnits*1.45)
# We add Rs 100 to the bill as additional fixed meter rent.
totalbill = totalbill + 100
# We multiply the present bill amount by 0.16 (Adding the tax) and add this bill to the past bill.
totalbill = totalbill + (totalbill*0.16)
# Print the Final Electricity Bill.
print("The Electricity bill for the units", numbOfUnits, '=', totalbill)

Output:

The Electricity bill for the units 176 = 1468.4207999999999

Method #2:Using If  Else Statement (User Input)

Approach:

  • Give the number of units consumed as user input using int(input()) and store it in a variable.
  • Calculate the bill using the above method.
  • Using If Else statements we check the conditions and calculate the cost per unit.
  • After Calculating cost per unit we multiply the number of units by 1.45 and add it to the bill(Adding monthly line rent to the bill)
  • We add Rs 100 to the bill as additional fixed meter rent.
  • We multiply the present bill amount by 0.16 (Adding the tax) and add this bill to the past bill.
  • Print the Final Electricity Bill.
  • The Exit of the Program.

Below is the Implementation:

# Give the number of units consumed as static input and store it in a variable.
numbOfUnits = int(input('Enter some random number of units ='))
# Using If Else statements we check the conditions and calculate the cost per unit.
# If the number of units used equals 100, the cost per unit is Rs 3.46.
if numbOfUnits <= 100:
    totalbill = numbOfUnits * 3.46
# If the number of units used is greater than 101 and less than 300,
# the cost per unit is Rs 7.43.
elif numbOfUnits >= 101 and numbOfUnits <= 300:
    totalbill = 346 + ((numbOfUnits - 100) * 7.43)
# If you consume more than 301 units and less than 500 units,
# the cost per unit is Rs 10.32.
elif numbOfUnits >= 301 and numbOfUnits <= 500:
    totalbill = 346 + 1486 + ((numbOfUnits - 300) * 10.32)
# If the number of units consumed exceeds 501,
# the cost per unit is Rs 11.71.
else:
    totalbill = 346 + 1486 + 2064 + ((numbOfUnits - 500) * 11.71)
# After Calculating cost per unit we multiply the number of units by 1.45 and
# add it to the bill(Adding monthly line rent to the bill)
totalbill = totalbill + (numbOfUnits*1.45)
# We add Rs 100 to the bill as additional fixed meter rent.
totalbill = totalbill + 100
# We multiply the present bill amount by 0.16 (Adding the tax) and add this bill to the past bill.
totalbill = totalbill + (totalbill*0.16)
# Print the Final Electricity Bill.
print("The Electricity bill for the units", numbOfUnits, '=', totalbill)

Output:

Enter some random number of units =259
The Electricity bill for the units 259 = 2323.3871999999997

Related Programs:

Python Program to Calculate Electricity Bill Read More »

Program to Find the Sum of Cosine Series

Python Program to Find the Sum of Cosine Series

Are you wondering how to seek help from subject matter experts and learn the Java language? Go with these Basic Java Programming Examples and try to code all of them on your own then check with the exact code provided by expert programmers.

Consider the case where we have a value x and we need to determine the sum of the sine(x) series. There are numerous terms in a cosine(x) series such that

Given n and x, where n is the number of entries in the series and x is the angle in degrees.
Calculate the value of cosine of x using the series expansion formula and compare it to the output of the library function.

cos x = 1 – (x2 / 2 !) + (x4 / 4 !) – (x6 / 6 !) +…

To begin solving the specific series-based problem, we will take the degree as input and convert it to radian. To obtain the sum of the entire number of terms in this series, we shall iterate through all of the given terms and obtain the sum by operations.

Given a number x in degrees and number of terms, the task is to print the sum of cosine series in  python

Examples:

Example1:

Input:

enter the number of degrees = 45
enter number of terms = 10

Output:

The sum of cosine series of  45 degrees of 10 terms = 0.71

Example2:

Input:

enter the number of degrees = 65
enter number of terms = 20

Output:

The sum of cosine series of  65 degrees of 20 terms = 0.42

Python Program to Find the Sum of Cosine Series

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.

1)Printing sum of cosine series (static input)

Approach:

  • Give the degree value of x and the number of terms as static and store them in separate variables.
  • As parameters, pass these values to the cosine function.
  • Create a cosine function and, using a for loop that iterates twice, convert degrees to radians.
  • Then apply the cosine formula expansion to each term and add them to the sum variable.
  • Then print the cosine expansion’s total sum.
  • Exit of program

Below is the implementation:

# importing math module
import math
# function which returns sum of cosine series


def sumCosine(degrees, terms):
  # taking a variable which stores sum of cosine series
    sumCosSeries = 1
    # taking sign variable and initialize it to -1
    signofSequence = -1
    for i in range(2, terms, 2):

        # pie value
        pievalue = 22/7
        # degree value of given number
        degval = degrees*(pievalue/180)
        sumCosSeries = sumCosSeries + \
            (signofSequence*(degval**i))/math.factorial(i)
        # changing the sign by multiplying it with -1
        signofSequence = -1*signofSequence

     # returning the sum of cosine series
    return sumCosSeries


degrees = 45
terms = 10
print("The sum of cosine series of ", degrees, "degrees", "of",
      terms, "terms =", round(sumCosine(degrees, terms), 2))

Output:

The sum of cosine series of  45 degrees of 10 terms = 0.71

Explanation:

  • The user must provide the value of x in degrees and the number of terms or give static input, which will be saved in separate variables.
  • These values are supplied as arguments to the cosine functions.
  • A cosine function is built, and a for loop is used to convert degrees to radians and calculate the values of each term using the sine expansion formula.
  • The sum variable is added to each term.
  • This is repeated until the number of terms equals the number specified by the user.
  • Print the total sum

2)Printing sum of cosine series (User input)

Approach:

  • Scan  the degree value of x and the number of terms using int(input())  and store them in separate variables.
  • As parameters, pass these values to the cosine function.
  • Create a cosine function and, using a for loop that iterates twice, convert degrees to radians.
  • Then apply the cosine formula expansion to each term and add them to the sum variable.
  • Then print the cosine expansion’s total sum.
  • Exit of program

Below is the implementation:

# importing math module
import math
# function which returns sum of cosine series


def sumCosine(degrees, terms):
  # taking a variable which stores sum of cosine series
    sumCosSeries = 1
    # taking sign variable and initialize it to -1
    signofSequence = -1
    for i in range(2, terms, 2):

        # pie value
        pievalue = 22/7
        # degree value of given number
        degval = degrees*(pievalue/180)
        sumCosSeries = sumCosSeries + \
            (signofSequence*(degval**i))/math.factorial(i)
        # changing the sign by multiplying it with -1
        signofSequence = -1*signofSequence

     # returning the sum of cosine series
    return sumCosSeries


degrees = int(input("enter the number of degrees = "))
terms = int(input("enter number of terms = "))
print("The sum of cosine series of ", degrees, "degrees", "of",
      terms, "terms =", round(sumCosine(degrees, terms), 2))

Output:

enter the number of degrees = 65
enter number of terms = 20
The sum of cosine series of 65 degrees of 20 terms = 0.42

Related Programs:

Python Program to Find the Sum of Cosine Series Read More »

Program for Given Two Numbers a and b Find all x Such that a % x = b

Python Program for Given Two Numbers a and b Find all x Such that a % x = b

In the previous article, we have discussed Python Program for Modular Multiplicative Inverse from 1 to n

Given two numbers a, b and the task is to find all x such that given a % x = b

Examples:

Example1:

Input:

Given a value = 21
Given b value = 5

Output:

The value of x such that given a%x==b {a,b = 21 5 } =  2

Explanation:

Here the values of x which satisfy a%x=b are 8,16 because 21%8=5 ,21%16=5.
so total number of possible x are 8,16 i.e 2 values

Example2:

Input:

Given a value = 35
Given b value = 8

Output:

The value of x such that given a%x==b {a,b = 35 8 } =  2

Program for Given two Numbers a and b Find all x Such that a % x = b in Python

Below are the ways to find all x such that given a % x = b in python:

Method #1: Using For Loop (Static Input)

Approach:

  • Import the math module using the import keyword.
  • Give the number as static input and store it in a variable.
  • Give the other number as static input and store it in another variable.
  • Pass the given number two numbers as the arguments to the a_mod_xisb function.
  • Create a function to say a_mod_xisb which takes the given two numbers as the arguments and returns all the values of x such that given a % x = b.
  • Check if the given number a is less than the given b value using the if conditional statement.
  • If it is true then print “There are no solutions possible”.
  • Return.
  • Check if the given a value is equal to the given b value using the if conditional statement.
  • If it is true then print “Infinite Solutions are possible for the equation”.
  • Return.
  • Take a variable say cnt and initialize its value to 0.
  • Subtract the given b value from the given a value and store it in another variable say rslt.
  • Calculate the value of square root of (gvn_a_val – gvn_b_val) using the math.sqrt() function and convert result to an integer using the int() function.
  • Store it in another variable say k.
  • Loop from 1 to the above result k using the for loop.
  • Inside the loop, check if the above value of rslt modulus iterator value is equal to 0 using the if conditional statement.
  • Again check if the rslt divided by the iterator value greater than the given b value using the if conditional statement.
  • If it is true, increment the count value by 1 and store it in the same variable.
  • Check if the iterator value is greater than the given b value using the if conditional statement.
  • If it is true, increment the count value by 1 and store it in the same variable.
  • Check if the k multiplied with itself is equal to the rslt and k greater than the given b value using the if conditional statement.
  • If it is true, decrement the count value by 1 and store it in the same variable.
  • Print the value of x such that given a%x==b.
  • The Exit of the Program.

Below is the implementation:

# Import the math module using the import keyword.
import math

# Create a function to say a_mod_xisb which takes the given two numbers as the arguments
# and returns all the values of x such that given a % x = b.


def a_mod_xisb(gvn_a_val, gvn_b_val):
    # Check if the given number a is less than the given b value using the if conditional
    # statement.

    if (gvn_a_val < gvn_b_val):
      # If it is true then print "There are no solutions possible".
        print("There are no solutions possible")
        # Return.
        return
    # Check if the given a value is equal to the given b value using the if conditional
    # statement.
    if (gvn_a_val == gvn_b_val):
        # If it is true then print "Infinite Solutions are possible for the equation".
        # Return.
        print("Infinite Solutions are possible for the equation")
        return
    # Take a variable say cnt and initialize its value to 0.
    cnt = 0
    # Subtract the given b value from the given a value and store it in another variable
    # say rslt.

    rslt = gvn_a_val - gvn_b_val
    # Calculate the value of square root of (gvn_a_val - gvn_b_val) using the math.sqrt()
    # function and convert result to an integer using the int() function.
    # Store it in another variable say k.
    k = (int)(math.sqrt(gvn_a_val - gvn_b_val))
    # Loop from 1 to the above result k using the for loop.
    for itr in range(1, k+1):
      # Inside the loop, check if the above value of rslt modulus iterator value is equal
      # to 0 using the if conditional statement.
        if (rslt % itr == 0):
          # Again check if the rslt divided by the iterator value greater than the given b value
          # using the if conditional statement.
            if (rslt / itr > gvn_b_val):
              # If it is true, increment the count value by 1 and store it in the same variable.
                cnt = cnt + 1
      # Check if the iterator value is greater than the given b value using the if
          # conditional statement.
            if (itr > gvn_b_val):
                # If it is true, increment the count value by 1 and store it in the same variable.
                cnt = cnt + 1
        # Check if the k multiplied with itself is equal to the rslt and k greater than the
        # given b value using the if conditional statement.
    if (k * k == rslt and k > gvn_b_val):
        # If it is true, decrement the count value by 1 and store it in the same variable.
        cnt = cnt - 1
    # Print the value of x such that given a%x==b.
    print(
        "The value of x such that given a%x==b {a,b =", gvn_a_val, gvn_b_val, "} = ", cnt)


# Give the number as static input and store it in a variable.
gvn_a_val = 15
# Give the other number as static input and store it in another variable.
gvn_b_val = 2
# Pass the given number two numbers as the arguments to the a_mod_xisb function.
a_mod_xisb(gvn_a_val, gvn_b_val)

Output:

The value of x such that given a%x==b {a,b = 15 2 } =  1

Method #2: Using For loop (User Input)

Approach:

  • Import the math module using the import keyword.
  • Give the number as user input using the int(input()) function and store it in a variable.
  • Give the other number as user input using the int(input()) function and store it in another variable.
  • Pass the given number two numbers as the arguments to the a_mod_xisb function.
  • Create a function to say a_mod_xisb which takes the given two numbers as the arguments and returns all the values of x such that given a % x = b.
  • Check if the given number a is less than the given b value using the if conditional statement.
  • If it is true then print “There are no solutions possible”.
  • Return.
  • Check if the given a value is equal to the given b value using the if conditional statement.
  • If it is true then print “Infinite Solutions are possible for the equation”.
  • Return.
  • Take a variable say cnt and initialize its value to 0.
  • Subtract the given b value from the given a value and store it in another variable say rslt.
  • Calculate the value of square root of (gvn_a_val – gvn_b_val) using the math.sqrt() function and convert result to an integer using the int() function.
  • Store it in another variable say k.
  • Loop from 1 to the above result k using the for loop.
  • Inside the loop, check if the above value of rslt modulus iterator value is equal to 0 using the if conditional statement.
  • Again check if the rslt divided by the iterator value greater than the given b value using the if conditional statement.
  • If it is true, increment the count value by 1 and store it in the same variable.
  • Check if the iterator value is greater than the given b value using the if conditional statement.
  • If it is true, increment the count value by 1 and store it in the same variable.
  • Check if the k multiplied with itself is equal to the rslt and k greater than the given b value using the if conditional statement.
  • If it is true, decrement the count value by 1 and store it in the same variable.
  • Print the value of x such that given a%x==b.
  • The Exit of the Program.

Below is the implementation:

# Import the math module using the import keyword.
import math

# Create a function to say a_mod_xisb which takes the given two numbers as the arguments
# and returns all the values of x such that given a % x = b.


def a_mod_xisb(gvn_a_val, gvn_b_val):
    # Check if the given number a is less than the given b value using the if conditional
    # statement.

    if (gvn_a_val < gvn_b_val):
      # If it is true then print "There are no solutions possible".
        print("There are no solutions possible")
        # Return.
        return
    # Check if the given a value is equal to the given b value using the if conditional
    # statement.
    if (gvn_a_val == gvn_b_val):
        # If it is true then print "Infinite Solutions are possible for the equation".
        # Return.
        print("Infinite Solutions are possible for the equation")
        return
    # Take a variable say cnt and initialize its value to 0.
    cnt = 0
    # Subtract the given b value from the given a value and store it in another variable
    # say rslt.

    rslt = gvn_a_val - gvn_b_val
    # Calculate the value of square root of (gvn_a_val - gvn_b_val) using the math.sqrt()
    # function and convert result to an integer using the int() function.
    # Store it in another variable say k.
    k = (int)(math.sqrt(gvn_a_val - gvn_b_val))
    # Loop from 1 to the above result k using the for loop.
    for itr in range(1, k+1):
      # Inside the loop, check if the above value of rslt modulus iterator value is equal
      # to 0 using the if conditional statement.
        if (rslt % itr == 0):
          # Again check if the rslt divided by the iterator value greater than the given b value
          # using the if conditional statement.
            if (rslt / itr > gvn_b_val):
              # If it is true, increment the count value by 1 and store it in the same variable.
                cnt = cnt + 1
      # Check if the iterator value is greater than the given b value using the if
          # conditional statement.
            if (itr > gvn_b_val):
                # If it is true, increment the count value by 1 and store it in the same variable.
                cnt = cnt + 1
        # Check if the k multiplied with itself is equal to the rslt and k greater than the
        # given b value using the if conditional statement.
    if (k * k == rslt and k > gvn_b_val):
        # If it is true, decrement the count value by 1 and store it in the same variable.
        cnt = cnt - 1
    # Print the value of x such that given a%x==b.
    print(
        "The value of x such that given a%x==b {a,b =", gvn_a_val, gvn_b_val, "} = ", cnt)


# Give the number as user input using the int(input()) function and
# store it in a variable.
gvn_a_val = int(input("Enter some random number = "))
# Give the other number as user input using the int(input()) function and
# store it in another variable.
gvn_b_val = int(input("Enter some random number = "))
# Pass the given number two numbers as the arguments to the a_mod_xisb function.
a_mod_xisb(gvn_a_val, gvn_b_val)

Output:

Enter some random number = 35
Enter some random number = 8
The value of x such that given a%x==b {a,b = 35 8 } = 2

Explore more Example Python Programs with output and explanation and practice them for your interviews, assignments and stand out from the rest of the crowd.

Python Program for Given Two Numbers a and b Find all x Such that a % x = b Read More »

Program to Calculate Seed of a Number

Python Program to Calculate Seed of a Number

Guys who are serious about learning the concepts of the java programming language should practice this list of programs in java and get a good grip on it for better results in exams or interviews.

We’ll learn how to find the seed of a number in Python in this article.

Seed of a Number:

If a number x is the seed of a number n, then:

x * the product of x’s digits equals n.

Given a number, the task is to print all the seeds of the given number.

Examples:

Example1:

Input:

Given Number =4977

Output:

79
711

Example2:

Input:

Given Number = 138

Output:

23

Program to Calculate Seed of a Number in Python

Below are the ways to print the seed of a number in Python

Method #1: Using For Loop (Static Input)

Approach:

  • Give the number as static input and store it in a variable.
  • Loop from 1 to given number using the For loop.
  • Check If the iterator value divides the given number leaving remainder 0 or not using the If conditional statement.
  • Convert the given iterator value into list of digits using list(),map(),int() and split() functions.
  • Take a variable proddig and initialize its value to 1.
  • Loop in this digits list using another For loop(Nested For loop).
  • Inside the inner for loop multiply the proddig with the number.
  • After the end of the inner For loop Check if proddig*iterator value is equal to the the given number using the If conditional statement.
  • If it is true then print the iterator value.
  • The Exit of the Program.

Below is the implementation:

# Give the number as static input and store it in a variable.
gvnnumb = 4977
# Loop from 1 to given number using the For loop.
for it in range(1, gvnnumb+1):
        # Check If the iterator value divides the given number
    # leaving remainder 0 or not using the If conditional statement.
    if(gvnnumb % it == 0):
                # Convert the given iterator value into
        # list of digits using list(),map(),int() and split() functions.
        numbdigi = list(map(int, str(it)))
        # Take a variable proddig and initialize its value to 1.
        proddig = 1
        # Loop in this digits list using another For loop(Nested For loop).
        for digit in numbdigi:
                # Inside the inner for loop multiply the proddig with the number.
            proddig = proddig*digit

        # After the end of the inner For loop Check if proddig*iterator

        # value is equal to the the given number using the If conditional statement.
        if(proddig*it == gvnnumb):
            # If it is true then print the iterator value.
            print(it)

Output:

79
711

Explanation:

79 * 7 * 9 = 4977
711*1*1*7=4977

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.
  • Loop from 1 to given number using the For loop.
  • Check If the iterator value divides the given number leaving remainder 0 or not using the If conditional statement.
  • Convert the given iterator value into list of digits using list(),map(),int() and split() functions.
  • Take a variable proddig and initialize its value to 1.
  • Loop in this digits list using another For loop(Nested For loop).
  • Inside the inner for loop multiply the proddig with the number.
  • After the end of the inner For loop Check if proddig*iterator value is equal to the the given number using the If conditional statement.
  • If it is true then print the iterator value.
  • 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.
gvnnumb = int(input('Enter some random number = '))
# Loop from 1 to given number using the For loop.
for it in range(1, gvnnumb+1):
        # Check If the iterator value divides the given number
    # leaving remainder 0 or not using the If conditional statement.
    if(gvnnumb % it == 0):
                # Convert the given iterator value into
        # list of digits using list(),map(),int() and split() functions.
        numbdigi = list(map(int, str(it)))
        # Take a variable proddig and initialize its value to 1.
        proddig = 1
        # Loop in this digits list using another For loop(Nested For loop).
        for digit in numbdigi:
                # Inside the inner for loop multiply the proddig with the number.
            proddig = proddig*digit

        # After the end of the inner For loop Check if proddig*iterator

        # value is equal to the the given number using the If conditional statement.
        if(proddig*it == gvnnumb):
            # If it is true then print the iterator value.
            print(it)

Output:

Enter some random number = 138
23

Explanation:

23*2*3=138

Related Programs:

Python Program to Calculate Seed of a Number Read More »

Program to Compute a Polynomial Equation given that the Coefficients of the Polynomial are stored in a List

Python Program to Compute a Polynomial Equation given that the Coefficients of the Polynomial are stored in a List

Are you new to the java programming language? We recommend you to ace up your practice session with these Basic Java Programs Examples

Given Coefficients of the polynomial and x which are stored in the list, the task is to compute the value of the polynomial equation with given x from the given Coefficients in Python.

Examples:

Example1:

Input:

given coefficient list = [7, 1, 3, 2]

Output:

The total value of the given polynomial 7 x^3 +1 x^2 +3 x +2 with the given value of x=5 is 917

Example2:

Input:

 given coefficient list = [3, 9, 1, 2]

Output:

The total value of the given polynomial 3 x^3 +9 x^2 +1 x +2 with the given value of x 6 = 980

Program to Compute a Polynomial Equation given that the Coefficients of the Polynomial are stored in a List

There are several ways to compute the value of the polynomial equation with given x from the given Coefficients in Python some of them are:

Method #1:Using for and while loop(User Input)

Approach:

  • Import the math module.
  • Take a empty list.
  • Loop from 1 to 4 using for loop as there are 4 coefficients terms in the equation.
  • Scan the coefficient as user input using int(input()) function.
  • Add this to the list using append() function.
  • Scan the value of x as user input using int(input()) function.
  • To compute the value of the polynomial expression for the first three terms, use a for loop and a while loop and store it in a sum variable.
  • To the total variable, add the fourth term.
  • The computed value should be printed.
  • Exit of program.

Below is the implementation:

import math
# Take a empty list.
coefflist = []
# Loop from 1 to 4 using for loop as there are 4 coefficients terms in the equation.
for t in range(4):
    # Scan the coefficient as user input using int(input()) function.
    elemen = int(input('Enter some random coefficient ='))
    # Add this to the list using append() function.
    coefflist.append(elemen)
# Scan the value of x as user input using int(input()) function.
x = int(input('Enter some random value of x ='))
# Taking a variable which stores totalValue and initialize it with 0
totalValue = 0
temp = 3
for k in range(0, 3):
    while(temp > 0):
        totalValue = totalValue+(coefflist[k]*(x**temp))
        # breaking the while looop
        break
    temp = temp-1
# To the total variable, add the fourth term.
totalValue = totalValue+coefflist[3]
print("The total value of the given polynomial " +
      str(coefflist[0])+' x^3 +'+str(coefflist[1])+' x^2 +'+str(coefflist[2])+' x +' +
      str(coefflist[3]), 'with the given value of x=', x, 'is', totalValue)

Output:

Enter some random coefficient =1
Enter some random coefficient =9
Enter some random coefficient =3
Enter some random coefficient =5
Enter some random value of x =8
The total value of the given polynomial 1 x^3 +9 x^2 +3 x +5 with the given value of x= 8 is 1117

Explanation:

  • The math module has been imported.
  • The user must enter the polynomial coefficients, which are saved in a list.
  • In addition, the user must input the value of x.
  • The for loop, which is used to retrieve the coefficients in the list, changes the value of I from 0 to 2.
  • The power for the value of x is determined by the value of j, which varies from 3 to 1.
  • This method is used to compute the values of the first three terms.
  • The final term is added to the total.
  • The final calculated value is printed.

Method #2: Using for and while loop(Static Input)

Approach:

  • Import the math module.
  • Take in the polynomial equation coefficients as static input in given list.
  • Give the value of x as static input.
  • To compute the value of the polynomial expression for the first three terms, use a for loop and a while loop and store it in a sum variable.
  • To the total variable, add the fourth term.
  • The computed value should be printed.
  • Exit of program.

Below is the implementation:

import math
# Take in the polynomial equation coefficients as static input in given list.
coefflist = [7, 1, 3, 2]
# Give the value of x as static input.
x = 5
# Taking a variable which stores totalValue and initialize it with 0
totalValue = 0
temp = 3
for k in range(0, 3):
    while(temp > 0):
        totalValue = totalValue+(coefflist[k]*(x**temp))
        # breaking the while looop
        break
    temp = temp-1
# To the total variable, add the fourth term.
totalValue = totalValue+coefflist[3]
print("The total value of the given polynomial " +
      str(coefflist[0])+' x^3 +'+str(coefflist[1])+' x^2 +'+str(coefflist[2])+' x +' +
      str(coefflist[3]), 'with the given value of x=', x, 'is', totalValue)

Output:

The total value of the given polynomial 7 x^3 +1 x^2 +3 x +2 with the given value of x=5 is 917

Explanation:

  • The for loop, which is used to retrieve the coefficients in the list, changes the value of I from 0 to 2.
  • The power for the value of x is determined by the value of j, which varies from 3 to 1.
  • This method is used to compute the values of the first three terms.
  • The final term is added to the total.
  • The final calculated value is printed.

Related Programs:

Python Program to Compute a Polynomial Equation given that the Coefficients of the Polynomial are stored in a List Read More »

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:

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

Program to Calculate the Average of Numbers in a Given List

Python Program to Calculate the Average of Numbers in a Given List

Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.

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 Calculate the average of all the numbers in the given list in python.

Examples:

Example1:

Input:

given list = [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16]

Output:

The average value of the given list [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16] = 11.0625

Example2:

Input:

given list = [  47 24.5 27 28 11 23 34.8 33 31 29 45 37 39 ]

Output:

The average value of the given list [47.0, 24.5, 27.0, 28.0, 11.0, 23.0, 34.8, 933.0, 31.0, 29.0, 45.0, 37.0, 39.0] = 100.71538461538461

Program to Calculate the Average of Numbers in a Given List in Python

There are several ways to calculate the average of all numbers in the given list 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: Counting sum manually ( Static Input separated by spaces)

Approach:

  • Give the list input as static
  • Take a variable say sumOfList which stores the sum of all list elements and initialize it to 0.
  • Traverse the list using for loop
  • For each iteration add the  iterator value to the sumOfList.
  • Calculate the length of list using len() function.
  • Calculate the average of given list by Dividing sumOfList with length.
  • Print the Average

Below is the implementation:

# given list
given_list = [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16]
# Take a variable say sumOfList which stores the
# sum of all list elements and initialize it to 0.
sumOfList = 0
# Traverse the given list using for loop
for eleme in given_list:
    # Add the iterator value to the sumOfList after each iteration.
    sumOfList = sumOfList+eleme
# calculating the length of given list using len() function
length = len(given_list)
# Calculate the average value of the given list by Dividing sumOfList with length
listAvg = sumOfList/length
# printng the  the average value of the given list
print("The average value of the given list", given_list, "=", listAvg)

Output:

The average value of the given list [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16] = 11.0625

Method #2:Using sum() function ( Static Input separated by spaces)

Approach:

  • Give the list input as static
  • Calculate the sum of list using sum() function and store it in variable sumOfList.
  • Calculate the length of list using len() function.
  • Calculate the average of given list by Dividing sumOfList with length.
  • Print the Average

Below is the implementation:

# given list
given_list = [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16]
# Calculating the sum of list using sum() function and store it in variable sumOfList.
sumOfList = sum(given_list)

# calculating the length of given list using len() function
length = len(given_list)
# Calculate the average value of the given list by Dividing sumOfList with length
listAvg = sumOfList/length
# printng the  the average value of the given list
print("The average value of the given list", given_list, "=", listAvg)

Output:

The average value of the given list [8, 9, 1, 23, 15, 20, 19, 13, 8, 7, 5, 2, 7, 10, 14, 16] = 11.0625

Method #3:Using sum() function ( User Input separated by spaces)

Approach:

  • Scan the list separated by spaces using map, list(),split() and float functions (Because list values can be decimal also).
  • Calculate the sum of list using sum() function and store it in variable sumOfList.
  • Calculate the length of list using len() function.
  • Calculate the average of given list by Dividing sumOfList with length.
  • Print the Average

Below is the implementation:

# Scan the list separated by spaces using map and float functions (Because list values can be decimal also)
given_list =list(map(float,input("Enter some random elements of the list : ").split()))
# Calculating the sum of list using sum() function and store it in variable sumOfList.
sumOfList = sum(given_list)

# calculating the length of given list using len() function
length = len(given_list)
# Calculate the average value of the given list by Dividing sumOfList with length
listAvg = sumOfList/length
# printng the  the average value of the given list
print("The average value of the given list", given_list, "=", listAvg)

Output:

Enter some random elements of the list : 47 24.5 27 28 11 23 34.8 33 31 29 45 37 39
The average value of the given list [47.0, 24.5, 27.0, 28.0, 11.0, 23.0, 34.8, 933.0, 31.0, 29.0, 45.0, 37.0, 39.0] = 100.71538461538461

Explanation :

We used the split function to split the input string separated by spaces, then used the map function to convert all of the strings to floats and placed all of the items in a list.

Related Articles:

Python Program to Calculate the Average of Numbers in a Given List Read More »