-1

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?

Cassano
  • 253
  • 5
  • 36

2 Answers2

2

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?

Golden Lion
  • 3,840
  • 2
  • 26
  • 35
  • 1
    How is this a "better alternative"? – Sayse May 16 '22 at 20:49
  • 1
    This seems to be a function that takes two numbers and find what percentage one is of the other, rather than taking a number and a percentage and finding that percentage of the number. – Acccumulation May 16 '22 at 20:56
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).

Acccumulation
  • 3,491
  • 1
  • 8
  • 12