Python Program to Find Percentage of a Number
percentage = (part / total) * 100, for example: percentage = (50 / 200) * 100.Examples
How to Think About It
Algorithm
Code
part = float(input('Enter the part value: ')) total = float(input('Enter the total value: ')) percentage = (part / total) * 100 print(f'Percentage: {percentage}%')
Dry Run
Let's trace the example where part = 50 and total = 200 through the code.
Input part value
User inputs 50, so part = 50.0
Input total value
User inputs 200, so total = 200.0
Calculate percentage
percentage = (50.0 / 200.0) * 100 = 0.25 * 100 = 25.0
Print result
Output is 'Percentage: 25.0%'
| Step | part | total | percentage | Output |
|---|---|---|---|---|
| 1 | 50.0 | - | - | - |
| 2 | 50.0 | 200.0 | - | - |
| 3 | 50.0 | 200.0 | 25.0 | - |
| 4 | 50.0 | 200.0 | 25.0 | Percentage: 25.0% |
Why This Works
Step 1: Divide part by total
Dividing part by total gives the fraction of the whole that the part represents.
Step 2: Multiply by 100
Multiplying the fraction by 100 converts it to a percentage, which is out of 100.
Step 3: Display the result
Printing the result shows the percentage value clearly to the user.
Alternative Approaches
def find_percentage(part, total): return (part / total) * 100 print(f'Percentage: {find_percentage(50, 200)}%')
part = int(input('Enter part: ')) total = int(input('Enter total: ')) percentage = round((part / total) * 100, 2) print(f'Percentage: {percentage}%')
Complexity: O(1) time, O(1) space
Time Complexity
The calculation involves only basic arithmetic operations without loops, so it runs in constant time O(1).
Space Complexity
Only a few variables are used to store inputs and the result, so space complexity is O(1).
Which Approach is Fastest?
All approaches perform the same constant-time calculation; using a function adds readability but no significant overhead.
| Approach | Time | Space | Best For |
|---|---|---|---|
| Direct calculation | O(1) | O(1) | Simple scripts |
| Function-based | O(1) | O(1) | Reusable code |
| Rounded output | O(1) | O(1) | Cleaner display |