簡體   English   中英

如何根據if語句設置Python(全局?)變量值

[英]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])也可以計算月訂閱。

  1. 目前,當我運行這個months_value 時給出的輸出是35,而不是32。它是21 + 14 = 35,並且沒有考慮捆綁折扣。 為什么是這樣?
  2. 如何固定months_value 以使其包含捆綁折扣,並且months_value = 35? (我想知道這是否涉及將months_value 指定為全局變量?)
  3. 為什么 Print 語句 1 和 2 中的第一個值不同? (18, vs 21) 我在 if/else 語句中計算了months_value 的值,所以我不明白為什么它們在這兩個語句之間有所不同。

我的代碼如下:

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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM