变量包含0,并且不接受用户输入

时间:2018-12-09 13:12:25

标签: python

我尝试计算学生的几个属性:

  • 学生人数
  • 学生的分数总和
  • 他们获得的最低,平均和最高分数。

但是,变量mark仅显示0。

如何使用函数而不是max()和min()解决此问题?

mark = 0

a = 0
student = 0
a = int(input("Enter Marks :"))

def maxx():
    maxx = 0
    for i in range(1, a):
        if a> maxx :
            maxx = a
    return maxx

def minn():
    minn = 0
    for i in range(1, a):
        if a < minn :
            minn = a
    return minn

while (a >= 0):
    mark = mark + a
    student = student + 1
    a = int(input("Enter Marks :"))

print("Exit")
print("Total students :", student)
print ("The total marks is:", mark)

average = mark/student

print ("The average marks is:", average)
print("The max marks is :", maxx())
print("The min marks is :", minn())

1 个答案:

答案 0 :(得分:0)

您的代码有很多问题。

是其中之一
for i in range(1, a):

如果要最小值或最大值,则此部分没有意义。您需要遍历一个成绩列表。
考虑到可以分别用markstudent代替sumlen,这也是不必要的。
整个代码似乎缺乏适当的结构。这是一个示例实现。如果不允许使用sumlen,则可以带回自己的markstudent方法,但请尽量避免混乱并保持可读性:

def maxx(grades):
    if (not grades): # if empty, we let the caller know 
        return None

    res = grades[0]  # we know the list is not empty

    for i in grades:
        if i > res:
            res = i
    return res

def minn(grades):
    if (not grades):
        return None

    res = grades[0]

    for i in grades:
        if i < res:
            res = i
    return res

def main():
    grades = []  # list of grades

    while (True):
        grade = int(input("Enter Mark: "))
        if (grade < 0): break
        grades.append(grade)

    student_cnt = len(grades)
    total = sum(grades)

    print("Exit")
    print("Total students :", student_cnt)
    print("The total marks is:", total)

    print ("The average marks is:", total / student_cnt)
    print("The max marks is :", maxx(grades))
    print("The min marks is :", minn(grades))


if __name__ == "__main__":
    main()

输入/输出:

Enter Mark:  30
Enter Mark:  20
Enter Mark:  10
Enter Mark:  40
Enter Mark:  -1
Exit
Total students : 4
The total marks is: 100
The average marks is: 25.0
The max marks is : 40
The min marks is : 10