Python“ For”循环迭代数组

时间:2018-09-21 20:45:39

标签: python loops

我是python的新手,我正在寻找有关循环结构的帮助,特别是如何使用“ For”循环或替代循环来解决问题。我需要根据数组中前几天的折扣价来计算折扣价,以便它将在数组中进行迭代并应用10%的折扣。这是我到目前为止的内容:

opnDays = ["mon", "tue", "wed", "thr", "fri"]

price = 10

def discount(array):
    for day in array:
        disPrice = price - (price * .1)
        print(day, disPrice)
discount(opnDays)
>>>
mon 9.0
tue 9.0
wed 9.0
thr 9.0
fri 9.0

我想得到:

>>>
mon 9.0
tue 8.1
wed 7.29
thr 6.561
fri 5.9109

任何有关如何组织此循环以获取前一天10%折扣的帮助都将有所帮助。 谢谢

5 个答案:

答案 0 :(得分:1)

您所写的代码已接近:

heroku

我在这里所做的是更改循环中opnDays = ["mon", "tue", "wed", "thr", "fri"] price = 10 def discount(array): disPrice = price for day in array: disPrice *= 0.9 print(day, disPrice) 的设置方式。您在每次迭代中都将其设置为相同的值(disPrice)。我所做的只是在开始时将其设置为0.9 * price,并在每次迭代时将其乘以price,从而获得所需的行为。

答案 1 :(得分:0)

您无需更改string&的值,因此在循环的每次迭代中都会计算出相同的结果。

这应该有效:

price

答案 2 :(得分:0)

如果您要坚持使用代码中的函数,则以下是一种方法:

opnDays = ["mon", "tue", "wed", "thr", "fri"]

price = 10

def discount(array):
    disPrice = price # assign initial price to discount
    for day in array:
        disPrice = disPrice*0.9 # Reduce the discount by 10 percent every time
        print(day, disPrice)

discount(opnDays)

输出

mon 9.0
tue 8.1
wed 7.29
thr 6.561
fri 5.9049000000000005

答案 3 :(得分:0)

您可以使用global并保持逻辑不变

opnDays = ["mon", "tue", "wed", "thr", "fri"]

price = 10
def discount(array):

    global price

    for day in array:
        price = price - (price * .1)
        print(day, price)
discount(opnDays)

为了避免global传递价格作为参数和首选方法

opnDays = ["mon", "tue", "wed", "thr", "fri"]

price = 10
def discount(array,price):

    for day in array:
        price = price - (price * .1)
        print(day, round(price,2))
discount(opnDays,price)

如果您需要在连续迭代后获得最终价格,我认为这可能是您的要求

opnDays = ["mon", "tue", "wed", "thr", "fri"]

price = 10
def discount(array,price):

    for day in array:
        price = price - (price * .1)
        print(day, round(price,2))
    return price
final_price = discount(opnDays,price)
print(final_price)

答案 4 :(得分:0)

您的代码非常接近,但是每天您都需要修改前一天的价格。

我会将起始价格传递给函数,就像传递日期名称列表一样。我还使用了.format,因此我们将价格打印为美元和美分。这只会影响价格的打印方式,不会影响实际价格,因此我们不会失去任何准确性。

我还对您的名称进行了一些更改,以使其符合通常的Python PEP-0008样式。

def discount(array, price):
    for day in array:
        price = price - (price * .1)
        print("{}: {:.2f}".format(day, price))

open_days = ["mon", "tue", "wed", "thr", "fri"]
start_price = 10.00
discount(open_days, start_price)

输出

mon: 9.00
tue: 8.10
wed: 7.29
thr: 6.56
fri: 5.90