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. I want to use a loop so that this can calculate for months_subscribed even if it has more elements, such as [3,2,18,0].
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!
My coworker helped me solve this.
The key is to make an empty list that holds the count of months subscribed, calculate revenue and use append to update the revenue values in that list, and return them. This is flexible as it works for any size list. It assumes the count of months_subscribed is non-negative.
This is what we did:
months_subscribed = [3,2,0] # Expected Revenue Result: [18, 14, 0]
def new_subscription_summary(months_subscribed):
# Make an empty list to hold each subscription's value
values = []
# Loop over each subscription
for this_sub in months_subscribed:
# Start with a price of $7/mo by default
price = 7
# But, if the subscription was for a multiple of 3 months, use the promo price of $6
if this_sub % 3 == 0: price = 6
# Multiply the price per month by the number of months to find the value, and add that to our list
values.append(price * this_sub)
print(values)
# Add up all the values and return
return sum(values)
new_subscription_summary(months_subscribed)
And this returns:
[18, 14, 0]