Python: Math – Calculate Percentages and Discounts

Python: Calculate Percentages and Discounts

Python: Calculate Percentages and Discounts

This tutorial demonstrates how to calculate percentages and discounts using Python. We’ll build progressively complex programs to solidify your understanding.

Example 1: Simple Percentage Calculation

Let’s start with a simple example: calculating the percentage of a value. We’ll calculate 20% of 100.


def calculate_percentage(total, percentage):
  """Calculates the percentage of a given total.

  Args:
    total: The total value.
    percentage: The percentage to calculate (as a decimal).

  Returns:
    The calculated percentage amount.
  """
  if not isinstance(total, (int, float)):
    raise TypeError("Total must be a number.")
  if not isinstance(percentage, (int, float)):
    raise TypeError("Percentage must be a number.")
  if percentage  1:
    raise ValueError("Percentage must be between 0 and 1.")

  return total  percentage

# Get input from the user
try:
  total_value = float(input("Enter the total value: "))
  percentage_value = float(input("Enter the percentage (e.g., 20 for 20%): "))
except ValueError:
  print("Invalid input. Please enter numbers only.")
  exit()

# Calculate the percentage
result = calculate_percentage(total_value, percentage_value)

# Print the result
print(f"The percentage of {total_value} at {percentage_value}% is: {result}")

Explanation:

  • We define a function `calculate_percentage` that takes the total value and percentage (as a decimal) as input.
  • We add input validation to ensure that the inputs are numbers and that the percentage is within the valid range (0-1).
  • The function then calculates the percentage by multiplying the total value by the percentage (as a decimal).
  • We get input from the user using the `input()` function and convert it to a floating-point number using `float()`. We use a `try-except` block to handle potential `ValueError` exceptions if the user enters non-numeric input.
  • We call the `calculate_percentage` function with the user’s input and print the result.

Common Mistakes and Corrections:

  • Mistake: Not handling `ValueError` when the user enters non-numeric input. Correction: Use a `try-except` block to catch the `ValueError` and print an error message.
  • Mistake: Using the percentage directly (e.g., 20) instead of a decimal (e.g., 0.20). Correction: The `calculate_percentage` function expects the percentage as a decimal.

Output:


Enter the total value: 100
Enter the percentage (e.g., 20 for 20%): 20
The percentage of 100.0 at 20.0% is: 20.0

Example 2: Calculating Discounted Price

Now, let’s calculate the discounted price of an item given its original price and the discount percentage. We’ll calculate a 10% discount on a price of $50.


def calculate_discounted_price(original_price, discount_percentage):
    """Calculates the discounted price.

    Args:
        original_price: The original price of the item.
        discount_percentage: The discount percentage (as a decimal).

    Returns:
        The discounted price.
    """
    if not isinstance(original_price, (int, float)):
        raise TypeError("Original price must be a number.")
    if not isinstance(discount_percentage, (int, float)):
        raise TypeError("Discount percentage must be a number.")
    if discount_percentage  1:
        raise ValueError("Discount percentage must be between 0 and 1.")

    discount_amount = original_price  discount_percentage
    discounted_price = original_price - discount_amount
    return discounted_price

# Get input from the user
try:
    original_price = float(input("Enter the original price: "))
    discount_percentage = float(input("Enter the discount percentage (e.g., 10 for 10%): "))
except ValueError:
    print("Invalid input. Please enter numbers only.")
    exit()

# Calculate the discounted price
discounted_price = calculate_discounted_price(original_price, discount_percentage)

# Print the result
print(f"The discounted price of ${original_price} at {discount_percentage}% is: ${discounted_price}")

Explanation:

  • We define a function `calculate_discounted_price` to calculate the discounted price.
  • We get input from the user for the original price and discount percentage.
  • We calculate the discount amount by multiplying the original price by the discount percentage.
  • We calculate the discounted price by subtracting the discount amount from the original price.
  • We print the discounted price.

Output:


Enter the original price: 50
Enter the discount percentage (e.g., 10 for 10%): 10
The discounted price of 50.0 at 10.0% is: 45.0

Example 3: Interactive Discount Calculation

Let’s create a more interactive program that prompts the user for the original price, discount percentage, and then calculates and displays the discounted price.


def calculate_discounted_price(original_price, discount_percentage):
    """Calculates the discounted price.

    Args:
        original_price: The original price of the item.
        discount_percentage: The discount percentage (as a decimal).

    Returns:
        The discounted price.
    """
    if not isinstance(original_price, (int, float)):
        raise TypeError("Original price must be a number.")
    if not isinstance(discount_percentage, (int, float)):
        raise TypeError("Discount percentage must be a number.")
    if discount_percentage  1:
        raise ValueError("Discount percentage must be between 0 and 1.")

    discount_amount = original_price  discount_percentage
    discounted_price = original_price - discount_amount
    return discounted_price


# Get input from the user
try:
    original_price = float(input("Enter the original price: "))
    discount_percentage = float(input("Enter the discount percentage (e.g., 10 for 10%): "))
except ValueError:
    print("Invalid input. Please enter numbers only.")
    exit()


# Calculate the discounted price
discounted_price = calculate_discounted_price(original_price, discount_percentage)

# Print the result
print(f"Original Price: ${original_price}")
print(f"Discount Percentage: {discount_percentage}%")
print(f"Discounted Price: ${discounted_price}")

Explanation:

  • This example is similar to the previous one but includes prints to show the original price, discount percentage, and discounted price in a more user-friendly format.

Output:


Enter the original price: 75
Enter the discount percentage (e.g., 10 for 10%): 20
Original Price: $75.0
Discount Percentage: 20.0%
Discounted Price: $60.0

Leave a Reply

Your email address will not be published. Required fields are marked *

We use cookies and similar technologies to enhance your experience on wobizdu.com, analyze site traffic, personalize content, and deliver relevant ads. Some cookies are essential for the site to function, while others help us improve performance and user experience. You may accept all cookies, decline optional ones, or customize your settings. Review our Privacy Policy to learn more.