在哪里添加while循环以使min和max正常工作

时间:2019-06-02 05:17:20

标签: python python-3.x while-loop

我的问题是不知道如何正确配置此部分编码以使max和min正常工作。

  

“为使最大/最小逻辑正确运行,必须将其放置在   循环,而不是之后。因此,WHILE循环本来是   首选。 (或者正确使用max()和min()方法。)“

我尝试移动包含max和min语句的if语句无济于事。 Python 3.7.3,使用IDLE。

def user_grade(statistic = None):
    f = []
    for grade in range(5):
        if statistic == "max":
            print('Max: {}'.format(max(f)))
        if statistic == "min":
            print('Min: {}'.format(min(f)))
        f.append(float(input("Enter Grade (percentage): ")))

    else:       
        print('Average: {}'.format(sum(f)/len(f)))

预期的输出:(数字将取决于用户输入。)

Enter Grade (percentage): 99
Enter Grade (percentage): 98
Enter Grade (percentage): 97
Enter Grade (percentage): 96
Enter Grade (percentage): 95
Max: 99.0
Average: 97.0
None  #The 'min" should be here instead of None. 

当前输出:

Traceback (most recent call last):
 line 22, in <module>
    print(user_grade('max'))
   line 13, in user_grade
    print('Max: {}'.format(max(f)))
ValueError: max() arg is an empty sequence

2 个答案:

答案 0 :(得分:0)

由于fmax()调用时f.append()是一个空列表,所以您得到一个错误,因此只需将max()部分放在def user_grade(statistic = None): f = [] for grade in range(5): f.append(float(input("Enter Grade (percentage): "))) if statistic == "max": print('Max: {}'.format(max(f))) if statistic == "min": print('Min: {}'.format(min(f))) print('Average: {}'.format(sum(f)/len(f))) 之前。

public class RungeKutta {

public static double NewtonsCoolingLaw(double objectTemp,double  ambientTemp)
     {
         double k = 0.19;       
         return -k * (objectTemp - ambientTemp);
     }

public static void main(String[] args) {

    double result = 0.0;  
    double  initialObjectTemp = 300.0, givenAmbientTemp = 70.0;
    double deltaX = (20.0 - 0)/10000;

    for(double t = 0.0; t <= 20.0; t += .1)
    {        
        double k1 = deltaX * NewtonsLaw(initialObjectTemp,givenAmbientTemp);
        double k2 = deltaX * NewtonsLaw(initialObjectTemp + (deltaX/2.0),givenAmbientTemp + (k1/2.0));
        double k3 = deltaX * NewtonsLaw(initialObjectTemp + (deltaX/2.0), givenAmbientTemp + (k2/2.0));
        double k4 = deltaX * NewtonsLaw(initialObjectTemp + deltaX, givenAmbientTemp + k3);
        givenAmbientTemp = givenAmbientTemp + (1.0/6.0) * (k1 + (2.0 * k2) + (2.0 * k3) + k4);
        result = givenAmbientTemp;
    }       
    System.out.println("The approx. object temp after 20 seconds is: " + result);

}

}

答案 1 :(得分:0)

您编写的代码表示您想要:

def user_grade():
    maximum = 0
    minimum = 100
    total = 0

    for _ in range(5):
        grade = float(input("Enter Grade (percentage): "))

        total += grade

        if grade > maximum:
            maximum = grade

        if grade < minimum:
            minimum = grade

    print('Max: {}'.format(maximum))
    print('Average: {}'.format(total / 5))
    print('Min: {}'.format(minimum))

但是您的预期输出和带引号的文字意味着有所不同:

{{1}}