mardi 9 novembre 2021

How to set Python (global?) variable value based on if statement

I'm learning Python and writing a function that takes an array input of the number of months users subscribed to a service (months_subscribed) and calculates revenue based on this. Revenue is $7 per month, with a bundle discount of $18 for 3 months. Let's start with an input of [3,2], so the expected total revenue (months_value) should be $18 + $14 = $32.

  1. Currently, when I run this months_value gives an output of 35, not 32. It is doing 21 + 14 = 35 and not taking into account the bundle discount. Why is this?
  2. How can months_value be fixed so that it incorporates the bundle discount, and months_value = 35? (I wonder if this involves specifying months_value as a global variable?)
  3. Why do the first values in Print statements 1 & 2 differ? (18, vs 21) I calculate the value of months_value in the if/else statement, so I don't understand why they vary between these two statements.

My code is as follows:

import numpy as np

months_subscribed = [3,2]

def subscription_summary(months_subscribed):

    # 3-month Bundle discount: 3 months for $18, otherwise $7 per month
    for j in range(0,len(months_subscribed)):
        if (months_subscribed[j] % 3 == 0):
            months_value = np.multiply(months_subscribed, 6)
        else:
            months_value = np.multiply(months_subscribed,7)
        print(months_value[j]) # Print statement 1: 18 then 14
    print(months_value)        # Print statement 2: [21 14]
    print(sum(months_value))   # Print statement 3: 35. Expected: 18 + 14 = 32

subscription_summary(months_subscribed)

exit()

Thank you!

Aucun commentaire:

Enregistrer un commentaire