In this post, we will learn how to calculate a percentage in Python by taking input from the user with a very simple explanation but before we jump into the programming part let’s see the formula to find a Percentage.

Formula to find a Percentage

Here the term ‘Obtain‘ refers to the amount you have acquired, while ‘Total‘ represents the overall sum of amounts.

Steps to Calculate a Percentage in Python

1.Ask the user for input of obtain and the total amount.
2.Calculate the percentage using the formula:
percentage = (obtain X 100)/total
3.print the result (print(percentage))

Now we know the steps to calculate a percentage in Python but before writing a program few programming concepts you have to know:

  1. How to take input from the user &
  2. Python arithmetic Operator

Source Code

obtain = float(input("Enter obtained amount: "))
total = float(input("Enter total amount: "))

# Formula
percentage = (obtain * 100) / total

# print the Result
print(f"Your Percentage is : {percentage:.2f}%")

Output

Enter obtained amount: 403
Enter total amount: 600
Your Percentage is : 67.17%

Now let’s modify this program and write it using function.

Calculate a Percentage in Python Using Function

Few programming concepts you have to know before writing this program:

  1. How to take input from the user
  2. Python arithmetic Operator &
  3. Python Functions

Source Code

#function declaration
def percentage_cal(obtain,total):
    return (obtain * 100) / total


obt = float(input("Enter obtained amount: "))
t= float(input("Enter total amount: "))

# call a function
percetage = percentage_cal(obt,t)

# print the Result
print(f"Your Percentage is : {percetage:.2f}%")

Output

Enter obtained amount: 500
Enter total amount: 600
Your Percentage is : 83.33%
Author

Hi, I'm Yagyavendra Tiwari, a computer engineer with a strong passion for programming. I'm excited to share my programming knowledge with everyone here and help educate others in this field.

Write A Comment