You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python列表与循环实现山羊月度收入计算问题排查求助

问题修复说明

根因定位

价格取值异常原因

  • 循环内取price_list值时误用了未定义的变量i作为索引,若i之前赋值为0,会始终取列表第一个元素400,需替换为循环变量作为索引
  • 缺失收入计算逻辑:当前直接输出单价,没有乘以当月售卖的山羊数量,实际月度收入=当月售卖量*当月单价
  • 售卖逻辑偏差:现有代码是每月售卖当月存量的20%,和需求「每月固定售出1月初初始山羊存量的20%」不符,需固定售卖量的计算基数

变量d逻辑不生效原因

未实现月份首字母元音判断、给d赋值的相关代码,d全程为空字符串,没有参与逻辑运行

其他语法错误

  • else分支print语句引号未闭合,format方法被写在了字符串内部
  • 最终打印的goats_sold_list没有提前定义,也没有年度收入累加逻辑
  • 打印语句存在拼写错误:At the of应为At the end of

修复后完整代码

# 输入校验,确保初始山羊数量为正
while True:
    goats = int(input("Enter the number of goats at the beginning of january :"))
    if goats > 0:
        break
    print(f"The number entered is not valid {goats}")

# 基础参数定义
goats_initial = goats  # 保存1月初初始存量,用于计算每月固定售卖数量
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]
annual_revenue = 0
goats_sold_list = []

for month_idx in range(len(year)):
    month_name = year[month_idx]
    # 计算当月售卖量:固定为初始存量的20%
    goats_sold = int(goats_initial * 0.2)
    goats_left = goats - goats_sold
    # 计算前缀d
    if month_name[0] in vowels:
        d = "d'"
    else:
        d = "de"
    # 计算当月收入
    month_revenue = goats_sold * price_list[month_idx]
    annual_revenue += month_revenue
    goats_sold_list.append(goats_sold)
    # 打印月度数据
    print(f"At the end of the month of {d} {month_name}, we will have {goats_left} goats left, monthly revenue: {month_revenue} $")
    # 更新剩余山羊数量
    goats = goats_left

# 输出年度汇总
print("\n")
print(f"ANNUAL REVENUE ........................................................ : {annual_revenue} $")
print(goats_sold_list)

内容的提问来源于stack exchange,提问作者HelloWorld

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.30 19:06:03