[英]How to set Python (global?) variable value based on if statement
我正在學習 Python 並編寫一個函數,該函數接受用戶訂閱服務的月數 (months_subscribed) 的數組輸入並基於此計算收入。 收入為每月 7 美元,3 個月的捆綁折扣為 18 美元。 讓我們從輸入 [3,2] 開始,因此預期總收入 (months_value) 應為 $18 + $14 = $32。 我想使用一個循環,以便即使它有更多元素(例如 [3,2,18,0])也可以計算月訂閱。
我的代碼如下:
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()
謝謝!
我認為列表中的 3,2 代表不同的月份,這決定了是否給予折扣。
PS:我也是python的新手,但我想我可以提供幫助
months_subscribed = [3,2]
def subscription_summary(months):
for j in range(0, Len(months)):
if months_subscribed[j] ℅ 3 == 0:
month_value = months_subscribed[j] * 6
month_value += 14
else:
month_value = months_subscribed[j] * 7
month_value += 14
print(month_value)
subscription_summary(months_subscribed)
我的同事幫我解決了這個問題。
關鍵是制作一個包含訂閱月數的空列表,計算收入並使用 append 更新該列表中的收入值,然后返回它們。 這很靈活,因為它適用於任何大小的列表。 它假定months_subscribed 的計數為非負數。
這就是我們所做的:
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)
這將返回:
[18, 14, 0]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.