Skip to main content
 首页 » 编程设计

Python 'For' 循环迭代数组

2024年12月31日14artech

我是 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% 折扣的帮助都会有所帮助。 谢谢

请您参考如下方法:

您编写的代码很接近:

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 并在每次迭代时将其乘以 0.9,从而产生所需的行为。