'Calculate percentage of a number

I'm trying to find the percentage of a given number, for example, if I wanted to know what is 80% of 100. The answer would be 80.

Here's what I tried so far:

percentage = 80
x = 100

y = percentage * x
decimal = percentage / 100

final = decimal * x

print(final)

Output: 80.0

What would be the better alternatives?



Solution 1:[1]

your equation looked correct

def percentage_of(num, of_num):
    return (num / of_num) * 100

print(percentage_of(50, 100))

find 80 is what percentage of 100

def percentage(num, per):
    return (num * per) / 100


print(percentage(100, 80))
80
print(percentage(101,77))
77.77

I built a function as a better alternative. you may be able to bit shift to get more efficiency for divide

How can I multiply and divide using only bit shifting and adding?

Solution 2:[2]

I would write it as final = (percentage/100)*x. This is shorter and eliminates the extra variable y, which isn't a very informative variable name. Also, putting parentheses around percentage/100 both means that you don't have to worry about what Python's order of operations is, and makes it clearer to anyone reading your code why you're dividing by 100 (i.e., it's because you're dealing with percentages).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Acccumulation