【问题标题】:Lists and loops列表和循环
【发布时间】:2021-11-29 19:41:59
【问题描述】:

我必须能够根据每月售出的山羊数量计算每月的收入,因为我知道每个月我售出 20% 的山羊最初在一月份。当我尝试通过我的 price_list 计算时,我只能得到 400 美元,而不是相应月份的 300 美元。

变量 d 用于知道月份是否以元音开头。如果是 d="d'",如果不是 d="de"。

我已经做了一个星期,似乎找不到解决我的两个问题的方法。

非常感谢您的帮助!!!

goats=int(input("Enter the number of goats at the beginning of january :"))
    
    year= ["january","february","march","april","may","june","july","august","september","october","november","december"]
    vowels = "aeiouy"
    price_list = [400,400,400,400,300,300,300,300,300,300,400,400]
    d=""
        
    if goats >0:
        for month in range(len(year)):
            goats_left = int(goats*0.8)
            goats_sold = goats - goats_left
            goats = goats_left
            print("At the of the month of {0} {1}  , we will have {2} goats left, monthly revenu: {3} $".format(d,year[month],goats,price_list[i]))
    else:
        print("The number entered is not valid {0}.format(goats))
        goats=int(input("Enter the number of goats at the beginning of january :"))
    
    
    
    
    print("\n")
    print("ANNUAL REVENUE ........................................................ :".format())
    print(goats_sold_list)

【问题讨论】:

  • 您的代码中有拼写错误和未定义的变量。 goats_sold_list 未定义。 print("The number entered is not valid {0}.format(goats)) 缺少 "price_list[i] 中的 i 未定义。你用vowels做什么?你永远不会设置d

标签: python loops for-loop if-statement


【解决方案1】:

我的第一个建议是使用 enumerate 作为一种更 Python 的方式来遍历您的列表并获取它的索引。我也不明白你在任何地方使用d,所以也许澄清一下你打算如何使用它。

最后,我在任何地方都没有看到 igoats_sold_list 声明。

这应该是改进的起点:

goats = int(input("Enter the number of goats at the beginning of january :"))
    
year = ["january","february","march","april","may","june","july","august","september","october","november","december"]
vowels = "aeiou"
price_list = [400,400,400,400,300,300,300,300,300,300,400,400]
d=""
goats_sold_list = []
    
if goats >0:
    for index, month in enumerate(year):
        #int() always rounds down, i.e 0.8 goes to 0
        goats_left = int(goats*0.8)
        goats_sold = goats - goats_left
        goats = goats_left

        goats_sold_list.append(goats_sold)
        print("At the of the month of {0} {1}  , we will have {2} goats left, monthly revenu: {3} $".format(d,month,goats,price_list[index]))
else:
    print("The number entered is not valid {0}.format(goats)")
    goats=int(input("Enter the number of goats at the beginning of january :"))

print("\n")
print("ANNUAL REVENUE ........................................................ :".format())
print(goats_sold_list)

【讨论】:

    【解决方案2】:

    我在price_list[i] 中没有看到[i] 的定义,除非有一些外部定义,我认为应该是price_list[month]

    我没有看到 d 在任何时候设置,您可能需要根据月份的第一个字母将一些代码行设置 d 到某个值。

    【讨论】:

      猜你喜欢
      • 2012-08-05
      • 2017-02-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多