【问题标题】:Curve grades fx (list operation and loops) python曲线等级 fx(列表操作和循环)python
【发布时间】:2020-11-01 22:09:15
【问题描述】:

我正在尝试将一个 fx 放在一起,让用户输入一个等级列表和曲线的点数。然后,fx 应将“曲线”添加到每个测试分数中,然后返回平均值。在一个 fx 中,我可以询问成绩、amt 曲线,并列出原始成绩并将 amt 的分数添加到每个成绩。在第二个 fx 中,我可以对新列表求和(不包含 sum fx -important),然后获取并返回平均值。是否可以将这些放在一个fx中?对于这个作业,我可以使用 for/while 循环和条件。

1)。取列表并添加点以制作新列表

grades = [int(x) for x in input("Please enter the grades separated by a space").split()]

c = float(input("Please enter the number of points to curve by: "))

new = [ ]

def addcurve(grades, c):
    for n in grades:
        new.append(n+c)
    return new

print(addcurve(grades, c))

[OUT]: [94.0, 45.0, 78.0, 95.0, 60.0, 74.0]

2)。对新列表求和并取平均值

[IN]:
def sumavg(new):
    total_sum = 0
    for n in new:
        total_sum += n  
        gt = len(new)
        final = total_sum/gt
    return "%.2f" %(final)

print("弯曲成绩后的新平均值为", sumavg(new))

[OUT]: The new average after curving the grades is 74.33

如果有人有见解,请告诉我!

谢谢!

干杯,

雷切尔

【问题讨论】:

    标签: python for-loop nested


    【解决方案1】:

    首先,在函数外部声明一个变量是不好的做法,函数用来存储它的操作结果并返回它。相反,在addcurve() 中声明new = []

    其次,你想要的功能是:

    def foo(grades, c):
        total_sum = 0
        for n in grades:
            total_sum += n+c
        final = total_sum/len(grades)
        return "%.2f" %(final)
    

    【讨论】:

    • 感谢您的帮助!至于 fx 之外的变量,这正是我在课堂上看到的。欣赏洞察力!
    • 实际上,如果我没有在 fx 之外定义 new 它就不会存储它
    • 正确的做法是在函数内部定义new = []并返回。要存储结果,您只需像这样调用函数new = addcurve(grades, c),然后调用print(new)。其余部分保持原样。
    猜你喜欢
    • 2018-02-25
    • 1970-01-01
    • 1970-01-01
    • 2022-01-24
    • 1970-01-01
    • 2012-06-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-31
    相关资源
    最近更新 更多